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"
136 #define _timestamp ({ \
138 gettimeofday(&tv, NULL); \
139 tv.tv_sec * 1000000 + tv.tv_usec; \
142 typedef std::vector<class ProfileTime *> TimeList;
152 ProfileTime(const char *name) :
156 times_.push_back(this);
159 void AddTime(uint64_t time) {
166 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
178 ProfileTimer(ProfileTime &time) :
185 time_.AddTime(_timestamp - start_);
190 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
192 std::cerr << "========" << std::endl;
195 #define _profile(name) { \
196 static ProfileTime name(#name); \
197 ProfileTimer _ ## name(name);
202 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
204 #define CYPoolStart() \
205 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
207 #define CYPoolEnd() \
211 // Hash Functions/Structures {{{
212 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
220 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
222 static _finline NSString *CydiaURL(NSString *path) {
224 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
225 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
226 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
227 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
228 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
230 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
233 static _finline void UpdateExternalStatus(uint64_t newStatus) {
235 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
236 notify_set_state(notify_token, newStatus);
237 notify_cancel(notify_token);
239 notify_post("com.saurik.Cydia.status");
242 /* [NSObject yieldToSelector:(withObject:)] {{{*/
243 @interface NSObject (Cydia)
244 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
245 - (id) yieldToSelector:(SEL)selector;
248 @implementation NSObject (Cydia)
253 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
254 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
255 id object([[context objectAtIndex:1] nonretainedObjectValue]);
256 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
258 /* XXX: deal with exceptions */
259 id value([self performSelector:selector withObject:object]);
261 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
262 [context removeAllObjects];
263 if ([signature methodReturnLength] != 0 && value != nil)
264 [context addObject:value];
269 performSelectorOnMainThread:@selector(doNothing)
275 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
276 volatile bool stopped(false);
278 NSMutableArray *context([NSMutableArray arrayWithObjects:
279 [NSValue valueWithPointer:selector],
280 [NSValue valueWithNonretainedObject:object],
281 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
284 NSThread *thread([[[NSThread alloc]
286 selector:@selector(_yieldToContext:)
292 NSRunLoop *loop([NSRunLoop currentRunLoop]);
293 NSDate *future([NSDate distantFuture]);
294 NSString *mode([loop currentMode] ?: NSDefaultRunLoopMode);
296 while (!stopped && [loop runMode:mode beforeDate:future]);
298 return [context count] == 0 ? nil : [context objectAtIndex:0];
301 - (id) yieldToSelector:(SEL)selector {
302 return [self yieldToSelector:selector withObject:nil];
308 /* Cydia Alert View {{{ */
309 @interface CYAlertView : UIAlertView {
313 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
317 @implementation CYAlertView
319 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
320 if ((self = [super init]) != nil) {
321 [self setTitle:title];
322 [self setDelegate:self];
323 for (NSString *button in buttons) [self addButtonWithTitle:button];
324 [self setCancelButtonIndex:index];
328 - (void) _updateFrameForDisplay {
329 [super _updateFrameForDisplay];
330 if ([self cancelButtonIndex] == -1) {
331 NSArray *buttons = [self buttons];
332 if ([buttons count]) {
333 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
334 for (UIThreePartButton *button in buttons)
335 [button setBackground:background forState:0];
340 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
341 button_ = buttonIndex + 1;
345 [self dismissWithClickedButtonIndex:-1 animated:YES];
348 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
349 [self setRunsModal:YES];
358 /* NSForcedOrderingSearch doesn't work on the iPhone */
359 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
360 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
361 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
363 #define lprintf(args...) fprintf(stderr, args)
366 #define TraceLogging (1 && !ForRelease)
367 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
368 #define ProfileTimes (0 && !ForRelease)
369 #define ForSaurik (0 && !ForRelease)
370 #define LogBrowser (0 && !ForRelease)
371 #define TrackResize (0 && !ForRelease)
372 #define ManualRefresh (1 && !ForRelease)
373 #define ShowInternals (0 && !ForRelease)
374 #define AlwaysReload (0 && !ForRelease)
375 #define TryIndexedCollation (0 && !ForRelease)
379 #define _trace(args...)
384 #define _profile(name) {
387 #define PrintTimes() do {} while (false)
391 typedef uint32_t (*SKRadixFunction)(id, void *);
393 @interface NSMutableArray (Radix)
394 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
402 @implementation NSMutableArray (Radix)
404 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
405 size_t count([self count]);
406 struct RadixItem_ *swap(new RadixItem_[count * 2]);
408 for (size_t i(0); i != count; ++i) {
409 RadixItem_ &item(swap[i]);
412 id object([self objectAtIndex:i]);
413 item.key = function(object, argument);
416 struct RadixItem_ *lhs(swap), *rhs(swap + count);
418 static const size_t width = 32;
419 static const size_t bits = 11;
420 static const size_t slots = 1 << bits;
421 static const size_t passes = (width + (bits - 1)) / bits;
423 size_t *hist(new size_t[slots]);
425 for (size_t pass(0); pass != passes; ++pass) {
426 memset(hist, 0, sizeof(size_t) * slots);
428 for (size_t i(0); i != count; ++i) {
429 uint32_t key(lhs[i].key);
431 key &= _not(uint32_t) >> width - bits;
436 for (size_t i(0); i != slots; ++i) {
437 size_t local(offset);
442 for (size_t i(0); i != count; ++i) {
443 uint32_t key(lhs[i].key);
445 key &= _not(uint32_t) >> width - bits;
446 rhs[hist[key]++] = lhs[i];
449 RadixItem_ *tmp(lhs);
456 const void **values(new const void *[count]);
457 for (size_t i(0); i != count; ++i)
458 values[i] = [self objectAtIndex:lhs[i].index];
459 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
467 /* Insertion Sort {{{ */
469 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
470 const char *ptr = (const char *)list;
472 CFIndex half = count / 2;
473 const char *probe = ptr + elementSize * half;
474 CFComparisonResult cr = comparator(element, probe, context);
475 if (0 == cr) return (probe - (const char *)list) / elementSize;
476 ptr = (cr < 0) ? ptr : probe + elementSize;
477 count = (cr < 0) ? half : (half + (count & 1) - 1);
479 return (ptr - (const char *)list) / elementSize;
482 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
483 const char *ptr = (const char *)list;
485 CFIndex half = count / 2;
486 const char *probe = ptr + elementSize * half;
487 CFComparisonResult cr = comparator(element, probe, context);
488 if (0 == cr) return (probe - (const char *)list) / elementSize;
489 ptr = (cr < 0) ? ptr : probe + elementSize;
490 count = (cr < 0) ? half : (half + (count & 1) - 1);
492 return (ptr - (const char *)list) / elementSize;
495 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
496 if (range.length == 0)
498 const void **values(new const void *[range.length]);
499 CFArrayGetValues(array, range, values);
501 #if HistogramInsertionSort > 0
502 uint32_t total(0), *offsets(new uint32_t[range.length]);
505 for (CFIndex index(1); index != range.length; ++index) {
506 const void *value(values[index]);
507 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
508 CFIndex correct(index);
509 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
510 #if HistogramInsertionSort > 1
511 NSLog(@"%@ < %@", value, values[correct - 1]);
516 if (correct != index) {
517 size_t offset(index - correct);
518 #if HistogramInsertionSort
522 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
524 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
525 values[correct] = value;
529 CFArrayReplaceValues(array, range, values, range.length);
532 #if HistogramInsertionSort > 0
533 for (CFIndex index(0); index != range.length; ++index)
534 if (offsets[index] != 0)
535 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
536 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
543 /* Apple Bug Fixes {{{ */
544 @implementation UIWebDocumentView (Cydia)
546 - (void) _setScrollerOffset:(CGPoint)offset {
547 UIScroller *scroller([self _scroller]);
549 CGSize size([scroller contentSize]);
550 CGSize bounds([scroller bounds].size);
553 max.x = size.width - bounds.width;
554 max.y = size.height - bounds.height;
562 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
563 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
565 [scroller setOffset:offset];
571 @interface NSInvocation (Cydia)
572 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target;
575 @implementation NSInvocation (Cydia)
577 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target {
578 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]]);
579 [invocation setTarget:target];
580 [invocation setSelector:selector];
586 @implementation WebScriptObject (NSFastEnumeration)
588 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
589 size_t length([self count] - state->state);
592 else if (length > count)
594 for (size_t i(0); i != length; ++i)
595 objects[i] = [self objectAtIndex:state->state++];
596 state->itemsPtr = objects;
597 state->mutationsPtr = (unsigned long *) self;
603 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
604 size_t length([self length] - state->state);
607 else if (length > count)
609 for (size_t i(0); i != length; ++i)
610 objects[i] = [self item:state->state++];
611 state->itemsPtr = objects;
612 state->mutationsPtr = (unsigned long *) self;
616 /* Cydia NSString Additions {{{ */
617 @interface NSString (Cydia)
618 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
619 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
620 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
621 - (NSComparisonResult) compareByPath:(NSString *)other;
622 - (NSString *) stringByCachingURLWithCurrentCDN;
623 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
626 @implementation NSString (Cydia)
628 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
629 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
632 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
633 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
634 memcpy(data, bytes, length);
635 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
638 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
639 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
642 - (NSComparisonResult) compareByPath:(NSString *)other {
643 NSString *prefix = [self commonPrefixWithString:other options:0];
644 size_t length = [prefix length];
646 NSRange lrange = NSMakeRange(length, [self length] - length);
647 NSRange rrange = NSMakeRange(length, [other length] - length);
649 lrange = [self rangeOfString:@"/" options:0 range:lrange];
650 rrange = [other rangeOfString:@"/" options:0 range:rrange];
652 NSComparisonResult value;
654 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
655 value = NSOrderedSame;
656 else if (lrange.location == NSNotFound)
657 value = NSOrderedAscending;
658 else if (rrange.location == NSNotFound)
659 value = NSOrderedDescending;
661 value = NSOrderedSame;
663 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
664 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
665 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
666 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
668 NSComparisonResult result = [lpath compare:rpath];
669 return result == NSOrderedSame ? value : result;
672 - (NSString *) stringByCachingURLWithCurrentCDN {
674 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
675 withString:@"://cache.cydia.saurik.com/"
679 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
680 return [(id)CFURLCreateStringByAddingPercentEscapes(
685 kCFStringEncodingUTF8
692 /* C++ NSString Wrapper Cache {{{ */
693 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
694 return size == 0 ? NULL :
695 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
696 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
699 static _finline CFStringRef CYStringCreate(const char *data) {
700 return CYStringCreate(data, strlen(data));
709 _finline void clear_() {
710 if (cache_ != NULL) {
717 _finline bool empty() const {
721 _finline size_t size() const {
725 _finline char *data() const {
729 _finline void clear() {
734 _finline CYString() :
741 _finline ~CYString() {
745 void operator =(const CYString &rhs) {
749 if (rhs.cache_ == nil)
752 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
755 void copy(apr_pool_t *pool) {
756 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
757 memcpy(temp, data_, size_);
762 void set(apr_pool_t *pool, const char *data, size_t size) {
768 data_ = const_cast<char *>(data);
776 _finline void set(apr_pool_t *pool, const char *data) {
777 set(pool, data, data == NULL ? 0 : strlen(data));
780 _finline void set(apr_pool_t *pool, const std::string &rhs) {
781 set(pool, rhs.data(), rhs.size());
784 bool operator ==(const CYString &rhs) const {
785 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
788 _finline operator CFStringRef() {
790 cache_ = CYStringCreate(data_, size_);
794 _finline operator id() {
795 return (NSString *) static_cast<CFStringRef>(*this);
798 _finline operator const char *() {
799 return reinterpret_cast<const char *>(data_);
803 /* C++ NSString Algorithm Adapters {{{ */
805 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
808 struct NSStringMapHash :
809 std::unary_function<NSString *, size_t>
811 _finline size_t operator ()(NSString *value) const {
812 return CFStringHashNSString((CFStringRef) value);
816 struct NSStringMapLess :
817 std::binary_function<NSString *, NSString *, bool>
819 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
820 return [lhs compare:rhs] == NSOrderedAscending;
824 struct NSStringMapEqual :
825 std::binary_function<NSString *, NSString *, bool>
827 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
828 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
829 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
830 //[lhs isEqualToString:rhs];
835 /* Perl-Compatible RegEx {{{ */
845 Pcre(const char *regex) :
850 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
853 lprintf("%d:%s\n", offset, error);
857 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
858 matches_ = new int[(capture_ + 1) * 3];
866 NSString *operator [](size_t match) {
867 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
870 bool operator ()(NSString *data) {
871 // XXX: length is for characters, not for bytes
872 return operator ()([data UTF8String], [data length]);
875 bool operator ()(const char *data, size_t size) {
877 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
881 /* Mime Addresses {{{ */
882 @interface Address : NSObject {
888 - (NSString *) address;
890 - (void) setAddress:(NSString *)address;
892 + (Address *) addressWithString:(NSString *)string;
893 - (Address *) initWithString:(NSString *)string;
897 @implementation Address
906 - (NSString *) name {
910 - (NSString *) address {
914 - (void) setAddress:(NSString *)address {
916 [address_ autorelease];
920 address_ = [address retain];
923 + (Address *) addressWithString:(NSString *)string {
924 return [[[Address alloc] initWithString:string] autorelease];
927 + (NSArray *) _attributeKeys {
928 return [NSArray arrayWithObjects:
934 - (NSArray *) attributeKeys {
935 return [[self class] _attributeKeys];
938 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
939 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
942 - (Address *) initWithString:(NSString *)string {
943 if ((self = [super init]) != nil) {
944 const char *data = [string UTF8String];
945 size_t size = [string length];
947 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
949 if (address_r(data, size)) {
950 name_ = [address_r[1] retain];
951 address_ = [address_r[2] retain];
953 name_ = [string retain];
961 /* CoreGraphics Primitives {{{ */
966 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
967 CGFloat color[] = {red, green, blue, alpha};
968 return CGColorCreate(space, color);
977 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
978 color_(Create_(space, red, green, blue, alpha))
980 Set(space, red, green, blue, alpha);
985 CGColorRelease(color_);
992 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
994 color_ = Create_(space, red, green, blue, alpha);
997 operator CGColorRef() {
1003 /* Random Global Variables {{{ */
1004 static const int PulseInterval_ = 50000;
1006 static const NSString *UI_;
1009 static bool RestartSubstrate_;
1010 static NSArray *Finishes_;
1012 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1013 #define NotifyConfig_ "/etc/notify.conf"
1015 static bool Queuing_;
1017 static CYColor Blue_;
1018 static CYColor Blueish_;
1019 static CYColor Black_;
1020 static CYColor Off_;
1021 static CYColor White_;
1022 static CYColor Gray_;
1023 static CYColor Green_;
1024 static CYColor Purple_;
1025 static CYColor Purplish_;
1027 static UIColor *InstallingColor_;
1028 static UIColor *RemovingColor_;
1030 static NSString *App_;
1032 static BOOL Advanced_;
1033 static BOOL Ignored_;
1035 static UIFont *Font12_;
1036 static UIFont *Font12Bold_;
1037 static UIFont *Font14_;
1038 static UIFont *Font18Bold_;
1039 static UIFont *Font22Bold_;
1041 static const char *Machine_ = NULL;
1042 static NSString *System_ = nil;
1043 static NSString *SerialNumber_ = nil;
1044 static NSString *ChipID_ = nil;
1045 static _H<NSString> Token_;
1046 static NSString *UniqueID_ = nil;
1047 static NSString *PLMN_ = nil;
1048 static NSString *Build_ = nil;
1049 static NSString *Product_ = nil;
1050 static NSString *Safari_ = nil;
1052 static CFLocaleRef Locale_;
1053 static NSArray *Languages_;
1054 static CGColorSpaceRef space_;
1056 static NSDictionary *SectionMap_;
1057 static NSMutableDictionary *Metadata_;
1058 static _transient NSMutableDictionary *Settings_;
1059 static _transient NSString *Role_;
1060 static _transient NSMutableDictionary *Packages_;
1061 static _transient NSMutableDictionary *Sections_;
1062 static _transient NSMutableDictionary *Sources_;
1063 static bool Changed_;
1067 static CGFloat ScreenScale_;
1068 static NSString *Idiom_;
1071 /* Display Helpers {{{ */
1072 inline float Interpolate(float begin, float end, float fraction) {
1073 return (end - begin) * fraction + begin;
1076 static _finline const char *StripVersion_(const char *version) {
1077 const char *colon(strchr(version, ':'));
1078 return colon == NULL ? version : colon + 1;
1081 NSString *LocalizeSection(NSString *section) {
1082 static Pcre title_r("^(.*?) \\((.*)\\)$");
1083 if (title_r(section)) {
1084 NSString *parent(title_r[1]);
1085 NSString *child(title_r[2]);
1087 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1088 LocalizeSection(parent),
1089 LocalizeSection(child)
1093 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1096 NSString *Simplify(NSString *title) {
1097 const char *data = [title UTF8String];
1098 size_t size = [title length];
1100 static Pcre square_r("^\\[(.*)\\]$");
1101 if (square_r(data, size))
1102 return Simplify(square_r[1]);
1104 static Pcre paren_r("^\\((.*)\\)$");
1105 if (paren_r(data, size))
1106 return Simplify(paren_r[1]);
1108 static Pcre title_r("^(.*?) \\((.*)\\)$");
1109 if (title_r(data, size))
1110 return Simplify(title_r[1]);
1116 NSString *GetLastUpdate() {
1117 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1120 return UCLocalize("NEVER_OR_UNKNOWN");
1122 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1123 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1125 CFRelease(formatter);
1127 return [(NSString *) formatted autorelease];
1130 bool isSectionVisible(NSString *section) {
1131 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1132 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1133 return hidden == nil || ![hidden boolValue];
1138 /* Delegate Prototypes {{{ */
1141 @class CydiaProgressEvent;
1143 @protocol DatabaseDelegate
1144 - (void) repairWithSelector:(SEL)selector;
1145 - (void) setConfigurationData:(NSString *)data;
1146 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
1149 @class CYPackageController;
1151 @protocol CydiaDelegate
1152 - (void) retainNetworkActivityIndicator;
1153 - (void) releaseNetworkActivityIndicator;
1154 - (void) clearPackage:(Package *)package;
1155 - (void) installPackage:(Package *)package;
1156 - (void) installPackages:(NSArray *)packages;
1157 - (void) removePackage:(Package *)package;
1158 - (void) beginUpdate;
1160 - (void) distUpgrade;
1162 - (void) updateData;
1164 - (void) addTrivialSource:(NSString *)href;
1165 - (void) showSettings;
1166 - (UIProgressHUD *) addProgressHUD;
1167 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1168 - (CYViewController *) pageForPackage:(NSString *)name;
1169 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1170 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1174 /* ProgressEvent Interface/Delegate {{{ */
1175 @interface CydiaProgressEvent : NSObject {
1176 _H<NSString> message_;
1180 _H<NSString> package_;
1182 _H<NSString> version_;
1185 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type;
1186 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package;
1187 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item;
1189 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type;
1191 - (NSString *) message;
1192 - (NSString *) type;
1195 - (NSString *) package;
1197 - (NSString *) version;
1199 - (void) setItem:(NSArray *)item;
1200 - (void) setPackage:(NSString *)package;
1201 - (void) setURL:(NSString *)url;
1202 - (void) setVersion:(NSString *)version;
1204 - (NSString *) compound:(NSString *)value;
1205 - (NSString *) compoundMessage;
1206 - (NSString *) compoundTitle;
1210 @protocol ProgressDelegate
1211 - (void) addProgressEvent:(CydiaProgressEvent *)event;
1212 - (void) setProgressPercent:(NSNumber *)percent;
1213 - (void) setProgressStatus:(NSDictionary *)status;
1214 - (void) setProgressCancellable:(NSNumber *)cancellable;
1215 - (bool) isProgressCancelled;
1216 - (void) setTitle:(NSString *)title;
1219 /* Status Delegation {{{ */
1221 public pkgAcquireStatus
1224 _transient NSObject<ProgressDelegate> *delegate_;
1234 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1235 delegate_ = delegate;
1238 NSObject<ProgressDelegate> *getDelegate() const {
1242 virtual bool MediaChange(std::string media, std::string drive) {
1246 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1249 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1250 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1251 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:@"STATUS" forItem:item]);
1252 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1255 virtual void Done(pkgAcquire::ItemDesc &item) {
1258 virtual void Fail(pkgAcquire::ItemDesc &item) {
1260 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1261 item.Owner->Status == pkgAcquire::Item::StatDone
1265 std::string &error(item.Owner->ErrorText);
1269 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:@"ERROR" forItem:item]);
1270 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1273 virtual bool Pulse(pkgAcquire *Owner) {
1274 bool value = pkgAcquireStatus::Pulse(Owner);
1277 double(CurrentBytes + CurrentItems) /
1278 double(TotalBytes + TotalItems)
1281 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1282 [NSNumber numberWithDouble:percent], @"Percent",
1284 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1285 [NSNumber numberWithDouble:TotalBytes], @"Total",
1286 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1287 nil] waitUntilDone:YES];
1289 if (value && ![delegate_ isProgressCancelled])
1297 _finline bool WasCancelled() const {
1301 virtual void Start() {
1302 pkgAcquireStatus::Start();
1303 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1306 virtual void Stop() {
1307 pkgAcquireStatus::Stop();
1308 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1309 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1313 /* Database Interface {{{ */
1314 typedef std::map< unsigned long, _H<Source> > SourceMap;
1316 @interface Database : NSObject {
1322 pkgCacheFile cache_;
1323 pkgDepCache::Policy *policy_;
1324 pkgRecords *records_;
1325 pkgProblemResolver *resolver_;
1326 pkgAcquire *fetcher_;
1328 SPtr<pkgPackageManager> manager_;
1329 pkgSourceList *list_;
1331 SourceMap sourceMap_;
1332 NSMutableArray *sourceList_;
1334 CFMutableArrayRef packages_;
1336 _transient NSObject<DatabaseDelegate> *delegate_;
1337 _transient NSObject<ProgressDelegate> *progress_;
1345 std::map<const char *, _H<NSString> > sections_;
1348 + (Database *) sharedInstance;
1351 - (void) _readCydia:(NSNumber *)fd;
1352 - (void) _readStatus:(NSNumber *)fd;
1353 - (void) _readOutput:(NSNumber *)fd;
1357 - (Package *) packageWithName:(NSString *)name;
1359 - (pkgCacheFile &) cache;
1360 - (pkgDepCache::Policy *) policy;
1361 - (pkgRecords *) records;
1362 - (pkgProblemResolver *) resolver;
1363 - (pkgAcquire &) fetcher;
1364 - (pkgSourceList &) list;
1365 - (NSArray *) packages;
1366 - (NSArray *) sources;
1367 - (Source *) sourceWithKey:(NSString *)key;
1368 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1376 - (void) updateWithStatus:(Status &)status;
1378 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1380 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1381 - (NSObject<ProgressDelegate> *) progressDelegate;
1383 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1385 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1389 /* ProgressEvent Implementation {{{ */
1390 @implementation CydiaProgressEvent
1392 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1393 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1396 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1397 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1398 [event setPackage:package];
1402 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1403 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1405 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1406 NSArray *fields([description componentsSeparatedByString:@" "]);
1407 [event setItem:fields];
1409 if ([fields count] > 3) {
1410 [event setPackage:[fields objectAtIndex:2]];
1411 [event setVersion:[fields objectAtIndex:3]];
1414 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1419 + (NSArray *) _attributeKeys {
1420 return [NSArray arrayWithObjects:
1430 - (NSArray *) attributeKeys {
1431 return [[self class] _attributeKeys];
1434 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1435 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1438 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1439 if ((self = [super init]) != nil) {
1445 - (NSString *) message {
1449 - (NSString *) type {
1453 - (NSArray *) item {
1454 return (id) item_ ?: [NSNull null];
1457 - (void) setItem:(NSArray *)item {
1461 - (NSString *) package {
1462 return (id) package_ ?: [NSNull null];
1465 - (void) setPackage:(NSString *)package {
1469 - (NSString *) url {
1470 return (id) url_ ?: [NSNull null];
1473 - (void) setURL:(NSString *)url {
1477 - (void) setVersion:(NSString *)version {
1481 - (NSString *) version {
1482 return (id) version_ ?: [NSNull null];
1485 - (NSString *) compound:(NSString *)value {
1487 NSString *mode(nil); {
1488 NSString *type([self type]);
1489 if ([type isEqualToString:@"ERROR"])
1490 mode = UCLocalize("ERROR");
1491 else if ([type isEqualToString:@"WARNING"])
1492 mode = UCLocalize("WARNING");
1496 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1502 - (NSString *) compoundMessage {
1503 return [self compound:[self message]];
1506 - (NSString *) compoundTitle {
1509 if (package_ == nil)
1511 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1512 title = [package name];
1516 return [self compound:title];
1522 // Cytore Definitions {{{
1523 struct PackageValue :
1526 Cytore::Offset<PackageValue> next_;
1528 uint32_t index_ : 23;
1529 uint32_t subscribed_ : 1;
1546 Cytore::Offset<PackageValue> packages_[1 << 16];
1549 static Cytore::File<MetaValue> MetaFile_;
1551 // Cytore Helper Functions {{{
1552 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1553 SplitHash nhash = { hashlittle(name, length) };
1555 PackageValue *metadata;
1557 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1558 offset: if (offset->IsNull()) {
1559 *offset = MetaFile_.New<PackageValue>(length + 1);
1560 metadata = &MetaFile_.Get(*offset);
1562 if (metadata == NULL) {
1566 metadata = new PackageValue();
1567 memset(metadata, 0, sizeof(*metadata));
1570 memcpy(metadata->name_, name, length + 1);
1571 metadata->nhash_ = nhash.u16[1];
1573 metadata = &MetaFile_.Get(*offset);
1575 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1576 offset = &metadata->next_;
1584 static void PackageImport(const void *key, const void *value, void *context) {
1585 bool &fail(*reinterpret_cast<bool *>(context));
1588 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1589 NSLog(@"failed to import package %@", key);
1593 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1594 NSDictionary *package((NSDictionary *) value);
1596 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1597 if ([subscribed boolValue] && !metadata->subscribed_)
1598 metadata->subscribed_ = true;
1600 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1601 time_t time([date timeIntervalSince1970]);
1602 if (metadata->first_ > time || metadata->first_ == 0)
1603 metadata->first_ = time;
1606 NSDate *date([package objectForKey:@"LastSeen"]);
1607 NSString *version([package objectForKey:@"LastVersion"]);
1609 if (date != nil && version != nil) {
1610 time_t time([date timeIntervalSince1970]);
1611 if (metadata->last_ < time || metadata->last_ == 0)
1612 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1613 size_t length(strlen(buffer));
1614 uint16_t vhash(hashlittle(buffer, length));
1616 size_t capped(std::min<size_t>(8, length));
1617 char *latest(buffer + length - capped);
1619 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1620 metadata->vhash_ = vhash;
1622 metadata->last_ = time;
1628 /* Source Class {{{ */
1629 @interface Source : NSObject {
1630 CYString depiction_;
1631 CYString description_;
1637 CYString distribution_;
1642 _H<NSString> authority_;
1644 CYString defaultIcon_;
1646 _H<NSDictionary> record_;
1650 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1652 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1654 - (NSString *) depictionForPackage:(NSString *)package;
1655 - (NSString *) supportForPackage:(NSString *)package;
1657 - (NSDictionary *) record;
1661 - (NSString *) distribution;
1662 - (NSString *) type;
1664 - (NSString *) host;
1666 - (NSString *) name;
1667 - (NSString *) description;
1668 - (NSString *) label;
1669 - (NSString *) origin;
1670 - (NSString *) version;
1672 - (NSString *) defaultIcon;
1676 @implementation Source
1680 distribution_.clear();
1683 description_.clear();
1689 defaultIcon_.clear();
1697 // XXX: this is a very inefficient way to call these deconstructors
1702 + (NSArray *) _attributeKeys {
1703 return [NSArray arrayWithObjects:
1718 - (NSArray *) attributeKeys {
1719 return [[self class] _attributeKeys];
1722 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1723 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1726 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1729 trusted_ = index->IsTrusted();
1731 uri_.set(pool, index->GetURI());
1732 distribution_.set(pool, index->GetDist());
1733 type_.set(pool, index->GetType());
1735 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1736 if (dindex != NULL) {
1738 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1741 pkgTagFile tags(&fd);
1743 pkgTagSection section;
1750 {"default-icon", &defaultIcon_},
1751 {"depiction", &depiction_},
1752 {"description", &description_},
1754 {"origin", &origin_},
1755 {"support", &support_},
1756 {"version", &version_},
1759 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1760 const char *start, *end;
1762 if (section.Find(names[i].name_, start, end)) {
1763 CYString &value(*names[i].value_);
1764 value.set(pool, start, end - start);
1770 record_ = [Sources_ objectForKey:[self key]];
1772 NSURL *url([NSURL URLWithString:uri_]);
1776 host_ = [host_ lowercaseString];
1779 // XXX: this is due to a bug in _H<>
1780 authority_ = (id) host_;
1782 authority_ = [url path];
1785 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1786 if ((self = [super init]) != nil) {
1787 [self setMetaIndex:index inPool:pool];
1791 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1792 NSDictionary *lhr = [self record];
1793 NSDictionary *rhr = [source record];
1796 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1798 NSString *lhs = [self name];
1799 NSString *rhs = [source name];
1801 if ([lhs length] != 0 && [rhs length] != 0) {
1802 unichar lhc = [lhs characterAtIndex:0];
1803 unichar rhc = [rhs characterAtIndex:0];
1805 if (isalpha(lhc) && !isalpha(rhc))
1806 return NSOrderedAscending;
1807 else if (!isalpha(lhc) && isalpha(rhc))
1808 return NSOrderedDescending;
1811 return [lhs compare:rhs options:LaxCompareOptions_];
1814 - (NSString *) depictionForPackage:(NSString *)package {
1815 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1818 - (NSString *) supportForPackage:(NSString *)package {
1819 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1822 - (NSDictionary *) record {
1830 - (NSString *) uri {
1834 - (NSString *) distribution {
1835 return distribution_;
1838 - (NSString *) type {
1842 - (NSString *) key {
1843 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1846 - (NSString *) host {
1850 - (NSString *) name {
1851 return origin_.empty() ? (id) authority_ : origin_;
1854 - (NSString *) description {
1855 return description_;
1858 - (NSString *) label {
1859 return label_.empty() ? (id) authority_ : label_;
1862 - (NSString *) origin {
1866 - (NSString *) version {
1870 - (NSString *) defaultIcon {
1871 return defaultIcon_;
1876 /* CydiaOperation Class {{{ */
1877 @interface CydiaOperation : NSObject {
1878 NSString *operator_;
1882 - (NSString *) operator;
1883 - (NSString *) value;
1887 @implementation CydiaOperation
1890 [operator_ release];
1895 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1896 if ((self = [super init]) != nil) {
1897 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1898 value_ = [[NSString alloc] initWithUTF8String:value];
1902 + (NSArray *) _attributeKeys {
1903 return [NSArray arrayWithObjects:
1909 - (NSArray *) attributeKeys {
1910 return [[self class] _attributeKeys];
1913 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1914 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1917 - (NSString *) operator {
1921 - (NSString *) value {
1927 /* CydiaClause Class {{{ */
1928 @interface CydiaClause : NSObject {
1930 CydiaOperation *version_;
1933 - (NSString *) package;
1934 - (CydiaOperation *) version;
1938 @implementation CydiaClause
1946 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1947 if ((self = [super init]) != nil) {
1948 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1950 if (const char *version = dep.TargetVer())
1951 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1953 version_ = [[NSNull null] retain];
1957 + (NSArray *) _attributeKeys {
1958 return [NSArray arrayWithObjects:
1964 - (NSArray *) attributeKeys {
1965 return [[self class] _attributeKeys];
1968 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1969 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1972 - (NSString *) package {
1976 - (CydiaOperation *) version {
1982 /* CydiaRelation Class {{{ */
1983 @interface CydiaRelation : NSObject {
1984 NSString *relationship_;
1985 NSMutableArray *clauses_;
1988 - (NSString *) relationship;
1989 - (NSArray *) clauses;
1993 @implementation CydiaRelation
1996 [relationship_ release];
2001 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2002 if ((self = [super init]) != nil) {
2003 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
2004 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
2006 pkgCache::DepIterator start;
2007 pkgCache::DepIterator end;
2008 dep.GlobOr(start, end); // ++dep
2011 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2013 // yes, seriously. (wtf?)
2021 + (NSArray *) _attributeKeys {
2022 return [NSArray arrayWithObjects:
2028 - (NSArray *) attributeKeys {
2029 return [[self class] _attributeKeys];
2032 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2033 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2036 - (NSString *) relationship {
2037 return relationship_;
2040 - (NSArray *) clauses {
2044 - (void) addClause:(CydiaClause *)clause {
2045 [clauses_ addObject:clause];
2050 /* Package Class {{{ */
2051 struct ParsedPackage {
2056 CYString depiction_;
2066 @interface Package : NSObject {
2069 uint32_t essential_ : 1;
2070 uint32_t obsolete_ : 1;
2071 uint32_t ignored_ : 1;
2075 _transient Database *database_;
2077 pkgCache::VerIterator version_;
2078 pkgCache::PkgIterator iterator_;
2079 pkgCache::VerFileIterator file_;
2085 CYString installed_;
2087 const char *section_;
2088 _transient NSString *section$_;
2092 PackageValue *metadata_;
2093 ParsedPackage *parsed_;
2095 NSMutableArray *tags_;
2098 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2099 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2101 - (pkgCache::PkgIterator) iterator;
2104 - (NSString *) section;
2105 - (NSString *) simpleSection;
2107 - (NSString *) longSection;
2108 - (NSString *) shortSection;
2112 - (Address *) maintainer;
2114 - (NSString *) longDescription;
2115 - (NSString *) shortDescription;
2118 - (PackageValue *) metadata;
2121 - (bool) subscribed;
2122 - (bool) setSubscribed:(bool)subscribed;
2126 - (NSString *) latest;
2127 - (NSString *) installed;
2128 - (BOOL) uninstalled;
2131 - (BOOL) upgradableAndEssential:(BOOL)essential;
2134 - (BOOL) unfiltered;
2138 - (BOOL) halfConfigured;
2139 - (BOOL) halfInstalled;
2141 - (NSString *) mode;
2144 - (NSString *) name;
2146 - (NSString *) homepage;
2147 - (NSString *) depiction;
2148 - (Address *) author;
2150 - (NSString *) support;
2152 - (NSArray *) files;
2153 - (NSArray *) warnings;
2154 - (NSArray *) applications;
2156 - (Source *) source;
2158 - (BOOL) matches:(NSString *)text;
2160 - (bool) hasSupportingRole;
2161 - (BOOL) hasTag:(NSString *)tag;
2162 - (NSString *) primaryPurpose;
2163 - (NSArray *) purposes;
2164 - (bool) isCommercial;
2166 - (void) setIndex:(size_t)index;
2168 - (CYString &) cyname;
2170 - (uint32_t) compareBySection:(NSArray *)sections;
2175 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2176 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2177 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2178 - (bool) isVisibleInSection:(NSString *)section;
2179 - (bool) isVisibleInSource:(Source *)source;
2183 uint32_t PackageChangesRadix(Package *self, void *) {
2188 uint32_t timestamp : 30;
2189 uint32_t ignored : 1;
2190 uint32_t upgradable : 1;
2194 bool upgradable([self upgradableAndEssential:YES]);
2195 value.bits.upgradable = upgradable ? 1 : 0;
2198 value.bits.timestamp = 0;
2199 value.bits.ignored = [self ignored] ? 0 : 1;
2200 value.bits.upgradable = 1;
2202 value.bits.timestamp = [self seen] >> 2;
2203 value.bits.ignored = 0;
2204 value.bits.upgradable = 0;
2207 return _not(uint32_t) - value.key;
2210 uint32_t PackagePrefixRadix(Package *self, void *context) {
2211 size_t offset(reinterpret_cast<size_t>(context));
2212 CYString &name([self cyname]);
2214 size_t size(name.size());
2217 char *text(name.data());
2220 if (!isdigit(text[0]))
2224 while (size != digits && isdigit(text[digits]))
2232 if (offset == 0 && zeros != 0) {
2233 memset(data, '0', zeros);
2234 memcpy(data + zeros, text, 4 - zeros);
2236 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2237 if (size <= offset - zeros)
2240 text += offset - zeros;
2241 size -= offset - zeros;
2244 memcpy(data, text, 4);
2246 memcpy(data, text, size);
2247 memset(data + size, 0, 4 - size);
2250 for (size_t i(0); i != 4; ++i)
2251 if (isalpha(data[i]))
2259 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2261 /* XXX: ntohl may be more honest */
2262 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2265 CYString &(*PackageName)(Package *self, SEL sel);
2267 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2268 _profile(PackageNameCompare)
2269 CYString &lhi(PackageName(lhs, @selector(cyname)));
2270 CYString &rhi(PackageName(rhs, @selector(cyname)));
2271 CFStringRef lhn(lhi), rhn(rhi);
2274 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2275 else if (rhn == NULL)
2276 return NSOrderedDescending;
2278 _profile(PackageNameCompare$NumbersLast)
2279 if (!lhi.empty() && !rhi.empty()) {
2280 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2281 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2282 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2283 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2284 return lha ? NSOrderedAscending : NSOrderedDescending;
2288 CFIndex length = CFStringGetLength(lhn);
2290 _profile(PackageNameCompare$Compare)
2291 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2296 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2297 return PackageNameCompare(*lhs, *rhs, context);
2300 struct PackageNameOrdering :
2301 std::binary_function<Package *, Package *, bool>
2303 _finline bool operator ()(Package *lhs, Package *rhs) const {
2304 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2308 @implementation Package
2310 - (NSString *) description {
2311 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2315 if (parsed_ != NULL)
2324 + (NSString *) webScriptNameForSelector:(SEL)selector {
2326 else if (selector == @selector(clear))
2328 else if (selector == @selector(getField:))
2330 else if (selector == @selector(hasTag:))
2332 else if (selector == @selector(install))
2334 else if (selector == @selector(remove))
2340 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2341 return [self webScriptNameForSelector:selector] == nil;
2344 + (NSArray *) _attributeKeys {
2345 return [NSArray arrayWithObjects:
2363 @"shortDescription",
2374 - (NSArray *) attributeKeys {
2375 return [[self class] _attributeKeys];
2378 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2379 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2382 - (NSArray *) relations {
2383 @synchronized (database_) {
2384 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2385 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2386 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2390 - (NSString *) getField:(NSString *)name {
2391 @synchronized (database_) {
2392 if ([database_ era] != era_ || file_.end())
2395 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2397 const char *start, *end;
2398 if (!parser.Find([name UTF8String], start, end))
2399 return (NSString *) [NSNull null];
2401 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2405 if (parsed_ != NULL)
2407 @synchronized (database_) {
2408 if ([database_ era] != era_ || file_.end())
2411 ParsedPackage *parsed(new ParsedPackage);
2414 _profile(Package$parse)
2415 pkgRecords::Parser *parser;
2417 _profile(Package$parse$Lookup)
2418 parser = &[database_ records]->Lookup(file_);
2423 _profile(Package$parse$Find)
2428 {"icon", &parsed->icon_},
2429 {"depiction", &parsed->depiction_},
2430 {"homepage", &parsed->homepage_},
2431 {"website", &website},
2432 {"bugs", &parsed->bugs_},
2433 {"support", &parsed->support_},
2434 {"sponsor", &parsed->sponsor_},
2435 {"author", &parsed->author_},
2438 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2439 const char *start, *end;
2441 if (parser->Find(names[i].name_, start, end)) {
2442 CYString &value(*names[i].value_);
2443 _profile(Package$parse$Value)
2444 value.set(pool_, start, end - start);
2450 _profile(Package$parse$Tagline)
2451 const char *start, *end;
2452 if (parser->ShortDesc(start, end)) {
2453 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2456 while (stop != start && stop[-1] == '\r')
2458 parsed->tagline_.set(pool_, start, stop - start);
2462 _profile(Package$parse$Retain)
2463 if (parsed->homepage_.empty())
2464 parsed->homepage_ = website;
2465 if (parsed->homepage_ == parsed->depiction_)
2466 parsed->homepage_.clear();
2471 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2472 if ((self = [super init]) != nil) {
2473 _profile(Package$initWithVersion)
2476 database_ = database;
2477 era_ = [database era];
2481 pkgCache::PkgIterator iterator(version.ParentPkg());
2482 iterator_ = iterator;
2484 _profile(Package$initWithVersion$Version)
2485 if (!version_.end())
2486 file_ = version_.FileList();
2488 pkgCache &cache([database_ cache]);
2489 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2493 _profile(Package$initWithVersion$Cache)
2494 name_.set(NULL, iterator.Display());
2496 latest_.set(NULL, StripVersion_(version_.VerStr()));
2498 pkgCache::VerIterator current(iterator.CurrentVer());
2500 installed_.set(NULL, StripVersion_(current.VerStr()));
2503 _profile(Package$initWithVersion$Tags)
2504 pkgCache::TagIterator tag(iterator.TagList());
2506 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2508 const char *name(tag.Name());
2509 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2511 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2512 if (strcmp(name + 6, "enduser") == 0)
2514 else if (strcmp(name + 6, "hacker") == 0)
2516 else if (strcmp(name + 6, "developer") == 0)
2518 else if (strcmp(name + 6, "cydia") == 0)
2524 if (strncmp(name, "cydia::", 7) == 0) {
2525 if (strcmp(name + 7, "essential") == 0)
2527 else if (strcmp(name + 7, "obsolete") == 0)
2532 } while (!tag.end());
2536 _profile(Package$initWithVersion$Metadata)
2537 const char *mixed(iterator.Name());
2538 size_t size(strlen(mixed));
2539 char lower[size + 1];
2541 for (size_t i(0); i != size; ++i)
2542 lower[i] = mixed[i] | 0x20;
2545 PackageValue *metadata(PackageFind(lower, size));
2546 metadata_ = metadata;
2548 id_.set(NULL, metadata->name_, size);
2550 const char *latest(version_.VerStr());
2551 size_t length(strlen(latest));
2553 uint16_t vhash(hashlittle(latest, length));
2555 size_t capped(std::min<size_t>(8, length));
2556 latest = latest + length - capped;
2558 if (metadata->first_ == 0)
2559 metadata->first_ = now_;
2561 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2562 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2563 metadata->vhash_ = vhash;
2564 metadata->last_ = now_;
2565 } else if (metadata->last_ == 0)
2566 metadata->last_ = metadata->first_;
2569 _profile(Package$initWithVersion$Section)
2570 section_ = iterator.Section();
2573 _profile(Package$initWithVersion$Flags)
2574 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2575 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2580 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2581 pkgCache::VerIterator version;
2583 _profile(Package$packageWithIterator$GetCandidateVer)
2584 version = [database policy]->GetCandidateVer(iterator);
2592 _profile(Package$packageWithIterator$Allocate)
2593 package = [Package allocWithZone:zone];
2596 _profile(Package$packageWithIterator$Initialize)
2598 initWithVersion:version
2605 _profile(Package$packageWithIterator$Autorelease)
2606 package = [package autorelease];
2612 - (pkgCache::PkgIterator) iterator {
2616 - (NSString *) section {
2617 if (section$_ == nil) {
2618 if (section_ == NULL)
2621 _profile(Package$section$mappedSectionForPointer)
2622 section$_ = [database_ mappedSectionForPointer:section_];
2627 - (NSString *) simpleSection {
2628 if (NSString *section = [self section])
2629 return Simplify(section);
2634 - (NSString *) longSection {
2635 return LocalizeSection([self section]);
2638 - (NSString *) shortSection {
2639 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2642 - (NSString *) uri {
2645 pkgIndexFile *index;
2646 pkgCache::PkgFileIterator file(file_.File());
2647 if (![database_ list].FindIndex(file, index))
2649 return [NSString stringWithUTF8String:iterator_->Path];
2650 //return [NSString stringWithUTF8String:file.Site()];
2651 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2655 - (Address *) maintainer {
2656 @synchronized (database_) {
2657 if ([database_ era] != era_ || file_.end())
2660 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2661 const std::string &maintainer(parser->Maintainer());
2662 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2666 @synchronized (database_) {
2667 if ([database_ era] != era_ || version_.end())
2670 return version_->InstalledSize;
2673 - (NSString *) longDescription {
2674 @synchronized (database_) {
2675 if ([database_ era] != era_ || file_.end())
2678 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2679 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2681 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2682 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2683 if ([lines count] < 2)
2686 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2687 for (size_t i(1), e([lines count]); i != e; ++i) {
2688 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2689 [trimmed addObject:trim];
2692 return [trimmed componentsJoinedByString:@"\n"];
2695 - (NSString *) shortDescription {
2696 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2700 _profile(Package$index)
2701 CFStringRef name((CFStringRef) [self name]);
2702 if (CFStringGetLength(name) == 0)
2704 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2705 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2707 return toupper(character);
2711 - (PackageValue *) metadata {
2716 PackageValue *metadata([self metadata]);
2717 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2720 - (bool) subscribed {
2721 return [self metadata]->subscribed_;
2724 - (bool) setSubscribed:(bool)subscribed {
2725 PackageValue *metadata([self metadata]);
2726 if (metadata->subscribed_ == subscribed)
2728 metadata->subscribed_ = subscribed;
2736 - (NSString *) latest {
2740 - (NSString *) installed {
2744 - (BOOL) uninstalled {
2745 return installed_.empty();
2749 return !version_.end();
2752 - (BOOL) upgradableAndEssential:(BOOL)essential {
2753 _profile(Package$upgradableAndEssential)
2754 pkgCache::VerIterator current(iterator_.CurrentVer());
2756 return essential && essential_;
2758 return !version_.end() && version_ != current;
2762 - (BOOL) essential {
2767 return [database_ cache][iterator_].InstBroken();
2770 - (BOOL) unfiltered {
2771 _profile(Package$unfiltered$obsolete)
2772 if (_unlikely(obsolete_))
2776 _profile(Package$unfiltered$hasSupportingRole)
2777 if (_unlikely(![self hasSupportingRole]))
2785 if (![self unfiltered])
2790 _profile(Package$visible$section)
2791 section = [self section];
2794 _profile(Package$visible$isSectionVisible)
2795 if (!isSectionVisible(section))
2803 unsigned char current(iterator_->CurrentState);
2804 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2807 - (BOOL) halfConfigured {
2808 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2811 - (BOOL) halfInstalled {
2812 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2816 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2817 return state.Mode != pkgDepCache::ModeKeep;
2820 - (NSString *) mode {
2821 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2823 switch (state.Mode) {
2824 case pkgDepCache::ModeDelete:
2825 if ((state.iFlags & pkgDepCache::Purge) != 0)
2829 case pkgDepCache::ModeKeep:
2830 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2831 return @"REINSTALL";
2832 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2836 case pkgDepCache::ModeInstall:
2837 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2838 return @"REINSTALL";
2839 else*/ switch (state.Status) {
2841 return @"DOWNGRADE";
2847 return @"NEW_INSTALL";
2858 - (NSString *) name {
2859 return name_.empty() ? id_ : name_;
2862 - (UIImage *) icon {
2863 NSString *section = [self simpleSection];
2866 if (parsed_ != NULL)
2867 if (NSString *href = parsed_->icon_)
2868 if ([href hasPrefix:@"file:///"])
2869 // XXX: correct escaping
2870 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2871 if (icon == nil) if (section != nil)
2872 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2873 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2874 if ([dicon hasPrefix:@"file:///"])
2875 // XXX: correct escaping
2876 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2878 icon = [UIImage applicationImageNamed:@"unknown.png"];
2882 - (NSString *) homepage {
2883 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2886 - (NSString *) depiction {
2887 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2890 - (Address *) sponsor {
2891 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2894 - (Address *) author {
2895 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2898 - (NSString *) support {
2899 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2902 - (NSArray *) files {
2903 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2904 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2907 fin.open([path UTF8String]);
2912 while (std::getline(fin, line))
2913 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2918 - (NSArray *) warnings {
2919 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2920 const char *name(iterator_.Name());
2922 size_t length(strlen(name));
2923 if (length < 2) invalid:
2924 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2925 else for (size_t i(0); i != length; ++i)
2927 /* XXX: technically this is not allowed */
2928 (name[i] < 'A' || name[i] > 'Z') &&
2929 (name[i] < 'a' || name[i] > 'z') &&
2930 (name[i] < '0' || name[i] > '9') &&
2931 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2934 if (strcmp(name, "cydia") != 0) {
2937 bool _private = false;
2940 bool repository = [[self section] isEqualToString:@"Repositories"];
2942 if (NSArray *files = [self files])
2943 for (NSString *file in files)
2944 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2946 else if (!user && [file isEqualToString:@"/User"])
2948 else if (!_private && [file isEqualToString:@"/private"])
2950 else if (!stash && [file isEqualToString:@"/var/stash"])
2953 /* XXX: this is not sensitive enough. only some folders are valid. */
2954 if (cydia && !repository)
2955 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2957 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2959 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2961 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2964 return [warnings count] == 0 ? nil : warnings;
2967 - (NSArray *) applications {
2968 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2970 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2972 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2973 if (NSArray *files = [self files])
2974 for (NSString *file in files)
2975 if (application_r(file)) {
2976 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2977 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2978 if ([id isEqualToString:me])
2981 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2983 display = application_r[1];
2985 NSString *bundle([file stringByDeletingLastPathComponent]);
2986 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2987 if (icon == nil || [icon length] == 0)
2989 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2991 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2992 [applications addObject:application];
2994 [application addObject:id];
2995 [application addObject:display];
2996 [application addObject:url];
2999 return [applications count] == 0 ? nil : applications;
3002 - (Source *) source {
3003 if (source_ == nil) {
3004 @synchronized (database_) {
3005 if ([database_ era] != era_ || file_.end())
3006 source_ = (Source *) [NSNull null];
3008 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
3012 return source_ == (Source *) [NSNull null] ? nil : source_;
3015 - (BOOL) matches:(NSString *)text {
3021 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
3022 if (range.location != NSNotFound)
3025 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
3026 if (range.location != NSNotFound)
3031 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
3032 if (range.location != NSNotFound)
3038 - (bool) hasSupportingRole {
3043 if ([Role_ isEqualToString:@"User"])
3047 if ([Role_ isEqualToString:@"Hacker"])
3051 if ([Role_ isEqualToString:@"Developer"])
3056 - (BOOL) hasTag:(NSString *)tag {
3057 return tags_ == nil ? NO : [tags_ containsObject:tag];
3060 - (NSString *) primaryPurpose {
3061 for (NSString *tag in tags_)
3062 if ([tag hasPrefix:@"purpose::"])
3063 return [tag substringFromIndex:9];
3067 - (NSArray *) purposes {
3068 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3069 for (NSString *tag in tags_)
3070 if ([tag hasPrefix:@"purpose::"])
3071 [purposes addObject:[tag substringFromIndex:9]];
3072 return [purposes count] == 0 ? nil : purposes;
3075 - (bool) isCommercial {
3076 return [self hasTag:@"cydia::commercial"];
3079 - (void) setIndex:(size_t)index {
3080 if (metadata_->index_ != index)
3081 metadata_->index_ = index;
3084 - (CYString &) cyname {
3085 return name_.empty() ? id_ : name_;
3088 - (uint32_t) compareBySection:(NSArray *)sections {
3089 NSString *section([self section]);
3090 for (size_t i(0), e([sections count]); i != e; ++i) {
3091 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3095 return _not(uint32_t);
3099 @synchronized (database_) {
3100 pkgProblemResolver *resolver = [database_ resolver];
3101 resolver->Clear(iterator_);
3103 pkgCacheFile &cache([database_ cache]);
3104 cache->SetReInstall(iterator_, false);
3105 cache->MarkKeep(iterator_, false);
3109 @synchronized (database_) {
3110 pkgProblemResolver *resolver = [database_ resolver];
3111 resolver->Clear(iterator_);
3112 resolver->Protect(iterator_);
3114 pkgCacheFile &cache([database_ cache]);
3115 cache->SetReInstall(iterator_, false);
3116 cache->MarkInstall(iterator_, false);
3118 pkgDepCache::StateCache &state((*cache)[iterator_]);
3119 if (!state.Install())
3120 cache->SetReInstall(iterator_, true);
3124 @synchronized (database_) {
3125 pkgProblemResolver *resolver = [database_ resolver];
3126 resolver->Clear(iterator_);
3127 resolver->Remove(iterator_);
3128 resolver->Protect(iterator_);
3130 pkgCacheFile &cache([database_ cache]);
3131 cache->SetReInstall(iterator_, false);
3132 cache->MarkDelete(iterator_, true);
3135 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3136 _profile(Package$isUnfilteredAndSearchedForBy)
3139 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3140 value &= [self unfiltered];
3143 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3144 value &= [self matches:search];
3151 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3152 if ([search length] == 0)
3155 _profile(Package$isUnfilteredAndSelectedForBy)
3158 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3159 value &= [self unfiltered];
3162 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3163 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3170 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3171 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3174 - (bool) isVisibleInSection:(NSString *)name {
3175 NSString *section([self section]);
3179 section == nil && [name length] == 0 ||
3180 [name isEqualToString:section]
3181 ) && [self visible];
3184 - (bool) isVisibleInSource:(Source *)source {
3185 return [self source] == source && [self visible];
3190 /* Section Class {{{ */
3191 @interface Section : NSObject {
3196 NSString *localized_;
3199 - (NSComparisonResult) compareByLocalized:(Section *)section;
3200 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3201 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3202 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3203 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3204 - (NSString *) name;
3211 - (void) addToCount;
3213 - (void) setCount:(size_t)count;
3214 - (NSString *) localized;
3218 @implementation Section
3222 if (localized_ != nil)
3223 [localized_ release];
3227 - (NSComparisonResult) compareByLocalized:(Section *)section {
3228 NSString *lhs(localized_);
3229 NSString *rhs([section localized]);
3231 /*if ([lhs length] != 0 && [rhs length] != 0) {
3232 unichar lhc = [lhs characterAtIndex:0];
3233 unichar rhc = [rhs characterAtIndex:0];
3235 if (isalpha(lhc) && !isalpha(rhc))
3236 return NSOrderedAscending;
3237 else if (!isalpha(lhc) && isalpha(rhc))
3238 return NSOrderedDescending;
3241 return [lhs compare:rhs options:LaxCompareOptions_];
3244 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3245 if ((self = [self initWithName:name localize:NO]) != nil) {
3246 if (localized != nil)
3247 localized_ = [localized retain];
3251 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3252 return [self initWithName:name row:0 localize:localize];
3255 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3256 if ((self = [super init]) != nil) {
3257 name_ = [name retain];
3261 localized_ = [LocalizeSection(name_) retain];
3265 /* XXX: localize the index thingees */
3266 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3267 if ((self = [super init]) != nil) {
3268 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3274 - (NSString *) name {
3294 - (void) addToCount {
3298 - (void) setCount:(size_t)count {
3302 - (NSString *) localized {
3309 static NSString *Colon_;
3310 static NSString *Elision_;
3311 static NSString *Error_;
3312 static NSString *Warning_;
3314 /* Database Implementation {{{ */
3315 @implementation Database
3317 + (Database *) sharedInstance {
3318 static Database *instance;
3319 if (instance == nil)
3320 instance = [[Database alloc] init];
3328 - (void) releasePackages {
3329 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3330 CFArrayRemoveAllValues(packages_);
3334 // XXX: actually implement this thing
3336 [sourceList_ release];
3337 [self releasePackages];
3338 apr_pool_destroy(pool_);
3339 NSRecycleZone(zone_);
3343 - (void) _readCydia:(NSNumber *)fd { _pooled
3344 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3345 std::istream is(&ib);
3348 static Pcre finish_r("^finish:([^:]*)$");
3350 while (std::getline(is, line)) {
3351 const char *data(line.c_str());
3352 size_t size = line.size();
3353 lprintf("C:%s\n", data);
3355 if (finish_r(data, size)) {
3356 NSString *finish = finish_r[1];
3357 int index = [Finishes_ indexOfObject:finish];
3358 if (index != INT_MAX && index > Finish_)
3366 - (void) _readStatus:(NSNumber *)fd { _pooled
3367 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3368 std::istream is(&ib);
3371 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3372 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3374 while (std::getline(is, line)) {
3375 const char *data(line.c_str());
3376 size_t size(line.size());
3377 lprintf("S:%s\n", data);
3379 if (conffile_r(data, size)) {
3380 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3381 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3382 } else if (strncmp(data, "status: ", 8) == 0) {
3383 // status: <package>: {unpacked,half-configured,installed}
3384 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:@"STATUS"]);
3385 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3386 } else if (strncmp(data, "processing: ", 12) == 0) {
3387 // processing: configure: config-test
3388 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:@"STATUS"]);
3389 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3390 } else if (pmstatus_r(data, size)) {
3391 std::string type([pmstatus_r[1] UTF8String]);
3393 NSString *package = pmstatus_r[2];
3394 if ([package isEqualToString:@"dpkg-exec"])
3397 float percent([pmstatus_r[3] floatValue]);
3398 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3400 NSString *string = pmstatus_r[4];
3402 if (type == "pmerror") {
3403 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"ERROR" forPackage:package]);
3404 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3405 } else if (type == "pmstatus") {
3406 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"STATUS" forPackage:package]);
3407 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3408 } else if (type == "pmconffile")
3409 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3411 lprintf("E:unknown pmstatus\n");
3413 lprintf("E:unknown status\n");
3419 - (void) _readOutput:(NSNumber *)fd { _pooled
3420 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3421 std::istream is(&ib);
3424 while (std::getline(is, line)) {
3425 lprintf("O:%s\n", line.c_str());
3427 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:@"INFORMATION"]);
3428 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3438 - (Package *) packageWithName:(NSString *)name {
3439 @synchronized (self) {
3440 if (static_cast<pkgDepCache *>(cache_) == NULL)
3442 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3443 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3447 if ((self = [super init]) != nil) {
3454 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3455 apr_pool_create(&pool_, NULL);
3457 size_t capacity(MetaFile_->active_);
3463 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3464 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3468 _assert(pipe(fds) != -1);
3471 _config->Set("APT::Keep-Fds::", cydiafd_);
3472 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3475 detachNewThreadSelector:@selector(_readCydia:)
3477 withObject:[NSNumber numberWithInt:fds[0]]
3480 _assert(pipe(fds) != -1);
3484 detachNewThreadSelector:@selector(_readStatus:)
3486 withObject:[NSNumber numberWithInt:fds[0]]
3489 _assert(pipe(fds) != -1);
3490 _assert(dup2(fds[0], 0) != -1);
3491 _assert(close(fds[0]) != -1);
3493 input_ = fdopen(fds[1], "a");
3495 _assert(pipe(fds) != -1);
3496 _assert(dup2(fds[1], 1) != -1);
3497 _assert(close(fds[1]) != -1);
3500 detachNewThreadSelector:@selector(_readOutput:)
3502 withObject:[NSNumber numberWithInt:fds[0]]
3507 - (pkgCacheFile &) cache {
3511 - (pkgDepCache::Policy *) policy {
3515 - (pkgRecords *) records {
3519 - (pkgProblemResolver *) resolver {
3523 - (pkgAcquire &) fetcher {
3527 - (pkgSourceList &) list {
3531 - (NSArray *) packages {
3532 return (NSArray *) packages_;
3535 - (NSArray *) sources {
3539 - (Source *) sourceWithKey:(NSString *)key {
3540 for (Source *source in [self sources]) {
3541 if ([[source key] isEqualToString:key])
3546 - (bool) popErrorWithTitle:(NSString *)title {
3549 while (!_error->empty()) {
3551 bool warning(!_error->PopMessage(error));
3556 size_t size(error.size());
3557 if (size == 0 || error[size - 1] != '\n')
3559 error.resize(size - 1);
3562 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3564 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3570 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3571 return [self popErrorWithTitle:title] || !success;
3574 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3575 @synchronized (self) {
3578 [self releasePackages];
3581 [sourceList_ removeAllObjects];
3601 apr_pool_clear(pool_);
3603 NSRecycleZone(zone_);
3604 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3606 int chk(creat("/tmp/cydia.chk", 0644));
3610 if (invocation != nil)
3611 [invocation invoke];
3613 NSString *title(UCLocalize("DATABASE"));
3616 OpProgress progress;
3617 while (!cache_.Open(progress, true)) { pop:
3619 bool warning(!_error->PopMessage(error));
3620 lprintf("cache_.Open():[%s]\n", error.c_str());
3622 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3623 [delegate_ repairWithSelector:@selector(configure)];
3624 else if (error == "The package lists or status file could not be parsed or opened.")
3625 [delegate_ repairWithSelector:@selector(update)];
3626 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3627 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3628 // else if (error == "Malformed Status line")
3629 // else if (error == "The list of sources could not be read.")
3631 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3641 unlink("/tmp/cydia.chk");
3643 now_ = [[NSDate date] timeIntervalSince1970];
3645 policy_ = new pkgDepCache::Policy();
3646 records_ = new pkgRecords(cache_);
3647 resolver_ = new pkgProblemResolver(cache_);
3648 fetcher_ = new pkgAcquire(&status_);
3651 list_ = new pkgSourceList();
3652 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3655 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3656 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:@"ERROR"] forTask:title];
3660 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3663 if (cache_->BrokenCount() != 0) {
3664 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3667 if (cache_->BrokenCount() != 0) {
3668 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:@"ERROR"] forTask:title];
3672 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3676 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3677 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3678 [sourceList_ addObject:object];
3680 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3681 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3682 // XXX: this could be more intelligent
3683 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3684 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3686 sourceMap_[cached->ID] = object;
3691 /*std::vector<Package *> packages;
3692 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3693 [packages_ release];
3698 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3699 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3700 //packages.push_back(package);
3701 CFArrayAppendValue(packages_, [package retain]);
3705 /*if (packages.empty())
3706 packages_ = [[NSArray alloc] init];
3708 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3711 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3712 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3713 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3721 /*if (!packages.empty())
3722 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3723 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3725 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3727 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3729 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3733 size_t count(CFArrayGetCount(packages_));
3734 MetaFile_->active_ = count;
3736 for (size_t index(0); index != count; ++index)
3737 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3741 } } CYPoolEnd() _trace(); }
3744 @synchronized (self) {
3746 resolver_ = new pkgProblemResolver(cache_);
3748 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3749 if (!cache_[iterator].Keep())
3750 cache_->MarkKeep(iterator, false);
3751 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3752 cache_->SetReInstall(iterator, false);
3755 - (void) configure {
3756 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3758 system([dpkg UTF8String]);
3763 // XXX: I don't remember this condition
3768 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3770 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3772 if ([self popErrorWithTitle:title])
3776 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3779 public pkgArchiveCleaner
3782 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3787 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3794 fetcher_->Shutdown();
3796 pkgRecords records(cache_);
3798 lock_ = new FileFd();
3799 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3801 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3803 if ([self popErrorWithTitle:title])
3807 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3810 manager_ = (_system->CreatePM(cache_));
3811 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3818 bool substrate(RestartSubstrate_);
3819 RestartSubstrate_ = false;
3821 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3823 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3825 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3827 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3828 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3831 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3833 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3835 [self popErrorWithTitle:title];
3839 bool failed = false;
3840 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3841 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3843 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3849 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3857 RestartSubstrate_ = true;
3860 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3862 if (_error->PendingError()) {
3867 if (result == pkgPackageManager::Failed) {
3872 if (result != pkgPackageManager::Completed) {
3877 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3879 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3881 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3882 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3885 if (![before isEqualToArray:after])
3890 NSString *title(UCLocalize("UPGRADE"));
3891 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3897 [self updateWithStatus:status_];
3900 - (void) updateWithStatus:(Status &)status {
3901 NSString *title(UCLocalize("REFRESHING_DATA"));
3904 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3908 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3909 if ([self popErrorWithTitle:title])
3912 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3914 bool success(ListUpdate(status, list, PulseInterval_));
3915 if (status.WasCancelled())
3918 [self popErrorWithTitle:title forOperation:success];
3920 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3922 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3926 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3927 delegate_ = delegate;
3930 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3931 progress_ = delegate;
3932 status_.setDelegate(delegate);
3935 - (NSObject<ProgressDelegate> *) progressDelegate {
3939 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3940 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3941 return i == sourceMap_.end() ? nil : i->second;
3944 - (NSString *) mappedSectionForPointer:(const char *)section {
3945 _H<NSString> *mapped;
3947 _profile(Database$mappedSectionForPointer$Cache)
3948 mapped = §ions_[section];
3951 if (*mapped == NULL) {
3952 size_t length(strlen(section));
3953 char spaced[length + 1];
3955 _profile(Database$mappedSectionForPointer$Replace)
3956 for (size_t index(0); index != length; ++index)
3957 spaced[index] = section[index] == '_' ? ' ' : section[index];
3958 spaced[length] = '\0';
3963 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3964 string = [NSString stringWithUTF8String:spaced];
3967 _profile(Database$mappedSectionForPointer$Map)
3968 string = [SectionMap_ objectForKey:string] ?: string;
3978 /* Web Scripting {{{ */
3979 @interface CydiaObject : NSObject {
3981 _transient id delegate_;
3984 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3988 @implementation CydiaObject
3991 [indirect_ release];
3995 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3996 if ((self = [super init]) != nil) {
3997 indirect_ = [indirect retain];
4001 - (void) setDelegate:(id)delegate {
4002 delegate_ = delegate;
4005 + (NSArray *) _attributeKeys {
4006 return [NSArray arrayWithObjects:
4021 - (NSArray *) attributeKeys {
4022 return [[self class] _attributeKeys];
4025 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4026 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4029 - (NSString *) version {
4033 - (NSString *) device {
4034 return [[UIDevice currentDevice] uniqueIdentifier];
4037 - (NSString *) firmware {
4038 return [[UIDevice currentDevice] systemVersion];
4041 - (NSString *) hostname {
4042 return [[UIDevice currentDevice] name];
4045 - (NSString *) idiom {
4046 return (id) Idiom_ ?: [NSNull null];
4049 - (NSString *) plmn {
4050 return (id) PLMN_ ?: [NSNull null];
4053 - (NSString *) ecid {
4054 return (id) ChipID_ ?: [NSNull null];
4057 - (NSString *) serial {
4058 return SerialNumber_;
4061 - (NSString *) role {
4062 return (id) Role_ ?: [NSNull null];
4065 - (NSString *) model {
4066 return [NSString stringWithUTF8String:Machine_];
4069 - (NSString *) token {
4070 return (id) Token_ ?: [NSNull null];
4073 + (NSString *) webScriptNameForSelector:(SEL)selector {
4075 else if (selector == @selector(addTrivialSource:))
4076 return @"addTrivialSource";
4077 else if (selector == @selector(close))
4079 else if (selector == @selector(du:))
4081 else if (selector == @selector(stringWithFormat:arguments:))
4083 else if (selector == @selector(getAllSources))
4084 return @"getAllSourcs";
4085 else if (selector == @selector(getKernelNumber:))
4086 return @"getKernelNumber";
4087 else if (selector == @selector(getKernelString:))
4088 return @"getKernelString";
4089 else if (selector == @selector(getInstalledPackages))
4090 return @"getInstalledPackages";
4091 else if (selector == @selector(getPackageById:))
4092 return @"getPackageById";
4093 else if (selector == @selector(installPackages:))
4094 return @"installPackages";
4095 else if (selector == @selector(localizedStringForKey:value:table:))
4097 else if (selector == @selector(refreshSources))
4098 return @"refreshSources";
4099 else if (selector == @selector(removeButton))
4100 return @"removeButton";
4101 else if (selector == @selector(substitutePackageNames:))
4102 return @"substitutePackageNames";
4103 else if (selector == @selector(scrollToBottom:))
4104 return @"scrollToBottom";
4105 else if (selector == @selector(setAllowsNavigationAction:))
4106 return @"setAllowsNavigationAction";
4107 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4108 return @"setButtonImage";
4109 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4110 return @"setButtonTitle";
4111 else if (selector == @selector(setHidesBackButton:))
4112 return @"setHidesBackButton";
4113 else if (selector == @selector(setHidesNavigationBar:))
4114 return @"setHidesNavigationBar";
4115 else if (selector == @selector(setNavigationBarStyle:))
4116 return @"setNavigationBarStyle";
4117 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4118 return @"setNavigationBarTintColor";
4119 else if (selector == @selector(setPopupHook:))
4120 return @"setPopupHook";
4121 else if (selector == @selector(setToken:))
4123 else if (selector == @selector(setViewportWidth:))
4124 return @"setViewportWidth";
4125 else if (selector == @selector(statfs:))
4127 else if (selector == @selector(supports:))
4133 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4134 return [self webScriptNameForSelector:selector] == nil;
4137 - (BOOL) supports:(NSString *)feature {
4138 return [feature isEqualToString:@"window.open"];
4141 - (NSNumber *) getKernelNumber:(NSString *)name {
4142 const char *string([name UTF8String]);
4145 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4146 return (id) [NSNull null];
4148 if (size != sizeof(int))
4149 return (id) [NSNull null];
4152 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4153 return (id) [NSNull null];
4155 return [NSNumber numberWithInt:value];
4158 - (NSString *) getKernelString:(NSString *)name {
4159 const char *string([name UTF8String]);
4162 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4163 return (id) [NSNull null];
4165 char value[size + 1];
4166 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4167 return (id) [NSNull null];
4169 // XXX: just in case you request something ludicrous
4172 return [NSString stringWithCString:value];
4175 - (void) addTrivialSource:(NSString *)href {
4176 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4179 - (void) refreshSources {
4180 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4183 - (NSArray *) getAllSources {
4184 return [[Database sharedInstance] sources];
4187 - (NSArray *) getInstalledPackages {
4188 Database *database([Database sharedInstance]);
4189 @synchronized (database) {
4190 NSArray *packages([database packages]);
4191 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4192 for (Package *package in packages)
4193 if (![package uninstalled])
4194 [installed addObject:package];
4198 - (Package *) getPackageById:(NSString *)id {
4199 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4203 return (Package *) [NSNull null];
4206 - (NSArray *) statfs:(NSString *)path {
4209 if (path == nil || statfs([path UTF8String], &stat) == -1)
4212 return [NSArray arrayWithObjects:
4213 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4214 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4215 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4219 - (NSNumber *) du:(NSString *)path {
4220 NSNumber *value(nil);
4223 _assert(pipe(fds) != -1);
4225 pid_t pid(ExecFork());
4227 _assert(dup2(fds[1], 1) != -1);
4228 _assert(close(fds[0]) != -1);
4229 _assert(close(fds[1]) != -1);
4230 /* XXX: this should probably not use du */
4231 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4236 _assert(close(fds[1]) != -1);
4238 if (FILE *du = fdopen(fds[0], "r")) {
4240 while (fgets(line, sizeof(line), du) != NULL) {
4241 size_t length(strlen(line));
4242 while (length != 0 && line[length - 1] == '\n')
4243 line[--length] = '\0';
4244 if (char *tab = strchr(line, '\t')) {
4246 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4251 } else _assert(close(fds[0]));
4255 if (waitpid(pid, &status, 0) == -1)
4258 else _assert(false);
4264 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4267 - (void) installPackages:(NSArray *)packages {
4268 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4271 - (NSString *) substitutePackageNames:(NSString *)message {
4272 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4273 for (size_t i(0), e([words count]); i != e; ++i) {
4274 NSString *word([words objectAtIndex:i]);
4275 if (Package *package = [[Database sharedInstance] packageWithName:word])
4276 [words replaceObjectAtIndex:i withObject:[package name]];
4279 return [words componentsJoinedByString:@" "];
4282 - (void) removeButton {
4283 [indirect_ removeButton];
4286 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4287 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4290 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4291 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4294 - (void) setAllowsNavigationAction:(NSString *)value {
4295 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4298 - (void) setHidesBackButton:(NSString *)value {
4299 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4302 - (void) setHidesNavigationBar:(NSString *)value {
4303 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4306 - (void) setNavigationBarStyle:(NSString *)value {
4307 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4310 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4311 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4312 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4313 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4316 - (void) _setToken:(NSString *)token {
4320 [Metadata_ removeObjectForKey:@"Token"];
4322 [Metadata_ setObject:Token_ forKey:@"Token"];
4327 - (void) setToken:(NSString *)token {
4328 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4331 - (void) setPopupHook:(id)function {
4332 [indirect_ setPopupHook:function];
4335 - (void) scrollToBottom:(NSNumber *)animated {
4336 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4339 - (void) setViewportWidth:(float)width {
4340 [indirect_ setViewportWidthOnMainThread:width];
4343 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4344 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4345 unsigned count([arguments count]);
4347 for (unsigned i(0); i != count; ++i)
4348 values[i] = [arguments objectAtIndex:i];
4349 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4352 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4353 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4355 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4357 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4363 /* @ Loading... Indicator {{{ */
4364 @interface CYLoadingIndicator : UIView {
4365 _H<UIActivityIndicatorView> spinner_;
4367 _H<UIView> container_;
4370 @property (readonly, nonatomic) UILabel *label;
4371 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4375 @implementation CYLoadingIndicator
4377 - (id) initWithFrame:(CGRect)frame {
4378 if ((self = [super initWithFrame:frame]) != nil) {
4379 container_ = [[[UIView alloc] init] autorelease];
4380 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4382 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4383 [spinner_ startAnimating];
4384 [container_ addSubview:spinner_];
4386 label_ = [[[UILabel alloc] init] autorelease];
4387 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4388 [label_ setBackgroundColor:[UIColor clearColor]];
4389 [label_ setTextColor:[UIColor blackColor]];
4390 [label_ setShadowColor:[UIColor whiteColor]];
4391 [label_ setShadowOffset:CGSizeMake(0, 1)];
4392 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4393 [container_ addSubview:label_];
4395 CGSize viewsize = frame.size;
4396 CGSize spinnersize = [spinner_ bounds].size;
4397 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4398 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4400 CGRect containrect = {
4401 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4402 CGSizeMake(bothwidth, spinnersize.height)
4405 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4413 [container_ setFrame:containrect];
4414 [spinner_ setFrame:spinrect];
4415 [label_ setFrame:textrect];
4416 [self addSubview:container_];
4420 - (UILabel *) label {
4424 - (UIActivityIndicatorView *) activityIndicatorView {
4430 /* Emulated Loading Controller {{{ */
4431 @interface CYEmulatedLoadingController : CYViewController {
4432 _transient Database *database_;
4433 _H<CYLoadingIndicator> indicator_;
4434 _H<UITabBar> tabbar_;
4435 _H<UINavigationBar> navbar_;
4440 @implementation CYEmulatedLoadingController
4442 - (id) initWithDatabase:(Database *)database {
4443 if ((self = [super init]) != nil) {
4444 database_ = database;
4448 // XXX: factor this out somewhere
4449 - (UIColor *) groupTableViewBackgroundColor {
4450 UIDevice *device([UIDevice currentDevice]);
4451 bool iPad([device respondsToSelector:@selector(userInterfaceIdiom)] && [device userInterfaceIdiom] == UIUserInterfaceIdiomPad);
4452 return iPad ? [UIColor colorWithRed:0.821 green:0.834 blue:0.860 alpha:1] : [UIColor groupTableViewBackgroundColor];
4456 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4457 [[self view] setBackgroundColor:[self groupTableViewBackgroundColor]];
4459 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4460 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4461 [[self view] addSubview:indicator_];
4463 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4464 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4465 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4466 [[self view] addSubview:tabbar_];
4468 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4469 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4470 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4471 [[self view] addSubview:navbar_];
4474 - (void) releaseSubviews {
4483 /* Cydia Browser Controller {{{ */
4484 @interface CYBrowserController : BrowserController {
4485 CydiaObject *cydia_;
4490 @implementation CYBrowserController
4497 - (NSURL *) navigationURL {
4498 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4501 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4504 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4505 [super webView:view didClearWindowObject:window forFrame:frame];
4507 WebDataSource *source([frame dataSource]);
4508 NSURLResponse *response([source response]);
4510 NSURL *url([response URL]);
4511 NSString *scheme([url scheme]);
4512 NSString *host([url host]);
4514 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4515 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4516 NSDictionary *headers([http allHeaderFields]);
4517 [self setHeaders:headers forHost:host];
4521 [host isEqualToString:@"cydia.saurik.com"] ||
4522 [host hasSuffix:@".cydia.saurik.com"] ||
4523 [scheme isEqualToString:@"file"]
4525 [window setValue:cydia_ forKey:@"cydia"];
4528 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4529 if (System_ != NULL)
4530 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4531 if (Machine_ != NULL)
4532 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4534 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4536 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4539 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4540 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4541 [self _setMoreHeaders:copy];
4545 - (void) setDelegate:(id)delegate {
4546 [super setDelegate:delegate];
4547 [cydia_ setDelegate:delegate];
4551 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4552 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4554 WebView *webview([[webview_ _documentView] webView]);
4556 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4559 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4561 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4562 if (Product_ != nil)
4563 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4565 [webview setApplicationNameForUserAgent:application];
4573 @interface NSObject (CydiaScript)
4574 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4577 @implementation NSObject (CydiaScript)
4579 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4585 @implementation NSArray (CydiaScript)
4587 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4588 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4589 for (size_t i(0), e([self count]); i != e; ++i)
4590 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4596 @implementation NSDictionary (CydiaScript)
4598 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4599 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4601 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4608 /* Confirmation Controller {{{ */
4609 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4610 if (!iterator.end())
4611 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4612 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4614 pkgCache::PkgIterator package(dep.TargetPkg());
4617 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4624 @protocol ConfirmationControllerDelegate
4625 - (void) cancelAndClear:(bool)clear;
4626 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4630 @interface ConfirmationController : CYBrowserController {
4631 _transient Database *database_;
4633 UIAlertView *essential_;
4635 NSDictionary *changes_;
4636 NSMutableArray *issues_;
4637 NSDictionary *sizes_;
4642 - (id) initWithDatabase:(Database *)database;
4646 @implementation ConfirmationController
4653 if (essential_ != nil)
4654 [essential_ release];
4661 RestartSubstrate_ = true;
4662 [delegate_ confirmWithNavigationController:[self navigationController]];
4665 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4666 NSString *context([alert context]);
4668 if ([context isEqualToString:@"remove"]) {
4669 if (button == [alert cancelButtonIndex])
4670 [self dismissModalViewControllerAnimated:YES];
4671 else if (button == [alert firstOtherButtonIndex]) {
4675 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4676 } else if ([context isEqualToString:@"unable"]) {
4677 [self dismissModalViewControllerAnimated:YES];
4678 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4680 [super alertView:alert clickedButtonAtIndex:button];
4684 - (void) _doContinue {
4685 [self dismissModalViewControllerAnimated:YES];
4686 [delegate_ cancelAndClear:NO];
4689 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4690 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4694 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4695 [super webView:view didClearWindowObject:window forFrame:frame];
4697 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4698 changes_, @"changes",
4702 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4705 - (id) initWithDatabase:(Database *)database {
4706 if ((self = [super init]) != nil) {
4707 database_ = database;
4709 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4710 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4711 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4712 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4713 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4717 pkgCacheFile &cache([database_ cache]);
4718 NSArray *packages([database_ packages]);
4719 pkgDepCache::Policy *policy([database_ policy]);
4721 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4723 for (Package *package in packages) {
4724 pkgCache::PkgIterator iterator([package iterator]);
4725 NSString *name([package id]);
4727 if ([package broken]) {
4728 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4730 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4732 reasons, @"reasons",
4735 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4739 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4740 pkgCache::DepIterator start;
4741 pkgCache::DepIterator end;
4742 dep.GlobOr(start, end); // ++dep
4744 if (!cache->IsImportantDep(end))
4746 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4749 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4751 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4752 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4753 clauses, @"clauses",
4757 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4759 pkgCache::PkgIterator target(start.TargetPkg());
4760 if (target->ProvidesList != 0)
4761 reason = @"missing";
4763 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4765 reason = @"installed";
4766 installed = [NSString stringWithUTF8String:ver.VerStr()];
4767 } else if (!cache[target].CandidateVerIter(cache).end())
4768 reason = @"uninstalled";
4769 else if (target->ProvidesList == 0)
4770 reason = @"uninstallable";
4772 reason = @"virtual";
4775 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4776 [NSString stringWithUTF8String:start.CompType()], @"operator",
4777 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4780 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4781 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4782 version, @"version",
4784 installed, @"installed",
4787 // yes, seriously. (wtf?)
4795 pkgDepCache::StateCache &state(cache[iterator]);
4797 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4799 if (state.NewInstall())
4800 [installs addObject:name];
4801 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4802 [reinstalls addObject:name];
4803 else if (state.Upgrade())
4804 [upgrades addObject:name];
4805 else if (state.Downgrade())
4806 [downgrades addObject:name];
4807 else if (!state.Delete())
4809 else if (special_r(name))
4810 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4811 [NSNull null], @"package",
4812 [NSArray arrayWithObjects:
4813 [NSDictionary dictionaryWithObjectsAndKeys:
4814 @"Conflicts", @"relationship",
4815 [NSArray arrayWithObjects:
4816 [NSDictionary dictionaryWithObjectsAndKeys:
4818 [NSNull null], @"version",
4819 @"installed", @"reason",
4826 if ([package essential])
4828 [removes addObject:name];
4831 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4832 substrate_ |= DepSubstrate(iterator.CurrentVer());
4837 else if (Advanced_) {
4838 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4840 essential_ = [[UIAlertView alloc]
4841 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4842 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4844 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4846 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4850 [essential_ setContext:@"remove"];
4852 essential_ = [[UIAlertView alloc]
4853 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4854 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4856 cancelButtonTitle:UCLocalize("OKAY")
4857 otherButtonTitles:nil
4860 [essential_ setContext:@"unable"];
4863 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4864 installs, @"installs",
4865 reinstalls, @"reinstalls",
4866 upgrades, @"upgrades",
4867 downgrades, @"downgrades",
4868 removes, @"removes",
4871 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4872 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4873 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4876 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4878 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4879 initWithTitle:UCLocalize("CANCEL")
4880 style:UIBarButtonItemStylePlain
4882 action:@selector(cancelButtonClicked)
4888 - (void) applyRightButton {
4889 if ([issues_ count] == 0 && ![self isLoading])
4890 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4891 initWithTitle:UCLocalize("CONFIRM")
4892 style:UIBarButtonItemStyleDone
4894 action:@selector(confirmButtonClicked)
4897 [[self navigationItem] setRightBarButtonItem:nil];
4901 - (void) cancelButtonClicked {
4902 [self dismissModalViewControllerAnimated:YES];
4903 [delegate_ cancelAndClear:YES];
4907 - (void) confirmButtonClicked {
4908 if (essential_ != nil)
4918 /* Progress Data {{{ */
4919 @interface CydiaProgressData : NSObject {
4920 _transient id delegate_;
4929 _H<NSMutableArray> events_;
4930 _H<NSString> title_;
4932 _H<NSString> status_;
4933 _H<NSString> finish_;
4938 @implementation CydiaProgressData
4940 + (NSArray *) _attributeKeys {
4941 return [NSArray arrayWithObjects:
4953 - (NSArray *) attributeKeys {
4954 return [[self class] _attributeKeys];
4957 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4958 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4962 if ((self = [super init]) != nil) {
4963 events_ = [NSMutableArray arrayWithCapacity:32];
4967 - (void) setDelegate:(id)delegate {
4968 delegate_ = delegate;
4971 - (void) setPercent:(float)value {
4975 - (NSNumber *) percent {
4976 return [NSNumber numberWithFloat:percent_];
4979 - (void) setCurrent:(float)value {
4983 - (NSNumber *) current {
4984 return [NSNumber numberWithFloat:current_];
4987 - (void) setTotal:(float)value {
4991 - (NSNumber *) total {
4992 return [NSNumber numberWithFloat:total_];
4995 - (void) setSpeed:(float)value {
4999 - (NSNumber *) speed {
5000 return [NSNumber numberWithFloat:speed_];
5003 - (NSArray *) events {
5007 - (void) removeAllEvents {
5008 [events_ removeAllObjects];
5011 - (void) addEvent:(CydiaProgressEvent *)event {
5012 [events_ addObject:event];
5015 - (void) setTitle:(NSString *)text {
5019 - (NSString *) title {
5023 - (void) setFinish:(NSString *)text {
5027 - (NSString *) finish {
5028 return (id) finish_ ?: [NSNull null];
5031 - (void) setRunning:(bool)running {
5035 - (NSNumber *) running {
5036 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5041 /* Progress Controller {{{ */
5042 @interface ProgressController : CYBrowserController <
5045 _transient Database *database_;
5046 _H<CydiaProgressData> progress_;
5050 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5052 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5054 - (void) setTitle:(NSString *)title;
5055 - (void) setCancellable:(bool)cancellable;
5059 @implementation ProgressController
5062 [database_ setProgressDelegate:nil];
5063 [progress_ setDelegate:nil];
5067 - (void) updateCancel {
5068 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5069 initWithTitle:UCLocalize("CANCEL")
5070 style:UIBarButtonItemStylePlain
5072 action:@selector(cancel)
5073 ] autorelease] : nil)];
5076 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5077 if ((self = [super init]) != nil) {
5078 database_ = database;
5079 delegate_ = delegate;
5081 [database_ setProgressDelegate:self];
5083 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5084 [progress_ setDelegate:self];
5086 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5088 [scroller_ setBackgroundColor:[UIColor blackColor]];
5090 [[self navigationItem] setHidesBackButton:YES];
5092 [self updateCancel];
5096 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5097 [super webView:view didClearWindowObject:window forFrame:frame];
5098 [window setValue:progress_ forKey:@"cydiaProgress"];
5101 - (void) updateProgress {
5102 [self dispatchEvent:@"CydiaProgressUpdate"];
5105 - (void) viewWillAppear:(BOOL)animated {
5106 if (![self hasLoaded])
5107 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5109 [super viewWillAppear:animated];
5113 UpdateExternalStatus(0);
5120 [delegate_ terminateWithSuccess];
5121 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5122 [delegate_ suspendWithAnimation:YES];
5124 [delegate_ suspend];*/
5136 system("/usr/bin/sbreload");
5142 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5143 SBReboot(SBSSpringBoardServerPort());
5145 reboot2(RB_AUTOBOOT);
5152 - (void) setTitle:(NSString *)title {
5153 [progress_ setTitle:title];
5154 [self updateProgress];
5157 - (UIBarButtonItem *) rightButton {
5158 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5159 initWithTitle:UCLocalize("CLOSE")
5160 style:UIBarButtonItemStylePlain
5162 action:@selector(close)
5166 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5167 UpdateExternalStatus(1);
5169 [progress_ setRunning:true];
5170 [self setTitle:title];
5171 // implicit updateProgress
5173 SHA1SumValue notifyconf; {
5175 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5178 MMap mmap(file, MMap::ReadOnly);
5180 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5181 notifyconf = sha1.Result();
5185 SHA1SumValue springlist; {
5187 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5190 MMap mmap(file, MMap::ReadOnly);
5192 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5193 springlist = sha1.Result();
5197 if (invocation != nil) {
5198 [invocation yieldToSelector:@selector(invoke)];
5199 [self setTitle:@"COMPLETE"];
5204 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5207 MMap mmap(file, MMap::ReadOnly);
5209 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5210 if (!(notifyconf == sha1.Result()))
5217 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5220 MMap mmap(file, MMap::ReadOnly);
5222 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5223 if (!(springlist == sha1.Result()))
5229 if (RestartSubstrate_)
5233 RestartSubstrate_ = false;
5236 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5237 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5238 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5239 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5240 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5244 system("su -c /usr/bin/uicache mobile");
5247 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5249 [progress_ setRunning:false];
5250 [self updateProgress];
5252 [self applyRightButton];
5255 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5256 [progress_ addEvent:event];
5257 [self updateProgress];
5260 - (bool) isProgressCancelled {
5261 return cancel_ == 2;
5266 [self updateCancel];
5269 - (void) setCancellable:(bool)cancellable {
5270 unsigned cancel(cancel_);
5274 else if (cancel_ == 0)
5277 if (cancel != cancel_)
5278 [self updateCancel];
5281 - (void) setProgressCancellable:(NSNumber *)cancellable {
5282 [self setCancellable:[cancellable boolValue]];
5285 - (void) setProgressPercent:(NSNumber *)percent {
5286 [progress_ setPercent:[percent floatValue]];
5287 [self updateProgress];
5290 - (void) setProgressStatus:(NSDictionary *)status {
5291 if (status == nil) {
5292 [progress_ setCurrent:0];
5293 [progress_ setTotal:0];
5294 [progress_ setSpeed:0];
5296 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5298 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5299 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5300 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5303 [self updateProgress];
5309 /* Cell Content View {{{ */
5310 @protocol ContentDelegate
5311 - (void) drawContentRect:(CGRect)rect;
5314 @interface ContentView : UIView {
5315 _transient id<ContentDelegate> delegate_;
5320 @implementation ContentView
5322 - (id) initWithFrame:(CGRect)frame {
5323 if ((self = [super initWithFrame:frame]) != nil) {
5324 [self setNeedsDisplayOnBoundsChange:YES];
5328 - (void) setDelegate:(id<ContentDelegate>)delegate {
5329 delegate_ = delegate;
5332 - (void) drawRect:(CGRect)rect {
5333 [super drawRect:rect];
5334 [delegate_ drawContentRect:rect];
5339 /* Cydia TableView Cell {{{ */
5340 @interface CYTableViewCell : UITableViewCell {
5341 ContentView *content_;
5347 @implementation CYTableViewCell
5354 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5355 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5357 if (view == content_) {
5358 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5359 highlighted_ = highlighted;
5362 [super _updateHighlightColorsForView:view highlighted:highlighted];
5365 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5366 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5367 highlighted_ = selected;
5369 [super setSelected:selected animated:animated];
5370 [content_ setNeedsDisplay];
5376 /* Package Cell {{{ */
5377 @interface PackageCell : CYTableViewCell <
5382 NSString *description_;
5390 - (PackageCell *) init;
5391 - (void) setPackage:(Package *)package;
5393 - (void) drawContentRect:(CGRect)rect;
5397 @implementation PackageCell
5399 - (void) clearPackage {
5410 if (description_ != nil) {
5411 [description_ release];
5415 if (source_ != nil) {
5420 if (badge_ != nil) {
5425 if (placard_ != nil) {
5435 [self clearPackage];
5439 - (PackageCell *) init {
5440 CGRect frame(CGRectMake(0, 0, 320, 74));
5441 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5442 UIView *content([self contentView]);
5443 CGRect bounds([content bounds]);
5445 content_ = [[ContentView alloc] initWithFrame:bounds];
5446 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5447 [content addSubview:content_];
5449 [content_ setDelegate:self];
5450 [content_ setOpaque:YES];
5454 - (NSString *) accessibilityLabel {
5455 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5458 - (void) setPackage:(Package *)package {
5459 [self clearPackage];
5462 Source *source = [package source];
5464 icon_ = [[package icon] retain];
5465 name_ = [[package name] retain];
5468 description_ = [package longDescription];
5469 if (description_ == nil)
5470 description_ = [package shortDescription];
5471 if (description_ != nil)
5472 description_ = [description_ retain];
5474 commercial_ = [package isCommercial];
5476 package_ = [package retain];
5478 NSString *label = nil;
5479 bool trusted = false;
5481 if (source != nil) {
5482 label = [source label];
5483 trusted = [source trusted];
5484 } else if ([[package id] isEqualToString:@"firmware"])
5485 label = UCLocalize("APPLE");
5487 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5489 NSString *from(label);
5491 NSString *section = [package simpleSection];
5492 if (section != nil && ![section isEqualToString:label]) {
5493 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5494 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5497 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5498 source_ = [from retain];
5500 if (NSString *purpose = [package primaryPurpose])
5501 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5502 badge_ = [badge_ retain];
5507 if (NSString *mode = [package_ mode]) {
5508 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5509 color = RemovingColor_;
5510 //placard = @"removing";
5512 color = InstallingColor_;
5513 //placard = @"installing";
5516 // XXX: the removing/installing placards are not @2x
5519 color = [UIColor whiteColor];
5521 if ([package installed] != nil)
5522 placard = @"installed";
5527 [content_ setBackgroundColor:color];
5530 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5531 placard_ = [placard_ retain];
5533 [self setNeedsDisplay];
5534 [content_ setNeedsDisplay];
5537 - (void) drawContentRect:(CGRect)rect {
5538 bool highlighted(highlighted_);
5539 float width([self bounds].size.width);
5542 CGContextRef context(UIGraphicsGetCurrentContext());
5543 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5544 CGContextFillRect(context, rect);
5549 rect.size = [icon_ size];
5551 rect.size.width /= 2;
5552 rect.size.height /= 2;
5554 rect.origin.x = 25 - rect.size.width / 2;
5555 rect.origin.y = 25 - rect.size.height / 2;
5557 [icon_ drawInRect:rect];
5560 if (badge_ != nil) {
5562 rect.size = [badge_ size];
5564 rect.size.width /= 2;
5565 rect.size.height /= 2;
5567 rect.origin.x = 36 - rect.size.width / 2;
5568 rect.origin.y = 36 - rect.size.height / 2;
5570 [badge_ drawInRect:rect];
5577 UISetColor(commercial_ ? Purple_ : Black_);
5578 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5579 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5582 UISetColor(commercial_ ? Purplish_ : Gray_);
5583 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5585 if (placard_ != nil)
5586 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5591 /* Section Cell {{{ */
5592 @interface SectionCell : CYTableViewCell <
5604 - (void) setSection:(Section *)section editing:(BOOL)editing;
5608 @implementation SectionCell
5610 - (void) clearSection {
5611 if (basic_ != nil) {
5616 if (section_ != nil) {
5626 if (count_ != nil) {
5633 [self clearSection];
5639 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5640 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5641 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5642 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5643 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5645 UIView *content([self contentView]);
5646 CGRect bounds([content bounds]);
5648 content_ = [[ContentView alloc] initWithFrame:bounds];
5649 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5650 [content addSubview:content_];
5651 [content_ setBackgroundColor:[UIColor whiteColor]];
5653 [content_ setDelegate:self];
5657 - (void) onSwitch:(id)sender {
5658 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5659 if (metadata == nil) {
5660 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5661 [Sections_ setObject:metadata forKey:basic_];
5664 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5668 - (void) setSection:(Section *)section editing:(BOOL)editing {
5669 if (editing != editing_) {
5671 [switch_ removeFromSuperview];
5673 [self addSubview:switch_];
5677 [self clearSection];
5679 if (section == nil) {
5680 name_ = [UCLocalize("ALL_PACKAGES") retain];
5683 basic_ = [section name];
5685 basic_ = [basic_ retain];
5687 section_ = [section localized];
5688 if (section_ != nil)
5689 section_ = [section_ retain];
5691 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5692 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5695 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5698 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5699 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5701 [content_ setNeedsDisplay];
5704 - (void) setFrame:(CGRect)frame {
5705 [super setFrame:frame];
5707 CGRect rect([switch_ frame]);
5708 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5711 - (NSString *) accessibilityLabel {
5715 - (void) drawContentRect:(CGRect)rect {
5716 bool highlighted(highlighted_ && !editing_);
5718 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5723 float width(rect.size.width);
5729 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5731 CGSize size = [count_ sizeWithFont:Font14_];
5735 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5741 /* File Table {{{ */
5742 @interface FileTable : CYViewController <
5743 UITableViewDataSource,
5746 _transient Database *database_;
5749 NSMutableArray *files_;
5753 - (id) initWithDatabase:(Database *)database;
5754 - (void) setPackage:(Package *)package;
5758 @implementation FileTable
5761 [self releaseSubviews];
5770 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5771 return files_ == nil ? 0 : [files_ count];
5774 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5778 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5779 static NSString *reuseIdentifier = @"Cell";
5781 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5783 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5784 [cell setFont:[UIFont systemFontOfSize:16]];
5786 [cell setText:[files_ objectAtIndex:indexPath.row]];
5787 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5792 - (NSURL *) navigationURL {
5793 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5797 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5799 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5800 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5801 [list_ setRowHeight:24.0f];
5802 [list_ setDataSource:self];
5803 [list_ setDelegate:self];
5804 [[self view] addSubview:list_];
5807 - (void) viewDidLoad {
5808 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5811 - (void) releaseSubviews {
5816 - (id) initWithDatabase:(Database *)database {
5817 if ((self = [super init]) != nil) {
5818 database_ = database;
5820 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5824 - (void) setPackage:(Package *)package {
5825 if (package_ != nil) {
5826 [package_ autorelease];
5835 [files_ removeAllObjects];
5837 if (package != nil) {
5838 package_ = [package retain];
5839 name_ = [[package id] retain];
5841 if (NSArray *files = [package files])
5842 [files_ addObjectsFromArray:files];
5844 if ([files_ count] != 0) {
5845 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5846 [files_ removeObjectAtIndex:0];
5847 [files_ sortUsingSelector:@selector(compareByPath:)];
5849 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5850 [stack addObject:@"/"];
5852 for (int i(0), e([files_ count]); i != e; ++i) {
5853 NSString *file = [files_ objectAtIndex:i];
5854 while (![file hasPrefix:[stack lastObject]])
5855 [stack removeLastObject];
5856 NSString *directory = [stack lastObject];
5857 [stack addObject:[file stringByAppendingString:@"/"]];
5858 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5859 ([stack count] - 2) * 3, "",
5860 [file substringFromIndex:[directory length]]
5869 - (void) reloadData {
5872 [self setPackage:[database_ packageWithName:name_]];
5877 /* Package Controller {{{ */
5878 @interface CYPackageController : CYBrowserController <
5879 UIActionSheetDelegate
5881 _transient Database *database_;
5882 _H<Package> package_;
5885 _H<NSMutableArray> buttons_;
5886 _H<UIBarButtonItem> button_;
5889 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5893 @implementation CYPackageController
5895 - (NSURL *) navigationURL {
5896 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5899 /* XXX: this is not safe at all... localization of /fail/ */
5900 - (void) _clickButtonWithName:(NSString *)name {
5901 if ([name isEqualToString:UCLocalize("CLEAR")])
5902 [delegate_ clearPackage:package_];
5903 else if ([name isEqualToString:UCLocalize("INSTALL")])
5904 [delegate_ installPackage:package_];
5905 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5906 [delegate_ installPackage:package_];
5907 else if ([name isEqualToString:UCLocalize("REMOVE")])
5908 [delegate_ removePackage:package_];
5909 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5910 [delegate_ installPackage:package_];
5911 else _assert(false);
5914 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5915 NSString *context([sheet context]);
5917 if ([context isEqualToString:@"modify"]) {
5918 if (button != [sheet cancelButtonIndex]) {
5919 NSString *buttonName = [buttons_ objectAtIndex:button];
5920 [self _clickButtonWithName:buttonName];
5923 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5927 - (bool) _allowJavaScriptPanel {
5932 - (void) _customButtonClicked {
5933 int count([buttons_ count]);
5938 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5940 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5941 [buttons addObjectsFromArray:buttons_];
5943 UIActionSheet *sheet = [[[UIActionSheet alloc]
5946 cancelButtonTitle:nil
5947 destructiveButtonTitle:nil
5948 otherButtonTitles:nil
5951 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5953 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5954 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5956 [sheet setContext:@"modify"];
5958 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5962 // We don't want to allow non-commercial packages to do custom things to the install button,
5963 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5964 - (void) customButtonClicked {
5966 [super customButtonClicked];
5968 [self _customButtonClicked];
5971 - (void) reloadButtonClicked {
5972 // Don't reload a commerical package by tapping the loading button,
5973 // but if it's not an Install button, we should forward it on.
5974 if (![package_ uninstalled])
5975 [self _customButtonClicked];
5978 - (void) applyLoadingTitle {
5979 // Don't show "Loading" as the title. Ever.
5982 - (UIBarButtonItem *) rightButton {
5987 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5988 if ((self = [super init]) != nil) {
5989 database_ = database;
5990 buttons_ = [NSMutableArray arrayWithCapacity:4];
5991 name_ = [NSString stringWithString:name];
5992 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5996 - (void) reloadData {
5997 package_ = [database_ packageWithName:name_];
5999 [buttons_ removeAllObjects];
6001 if (package_ != nil) {
6002 [(Package *) package_ parse];
6004 commercial_ = [package_ isCommercial];
6006 if ([package_ mode] != nil)
6007 [buttons_ addObject:UCLocalize("CLEAR")];
6008 if ([package_ source] == nil);
6009 else if ([package_ upgradableAndEssential:NO])
6010 [buttons_ addObject:UCLocalize("UPGRADE")];
6011 else if ([package_ uninstalled])
6012 [buttons_ addObject:UCLocalize("INSTALL")];
6014 [buttons_ addObject:UCLocalize("REINSTALL")];
6015 if (![package_ uninstalled])
6016 [buttons_ addObject:UCLocalize("REMOVE")];
6020 switch ([buttons_ count]) {
6021 case 0: title = nil; break;
6022 case 1: title = [buttons_ objectAtIndex:0]; break;
6023 default: title = UCLocalize("MODIFY"); break;
6026 button_ = [[[UIBarButtonItem alloc]
6028 style:UIBarButtonItemStylePlain
6030 action:@selector(customButtonClicked)
6036 - (bool) isLoading {
6037 return commercial_ ? [super isLoading] : false;
6043 /* Package List Controller {{{ */
6044 @interface PackageListController : CYViewController <
6045 UITableViewDataSource,
6048 _transient Database *database_;
6050 NSMutableArray *packages_;
6051 NSMutableArray *sections_;
6053 NSMutableArray *index_;
6054 NSMutableDictionary *indices_;
6058 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6059 - (void) setDelegate:(id)delegate;
6060 - (void) resetCursor;
6064 @implementation PackageListController
6067 [packages_ release];
6068 [sections_ release];
6077 - (void) deselectWithAnimation:(BOOL)animated {
6078 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6081 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6082 CGRect base = [[self view] bounds];
6083 base.size.height -= bounds.size.height;
6084 base.origin = [list_ frame].origin;
6086 [UIView beginAnimations:nil context:NULL];
6087 [UIView setAnimationBeginsFromCurrentState:YES];
6088 [UIView setAnimationCurve:curve];
6089 [UIView setAnimationDuration:duration];
6090 [list_ setFrame:base];
6091 [UIView commitAnimations];
6094 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6095 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6098 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6099 [self resizeForKeyboardBounds:bounds duration:0];
6102 - (void) keyboardWillShow:(NSNotification *)notification {
6105 NSTimeInterval duration;
6106 UIViewAnimationCurve curve;
6107 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6108 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6109 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6110 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6112 CGRect kbframe = CGRectMake(round(center.x - bounds.size.width / 2.0), round(center.y - bounds.size.height / 2.0), bounds.size.width, bounds.size.height);
6113 UIViewController *base = self;
6114 while ([base parentViewController] != nil)
6115 base = [base parentViewController];
6116 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6117 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6119 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6122 - (void) keyboardWillHide:(NSNotification *)notification {
6123 NSTimeInterval duration;
6124 UIViewAnimationCurve curve;
6125 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6126 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6128 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6131 - (void) viewWillAppear:(BOOL)animated {
6132 [super viewWillAppear:animated];
6134 [self resizeForKeyboardBounds:CGRectZero];
6135 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6136 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6139 - (void) viewWillDisappear:(BOOL)animated {
6140 [super viewWillDisappear:animated];
6142 [self resizeForKeyboardBounds:CGRectZero];
6143 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6144 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6147 - (void) viewDidAppear:(BOOL)animated {
6148 [super viewDidAppear:animated];
6149 [self deselectWithAnimation:animated];
6152 - (void) didSelectPackage:(Package *)package {
6153 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6154 [view setDelegate:delegate_];
6155 [[self navigationController] pushViewController:view animated:YES];
6158 #if TryIndexedCollation
6159 + (BOOL) hasIndexedCollation {
6160 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6164 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6165 NSInteger count([sections_ count]);
6166 return count == 0 ? 1 : count;
6169 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6170 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6172 return [[sections_ objectAtIndex:section] name];
6175 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6176 if ([sections_ count] == 0)
6178 return [[sections_ objectAtIndex:section] count];
6181 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6182 @synchronized (database_) {
6183 if ([database_ era] != era_)
6186 Section *section([sections_ objectAtIndex:[path section]]);
6187 NSInteger row([path row]);
6188 Package *package([packages_ objectAtIndex:([section row] + row)]);
6189 return [[package retain] autorelease];
6192 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6193 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6195 cell = [[[PackageCell alloc] init] autorelease];
6196 [cell setPackage:[self packageAtIndexPath:path]];
6200 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6201 Package *package([self packageAtIndexPath:path]);
6202 package = [database_ packageWithName:[package id]];
6203 [self didSelectPackage:package];
6206 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6207 // XXX: is 20 the most optimal number here?
6208 return [packages_ count] > 20 ? index_ : nil;
6211 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6212 #if TryIndexedCollation
6213 if ([[self class] hasIndexedCollation]) {
6214 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6221 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6222 if ((self = [super init]) != nil) {
6223 database_ = database;
6224 title_ = [title copy];
6225 [[self navigationItem] setTitle:title_];
6227 #if TryIndexedCollation
6228 if ([[self class] hasIndexedCollation])
6229 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6232 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6234 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6236 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6237 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6239 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6240 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6241 [list_ setRowHeight:73];
6242 [[self view] addSubview:list_];
6244 [list_ setDataSource:self];
6245 [list_ setDelegate:self];
6249 - (void) setDelegate:(id)delegate {
6250 delegate_ = delegate;
6253 - (bool) hasPackage:(Package *)package {
6257 - (void) reloadData {
6260 era_ = [database_ era];
6261 NSArray *packages = [database_ packages];
6263 [packages_ removeAllObjects];
6264 [sections_ removeAllObjects];
6266 _profile(PackageTable$reloadData$Filter)
6267 for (Package *package in packages)
6268 if ([self hasPackage:package])
6269 [packages_ addObject:package];
6272 [indices_ removeAllObjects];
6274 Section *section = nil;
6276 #if TryIndexedCollation
6277 if ([[self class] hasIndexedCollation]) {
6278 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6279 NSArray *titles = [collation sectionIndexTitles];
6282 _profile(PackageTable$reloadData$Section)
6283 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6287 _profile(PackageTable$reloadData$Section$Package)
6288 package = [packages_ objectAtIndex:offset];
6289 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6292 while (secidx < index) {
6295 _profile(PackageTable$reloadData$Section$Allocate)
6296 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6299 _profile(PackageTable$reloadData$Section$Add)
6300 [sections_ addObject:section];
6304 [section addToCount];
6310 [index_ removeAllObjects];
6312 _profile(PackageTable$reloadData$Section)
6313 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6317 _profile(PackageTable$reloadData$Section$Package)
6318 package = [packages_ objectAtIndex:offset];
6319 index = [package index];
6322 if (section == nil || [section index] != index) {
6323 _profile(PackageTable$reloadData$Section$Allocate)
6324 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6327 [index_ addObject:[section name]];
6328 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6330 _profile(PackageTable$reloadData$Section$Add)
6331 [sections_ addObject:section];
6335 [section addToCount];
6340 _profile(PackageTable$reloadData$List)
6345 - (void) resetCursor {
6346 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6351 /* Filtered Package List Controller {{{ */
6352 @interface FilteredPackageListController : PackageListController {
6358 - (void) setObject:(id)object;
6359 - (void) setObject:(id)object forFilter:(SEL)filter;
6361 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6365 @implementation FilteredPackageListController
6373 - (void) setFilter:(SEL)filter {
6376 /* XXX: this is an unsafe optimization of doomy hell */
6377 Method method(class_getInstanceMethod([Package class], filter));
6378 _assert(method != NULL);
6379 imp_ = method_getImplementation(method);
6380 _assert(imp_ != NULL);
6383 - (void) setObject:(id)object {
6389 object_ = [object retain];
6392 - (void) setObject:(id)object forFilter:(SEL)filter {
6393 [self setFilter:filter];
6394 [self setObject:object];
6397 - (bool) hasPackage:(Package *)package {
6398 _profile(FilteredPackageTable$hasPackage)
6399 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6403 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6404 if ((self = [super initWithDatabase:database title:title]) != nil) {
6405 [self setFilter:filter];
6406 [self setObject:object];
6413 /* Home Controller {{{ */
6414 @interface HomeController : CYBrowserController {
6419 @implementation HomeController
6422 if ((self = [super init]) != nil) {
6423 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6427 - (NSURL *) navigationURL {
6428 return [NSURL URLWithString:@"cydia://home"];
6431 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6432 [super _setMoreHeaders:request];
6435 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6436 if (UniqueID_ != nil)
6437 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6439 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6442 - (void) aboutButtonClicked {
6443 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6445 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6446 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6447 [alert setCancelButtonIndex:0];
6450 @"Copyright (C) 2008-2011\n"
6451 "Jay Freeman (saurik)\n"
6452 "saurik@saurik.com\n"
6453 "http://www.saurik.com/"
6459 - (void) viewDidLoad {
6460 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6461 initWithTitle:UCLocalize("ABOUT")
6462 style:UIBarButtonItemStylePlain
6464 action:@selector(aboutButtonClicked)
6470 /* Manage Controller {{{ */
6471 @interface ManageController : CYBrowserController {
6474 - (void) queueStatusDidChange;
6478 @implementation ManageController
6481 if ((self = [super init]) != nil) {
6482 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6486 - (NSURL *) navigationURL {
6487 return [NSURL URLWithString:@"cydia://manage"];
6490 - (void) viewDidLoad {
6491 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6492 initWithTitle:UCLocalize("SETTINGS")
6493 style:UIBarButtonItemStylePlain
6495 action:@selector(settingsButtonClicked)
6498 [self queueStatusDidChange];
6501 - (void) settingsButtonClicked {
6502 [delegate_ showSettings];
6506 - (void) queueButtonClicked {
6510 - (void) applyLoadingTitle {
6511 // Disable "Loading" title.
6514 - (void) applyRightButton {
6515 // Disable right button.
6519 - (void) queueStatusDidChange {
6521 if (!IsWildcat_ && Queuing_) {
6522 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6523 initWithTitle:UCLocalize("QUEUE")
6524 style:UIBarButtonItemStyleDone
6526 action:@selector(queueButtonClicked)
6529 [[self navigationItem] setRightBarButtonItem:nil];
6534 - (bool) isLoading {
6535 // Never show as loading.
6542 /* Refresh Bar {{{ */
6543 @interface RefreshBar : UINavigationBar {
6544 UIProgressIndicator *indicator_;
6545 UITextLabel *prompt_;
6546 UIProgressBar *progress_;
6547 UINavigationButton *cancel_;
6552 @implementation RefreshBar
6555 [indicator_ release];
6557 [progress_ release];
6562 - (void) positionViews {
6563 CGRect frame = [cancel_ frame];
6564 frame.size = [cancel_ sizeThatFits:frame.size];
6565 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6566 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6567 [cancel_ setFrame:frame];
6569 CGSize prgsize = {75, 100};
6571 [self frame].size.width - prgsize.width - 10,
6572 ([self frame].size.height - prgsize.height) / 2
6574 [progress_ setFrame:prgrect];
6576 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6577 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6578 CGRect indrect = {{indoffset, indoffset}, indsize};
6579 [indicator_ setFrame:indrect];
6581 CGSize prmsize = {215, indsize.height + 4};
6583 indoffset * 2 + indsize.width,
6584 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6586 [prompt_ setFrame:prmrect];
6589 - (void) setFrame:(CGRect)frame {
6590 [super setFrame:frame];
6591 [self positionViews];
6594 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6595 if ((self = [super initWithFrame:frame]) != nil) {
6596 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6598 [self setBarStyle:UIBarStyleBlack];
6600 UIBarStyle barstyle([self _barStyle:NO]);
6601 bool ugly(barstyle == UIBarStyleDefault);
6603 UIProgressIndicatorStyle style = ugly ?
6604 UIProgressIndicatorStyleMediumBrown :
6605 UIProgressIndicatorStyleMediumWhite;
6607 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6608 [indicator_ setStyle:style];
6609 [indicator_ startAnimation];
6610 [self addSubview:indicator_];
6612 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6613 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6614 [prompt_ setBackgroundColor:[UIColor clearColor]];
6615 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6616 [self addSubview:prompt_];
6618 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6619 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6620 [progress_ setStyle:0];
6621 [self addSubview:progress_];
6623 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6624 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6625 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6626 [cancel_ setBarStyle:barstyle];
6628 [self positionViews];
6632 - (void) setCancellable:(bool)cancellable {
6634 [self addSubview:cancel_];
6636 [cancel_ removeFromSuperview];
6640 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6641 [progress_ setProgress:0];
6645 [self setCancellable:NO];
6648 - (void) setPrompt:(NSString *)prompt {
6649 [prompt_ setText:prompt];
6652 - (void) setProgress:(float)progress {
6653 [progress_ setProgress:progress];
6659 @class CYNavigationController;
6661 /* Cydia Tab Bar Controller {{{ */
6662 @interface CYTabBarController : UITabBarController <
6663 UITabBarControllerDelegate,
6666 _transient Database *database_;
6667 RefreshBar *refreshbar_;
6671 // XXX: ok, "updatedelegate_"?...
6672 _transient NSObject<CydiaDelegate> *updatedelegate_;
6675 UIViewController *remembered_;
6676 _transient UIViewController *transient_;
6679 - (NSArray *) navigationURLCollection;
6680 - (void) dropBar:(BOOL)animated;
6681 - (void) beginUpdate;
6682 - (void) raiseBar:(BOOL)animated;
6687 @implementation CYTabBarController
6689 - (void) setUnselectedViewController:(UIViewController *)transient {
6690 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6691 if (transient != nil) {
6692 if (transient_ == nil)
6693 remembered_ = [[controllers objectAtIndex:0] retain];
6694 transient_ = transient;
6695 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6696 [controllers replaceObjectAtIndex:0 withObject:transient_];
6697 [self setSelectedIndex:0];
6698 [self setViewControllers:controllers];
6699 [self concealTabBarSelection];
6700 } else if (remembered_ != nil) {
6701 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6702 transient_ = transient;
6703 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6704 [remembered_ release];
6706 [self setViewControllers:controllers];
6707 [self revealTabBarSelection];
6711 - (UIViewController *) unselectedViewController {
6715 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6716 if ([self unselectedViewController])
6717 [self setUnselectedViewController:nil];
6720 - (NSArray *) navigationURLCollection {
6721 NSMutableArray *items([NSMutableArray array]);
6723 // XXX: Should this deal with transient view controllers?
6724 for (id navigation in [self viewControllers]) {
6725 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6727 [items addObject:stack];
6733 - (void) reloadData {
6734 for (CYViewController *controller in [self viewControllers])
6735 [controller reloadData];
6737 [(CYNavigationController *)[self unselectedViewController] reloadData];
6741 [refreshbar_ release];
6742 [[NSNotificationCenter defaultCenter] removeObserver:self];
6747 - (id) initWithDatabase:(Database *)database {
6748 if ((self = [super init]) != nil) {
6749 database_ = database;
6750 [self setDelegate:self];
6752 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6753 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6755 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6759 - (void) setUpdate:(NSDate *)date {
6763 - (void) beginUpdate {
6764 [refreshbar_ start];
6767 [updatedelegate_ retainNetworkActivityIndicator];
6771 detachNewThreadSelector:@selector(performUpdate)
6777 - (void) performUpdate { _pooled
6779 status.setDelegate(self);
6780 [database_ updateWithStatus:status];
6783 performSelectorOnMainThread:@selector(completeUpdate)
6789 - (void) stopUpdateWithSelector:(SEL)selector {
6791 [updatedelegate_ releaseNetworkActivityIndicator];
6793 [self raiseBar:YES];
6796 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6799 - (void) completeUpdate {
6802 [self stopUpdateWithSelector:@selector(reloadData)];
6805 - (void) cancelUpdate {
6806 [self stopUpdateWithSelector:@selector(updateData)];
6809 - (void) cancelPressed {
6810 [self cancelUpdate];
6817 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6818 [refreshbar_ setPrompt:[event compoundMessage]];
6821 - (bool) isProgressCancelled {
6825 - (void) setProgressCancellable:(NSNumber *)cancellable {
6826 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6829 - (void) setProgressPercent:(NSNumber *)percent {
6830 [refreshbar_ setProgress:[percent floatValue]];
6833 - (void) setProgressStatus:(NSDictionary *)status {
6835 [self setProgressPercent:[status objectForKey:@"Percent"]];
6838 - (void) setUpdateDelegate:(id)delegate {
6839 updatedelegate_ = delegate;
6842 - (CGFloat) statusBarHeight {
6843 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6844 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6846 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6850 - (UIView *) transitionView {
6851 if ([self respondsToSelector:@selector(_transitionView)])
6852 return [self _transitionView];
6854 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6857 - (void) dropBar:(BOOL)animated {
6862 UIView *transition([self transitionView]);
6863 [[self view] addSubview:refreshbar_];
6865 CGRect barframe([refreshbar_ frame]);
6867 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6868 barframe.origin.y = [self statusBarHeight];
6870 barframe.origin.y = 0;
6872 [refreshbar_ setFrame:barframe];
6875 [UIView beginAnimations:nil context:NULL];
6877 CGRect viewframe = [transition frame];
6878 viewframe.origin.y += barframe.size.height;
6879 viewframe.size.height -= barframe.size.height;
6880 [transition setFrame:viewframe];
6883 [UIView commitAnimations];
6885 // Ensure bar has the proper width for our view, it might have changed
6886 barframe.size.width = viewframe.size.width;
6887 [refreshbar_ setFrame:barframe];
6889 // XXX: fix Apple's layout bug
6890 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6893 - (void) raiseBar:(BOOL)animated {
6898 UIView *transition([self transitionView]);
6899 [refreshbar_ removeFromSuperview];
6901 CGRect barframe([refreshbar_ frame]);
6904 [UIView beginAnimations:nil context:NULL];
6906 CGRect viewframe = [transition frame];
6907 viewframe.origin.y -= barframe.size.height;
6908 viewframe.size.height += barframe.size.height;
6909 [transition setFrame:viewframe];
6912 [UIView commitAnimations];
6914 // XXX: fix Apple's layout bug
6915 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6919 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6920 // XXX: fix Apple's layout bug
6921 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6925 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6926 bool dropped(dropped_);
6931 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6936 // XXX: fix Apple's layout bug
6937 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6940 - (void) statusBarFrameChanged:(NSNotification *)notification {
6949 /* Cydia Navigation Controller {{{ */
6950 @interface CYNavigationController : UINavigationController {
6951 _transient Database *database_;
6952 _transient id<UINavigationControllerDelegate> delegate_;
6955 - (NSArray *) navigationURLCollection;
6956 - (id) initWithDatabase:(Database *)database;
6957 - (void) reloadData;
6962 @implementation CYNavigationController
6964 - (NSArray *) navigationURLCollection {
6965 NSMutableArray *stack([NSMutableArray array]);
6967 for (CYViewController *controller in [self viewControllers]) {
6968 NSString *url = [[controller navigationURL] absoluteString];
6970 [stack addObject:url];
6976 - (void) reloadData {
6977 for (CYViewController *page in [self viewControllers]) {
6978 // Only reload controllers that have already loaded.
6979 // This prevents a page from accidentally loading too
6980 // early if it hasn't been shown on the screen yet.
6981 if ([page hasLoaded])
6986 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6987 delegate_ = delegate;
6990 - (id) initWithDatabase:(Database *)database {
6991 if ((self = [super init]) != nil) {
6992 database_ = database;
6999 /* Cydia:// Protocol {{{ */
7000 @interface CydiaURLProtocol : NSURLProtocol {
7005 @implementation CydiaURLProtocol
7007 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7008 NSURL *url([request URL]);
7012 NSString *scheme([[url scheme] lowercaseString]);
7013 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7015 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7021 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7025 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7026 id<NSURLProtocolClient> client([self client]);
7028 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7030 NSData *data(UIImagePNGRepresentation(icon));
7032 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7033 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7034 [client URLProtocol:self didLoadData:data];
7035 [client URLProtocolDidFinishLoading:self];
7039 - (void) startLoading {
7040 id<NSURLProtocolClient> client([self client]);
7041 NSURLRequest *request([self request]);
7043 NSURL *url([request URL]);
7044 NSString *href([url absoluteString]);
7045 NSString *scheme([[url scheme] lowercaseString]);
7049 if ([scheme isEqualToString:@"cydia"])
7050 path = [href substringFromIndex:8];
7051 else if ([scheme isEqualToString:@"about"])
7052 path = [href substringFromIndex:12];
7053 else _assert(false);
7055 NSRange slash([path rangeOfString:@"/"]);
7058 if (slash.location == NSNotFound) {
7062 command = [path substringToIndex:slash.location];
7063 path = [path substringFromIndex:(slash.location + 1)];
7066 Database *database([Database sharedInstance]);
7068 if ([command isEqualToString:@"package-icon"]) {
7071 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7072 Package *package([database packageWithName:path]);
7075 UIImage *icon([package icon]);
7076 [self _returnPNGWithImage:icon forRequest:request];
7077 } else if ([command isEqualToString:@"source-icon"]) {
7080 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7081 NSString *source(Simplify(path));
7082 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7084 icon = [UIImage applicationImageNamed:@"unknown.png"];
7085 [self _returnPNGWithImage:icon forRequest:request];
7086 } else if ([command isEqualToString:@"uikit-image"]) {
7089 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7090 UIImage *icon(_UIImageWithName(path));
7091 [self _returnPNGWithImage:icon forRequest:request];
7092 } else if ([command isEqualToString:@"section-icon"]) {
7095 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7096 NSString *section(Simplify(path));
7097 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7099 icon = [UIImage applicationImageNamed:@"unknown.png"];
7100 [self _returnPNGWithImage:icon forRequest:request];
7102 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7106 - (void) stopLoading {
7112 /* Section Controller {{{ */
7113 @interface SectionController : FilteredPackageListController {
7114 _H<NSString> section_;
7117 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7121 @implementation SectionController
7123 - (NSURL *) navigationURL {
7124 NSString *name = section_;
7128 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7131 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7134 title = UCLocalize("ALL_PACKAGES");
7135 else if (![name isEqual:@""])
7136 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7138 title = UCLocalize("NO_SECTION");
7140 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7147 /* Sections Controller {{{ */
7148 @interface SectionsController : CYViewController <
7149 UITableViewDataSource,
7152 _transient Database *database_;
7153 NSMutableArray *sections_;
7154 NSMutableArray *filtered_;
7159 - (id) initWithDatabase:(Database *)database;
7160 - (void) editButtonClicked;
7164 @implementation SectionsController
7167 [self releaseSubviews];
7168 [sections_ release];
7169 [filtered_ release];
7174 - (NSURL *) navigationURL {
7175 return [NSURL URLWithString:@"cydia://sections"];
7178 - (void) updateNavigationItem {
7179 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7180 if ([sections_ count] == 0) {
7181 [[self navigationItem] setRightBarButtonItem:nil];
7183 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7184 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7186 action:@selector(editButtonClicked)
7187 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7191 - (BOOL) isEditing {
7195 - (void) setEditing:(BOOL)editing {
7196 if ((editing_ = editing))
7199 [delegate_ updateData];
7201 [self updateNavigationItem];
7204 - (void) viewDidAppear:(BOOL)animated {
7205 [super viewDidAppear:animated];
7206 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7209 - (void) viewWillDisappear:(BOOL)animated {
7210 [super viewWillDisappear:animated];
7211 if (editing_) [self setEditing:NO];
7214 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7215 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7219 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7220 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7223 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7227 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7228 static NSString *reuseIdentifier = @"SectionCell";
7230 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7232 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7234 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7239 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7243 Section *section = [self sectionAtIndexPath:indexPath];
7245 SectionController *controller = [[[SectionController alloc]
7246 initWithDatabase:database_
7247 section:[section name]
7249 [controller setDelegate:delegate_];
7251 [[self navigationController] pushViewController:controller animated:YES];
7255 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7257 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7258 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7259 [list_ setRowHeight:45.0f];
7260 [list_ setDataSource:self];
7261 [list_ setDelegate:self];
7262 [[self view] addSubview:list_];
7265 - (void) viewDidLoad {
7266 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7269 - (void) releaseSubviews {
7274 - (id) initWithDatabase:(Database *)database {
7275 if ((self = [super init]) != nil) {
7276 database_ = database;
7278 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7279 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7283 - (void) reloadData {
7286 NSArray *packages = [database_ packages];
7288 [sections_ removeAllObjects];
7289 [filtered_ removeAllObjects];
7291 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7294 for (Package *package in packages) {
7295 NSString *name([package section]);
7296 NSString *key(name == nil ? @"" : name);
7300 _profile(SectionsView$reloadData$Section)
7301 section = [sections objectForKey:key];
7302 if (section == nil) {
7303 _profile(SectionsView$reloadData$Section$Allocate)
7304 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7305 [sections setObject:section forKey:key];
7310 [section addToCount];
7312 _profile(SectionsView$reloadData$Filter)
7313 if (![package valid] || ![package visible])
7321 [sections_ addObjectsFromArray:[sections allValues]];
7323 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7325 for (Section *section in sections_) {
7326 size_t count([section row]);
7330 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7331 [section setCount:count];
7332 [filtered_ addObject:section];
7335 [self updateNavigationItem];
7340 - (void) editButtonClicked {
7341 [self setEditing:(!editing_)];
7347 /* Changes Controller {{{ */
7348 @interface ChangesController : CYViewController <
7349 UITableViewDataSource,
7352 _transient Database *database_;
7354 CFMutableArrayRef packages_;
7355 NSMutableArray *sections_;
7358 BOOL hasSentFirstLoad_;
7361 - (id) initWithDatabase:(Database *)database;
7365 @implementation ChangesController
7368 [self releaseSubviews];
7369 CFRelease(packages_);
7370 [sections_ release];
7375 - (NSURL *) navigationURL {
7376 return [NSURL URLWithString:@"cydia://changes"];
7379 - (void) viewWillAppear:(BOOL)animated {
7380 // Loads after it appears, so don't load beforehand.
7382 [super viewWillAppear:animated];
7385 - (void) viewDidAppear:(BOOL)animated {
7386 [super viewDidAppear:animated];
7388 if (!hasSentFirstLoad_) {
7389 hasSentFirstLoad_ = YES;
7390 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7392 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7396 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7397 NSInteger count([sections_ count]);
7398 return count == 0 ? 1 : count;
7401 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7402 if ([sections_ count] == 0)
7404 return [[sections_ objectAtIndex:section] name];
7407 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7408 if ([sections_ count] == 0)
7410 return [[sections_ objectAtIndex:section] count];
7413 - (Package *) packageAtIndex:(NSUInteger)index {
7414 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7417 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7418 @synchronized (database_) {
7419 if ([database_ era] != era_)
7422 NSUInteger sectionIndex([path section]);
7423 if (sectionIndex >= [sections_ count])
7425 Section *section([sections_ objectAtIndex:sectionIndex]);
7426 NSInteger row([path row]);
7427 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7430 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7431 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7433 cell = [[[PackageCell alloc] init] autorelease];
7434 [cell setPackage:[self packageAtIndexPath:path]];
7438 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7439 Package *package([self packageAtIndexPath:path]);
7440 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7441 [view setDelegate:delegate_];
7442 [[self navigationController] pushViewController:view animated:YES];
7446 - (void) refreshButtonClicked {
7447 [delegate_ beginUpdate];
7448 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7451 - (void) upgradeButtonClicked {
7452 [delegate_ distUpgrade];
7456 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7458 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7459 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7460 [list_ setRowHeight:73];
7461 [list_ setDataSource:self];
7462 [list_ setDelegate:self];
7463 [[self view] addSubview:list_];
7466 - (void) viewDidLoad {
7467 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7470 - (void) releaseSubviews {
7475 - (id) initWithDatabase:(Database *)database {
7476 if ((self = [super init]) != nil) {
7477 database_ = database;
7479 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7480 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7484 // this mostly works because reloadData (below) is @synchronized (database_)
7485 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7486 - (void) _reloadPackages:(NSArray *)packages {
7487 CFRelease(packages_);
7488 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7491 _profile(ChangesController$_reloadPackages$Filter)
7492 for (Package *package in packages)
7493 if ([package upgradableAndEssential:YES] || [package visible])
7494 CFArrayAppendValue(packages_, package);
7497 _profile(ChangesController$_reloadPackages$radixSort)
7498 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7503 - (void) reloadData {
7504 @synchronized (database_) {
7505 era_ = [database_ era];
7506 NSArray *packages = [database_ packages];
7508 [sections_ removeAllObjects];
7511 UIProgressHUD *hud([delegate_ addProgressHUD]);
7512 [hud setText:UCLocalize("LOADING")];
7513 //NSLog(@"HUD:%@::%@", delegate_, hud);
7514 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7515 [delegate_ removeProgressHUD:hud];
7517 [self _reloadPackages:packages];
7520 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7521 Section *ignored = nil;
7522 Section *section = nil;
7526 bool unseens = false;
7528 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7530 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7531 Package *package = [self packageAtIndex:offset];
7533 BOOL uae = [package upgradableAndEssential:YES];
7537 time_t seen([package seen]);
7539 if (section == nil || last != seen) {
7543 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7546 _profile(ChangesController$reloadData$Allocate)
7547 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7548 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7549 [sections_ addObject:section];
7553 [section addToCount];
7554 } else if ([package ignored]) {
7555 if (ignored == nil) {
7556 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7558 [ignored addToCount];
7561 [upgradable addToCount];
7566 CFRelease(formatter);
7569 Section *last = [sections_ lastObject];
7570 size_t count = [last count];
7571 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7572 [sections_ removeLastObject];
7575 if ([ignored count] != 0)
7576 [sections_ insertObject:ignored atIndex:0];
7578 [sections_ insertObject:upgradable atIndex:0];
7583 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7584 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7585 style:UIBarButtonItemStylePlain
7587 action:@selector(upgradeButtonClicked)
7590 if (![delegate_ updating])
7591 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7592 initWithTitle:UCLocalize("REFRESH")
7593 style:UIBarButtonItemStylePlain
7595 action:@selector(refreshButtonClicked)
7603 /* Search Controller {{{ */
7604 @interface SearchController : FilteredPackageListController <
7607 _H<UISearchBar> search_;
7611 - (id) initWithDatabase:(Database *)database;
7612 - (void) setSearchTerm:(NSString *)term;
7613 - (void) reloadData;
7617 @implementation SearchController
7620 [search_ setDelegate:nil];
7624 - (NSURL *) navigationURL {
7625 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7626 return [NSURL URLWithString:@"cydia://search"];
7628 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7631 - (void) setSearchTerm:(NSString *)searchTerm {
7632 [search_ setText:searchTerm];
7636 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7637 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7638 [search_ resignFirstResponder];
7642 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7643 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7647 - (id) initWithDatabase:(Database *)database {
7648 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7649 search_ = [[[UISearchBar alloc] init] autorelease];
7650 [search_ setDelegate:self];
7654 - (void) viewDidAppear:(BOOL)animated {
7655 [super viewDidAppear:animated];
7657 if (!searchloaded_) {
7658 searchloaded_ = YES;
7659 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7660 [search_ layoutSubviews];
7661 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7663 UITextField *textField;
7664 if ([search_ respondsToSelector:@selector(searchField)])
7665 textField = [search_ searchField];
7667 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7669 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7670 [textField setEnablesReturnKeyAutomatically:NO];
7671 [[self navigationItem] setTitleView:textField];
7675 - (void) reloadData {
7676 [self setObject:[search_ text]];
7681 - (void) didSelectPackage:(Package *)package {
7682 [search_ resignFirstResponder];
7683 [super didSelectPackage:package];
7688 /* Package Settings Controller {{{ */
7689 @interface PackageSettingsController : CYViewController <
7690 UITableViewDataSource,
7693 _transient Database *database_;
7696 UITableView *table_;
7697 UISwitch *subscribedSwitch_;
7698 UISwitch *ignoredSwitch_;
7699 UITableViewCell *subscribedCell_;
7700 UITableViewCell *ignoredCell_;
7703 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7707 @implementation PackageSettingsController
7710 [self releaseSubviews];
7717 - (NSURL *) navigationURL {
7718 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7721 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7722 if (package_ == nil)
7725 if ([package_ installed] == nil)
7731 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7732 if (package_ == nil)
7735 // both sections contain just one item right now.
7739 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7743 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7745 return UCLocalize("SHOW_ALL_CHANGES_EX");
7747 return UCLocalize("IGNORE_UPGRADES_EX");
7750 - (void) onSubscribed:(id)control {
7751 bool value([control isOn]);
7752 if (package_ == nil)
7754 if ([package_ setSubscribed:value])
7755 [delegate_ updateData];
7758 - (void) _updateIgnored {
7759 const char *package([name_ UTF8String]);
7760 bool on([ignoredSwitch_ isOn]);
7762 pid_t pid(ExecFork());
7764 FILE *dpkg(popen("dpkg --set-selections", "w"));
7765 fwrite(package, strlen(package), 1, dpkg);
7768 fwrite(" hold\n", 6, 1, dpkg);
7770 fwrite(" install\n", 9, 1, dpkg);
7780 int result(waitpid(pid, &status, 0));
7783 _assert(result == pid);
7789 - (void) onIgnored:(id)control {
7790 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7791 [invocation setTarget:self];
7792 [invocation setSelector:@selector(_updateIgnored)];
7794 [delegate_ reloadDataWithInvocation:invocation];
7797 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7798 if (package_ == nil)
7801 switch ([indexPath section]) {
7802 case 0: return subscribedCell_;
7803 case 1: return ignoredCell_;
7812 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7814 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7815 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7816 [table_ setDataSource:self];
7817 [table_ setDelegate:self];
7818 [[self view] addSubview:table_];
7820 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7821 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7822 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7824 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7825 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7826 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7828 subscribedCell_ = [[UITableViewCell alloc] init];
7829 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7830 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7831 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7833 ignoredCell_ = [[UITableViewCell alloc] init];
7834 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7835 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7836 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7839 - (void) viewDidLoad {
7840 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7843 - (void) releaseSubviews {
7844 [ignoredCell_ release];
7847 [subscribedCell_ release];
7848 subscribedCell_ = nil;
7853 [ignoredSwitch_ release];
7854 ignoredSwitch_ = nil;
7856 [subscribedSwitch_ release];
7857 subscribedSwitch_ = nil;
7860 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7861 if ((self = [super init]) != nil) {
7862 database_ = database;
7863 name_ = [package retain];
7867 - (void) reloadData {
7870 if (package_ != nil)
7871 [package_ autorelease];
7872 package_ = [database_ packageWithName:name_];
7874 if (package_ != nil) {
7875 package_ = [package_ retain];
7876 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7877 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7878 } // XXX: what now, G?
7880 [table_ reloadData];
7886 /* Installed Controller {{{ */
7887 @interface InstalledController : FilteredPackageListController {
7891 - (id) initWithDatabase:(Database *)database;
7893 - (void) updateRoleButton;
7894 - (void) queueStatusDidChange;
7898 @implementation InstalledController
7904 - (NSURL *) navigationURL {
7905 return [NSURL URLWithString:@"cydia://installed"];
7908 - (id) initWithDatabase:(Database *)database {
7909 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7910 [self updateRoleButton];
7911 [self queueStatusDidChange];
7916 - (void) queueButtonClicked {
7921 - (void) queueStatusDidChange {
7925 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7926 initWithTitle:UCLocalize("QUEUE")
7927 style:UIBarButtonItemStyleDone
7929 action:@selector(queueButtonClicked)
7932 [[self navigationItem] setLeftBarButtonItem:nil];
7938 - (void) updateRoleButton {
7939 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7940 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7941 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7942 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7944 action:@selector(roleButtonClicked)
7948 - (void) roleButtonClicked {
7949 [self setObject:[NSNumber numberWithBool:expert_]];
7953 [self updateRoleButton];
7959 /* Source Cell {{{ */
7960 @interface SourceCell : CYTableViewCell <
7968 - (void) setSource:(Source *)source;
7972 @implementation SourceCell
7974 - (void) clearSource {
7984 - (void) setSource:(Source *)source {
7988 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7990 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7991 icon_ = [icon_ retain];
7993 origin_ = [[source name] retain];
7994 label_ = [[source uri] retain];
7996 [content_ setNeedsDisplay];
8004 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8005 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8006 UIView *content([self contentView]);
8007 CGRect bounds([content bounds]);
8009 content_ = [[ContentView alloc] initWithFrame:bounds];
8010 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8011 [content_ setBackgroundColor:[UIColor whiteColor]];
8012 [content addSubview:content_];
8014 [content_ setDelegate:self];
8015 [content_ setOpaque:YES];
8019 - (NSString *) accessibilityLabel {
8023 - (void) drawContentRect:(CGRect)rect {
8024 bool highlighted(highlighted_);
8025 float width(rect.size.width);
8028 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8035 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8039 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8044 /* Source Controller {{{ */
8045 @interface SourceController : FilteredPackageListController {
8046 _transient Source *source_;
8050 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8054 @implementation SourceController
8056 - (NSURL *) navigationURL {
8057 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8060 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8061 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8063 key_ = [[source key] retain];
8067 - (void) reloadData {
8068 source_ = [database_ sourceWithKey:key_];
8070 key_ = [[source_ key] retain];
8071 [self setObject:source_];
8072 [[self navigationItem] setTitle:[source_ label]];
8079 /* Sources Controller {{{ */
8080 @interface SourcesController : CYViewController <
8081 UITableViewDataSource,
8084 _transient Database *database_;
8086 NSMutableArray *sources_;
8090 UIProgressHUD *hud_;
8093 //NSURLConnection *installer_;
8094 NSURLConnection *trivial_;
8095 NSURLConnection *trivial_bz2_;
8096 NSURLConnection *trivial_gz_;
8097 //NSURLConnection *automatic_;
8102 - (id) initWithDatabase:(Database *)database;
8103 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8107 @implementation SourcesController
8109 - (void) _releaseConnection:(NSURLConnection *)connection {
8110 if (connection != nil) {
8111 [connection cancel];
8112 //[connection setDelegate:nil];
8113 [connection release];
8118 [self releaseSubviews];
8124 //[self _releaseConnection:installer_];
8125 [self _releaseConnection:trivial_];
8126 [self _releaseConnection:trivial_gz_];
8127 [self _releaseConnection:trivial_bz2_];
8128 //[self _releaseConnection:automatic_];
8134 - (NSURL *) navigationURL {
8135 return [NSURL URLWithString:@"cydia://sources"];
8138 - (void) viewDidAppear:(BOOL)animated {
8139 [super viewDidAppear:animated];
8140 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8143 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8144 return offset_ == 0 ? 1 : 2;
8147 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8148 switch (section + (offset_ == 0 ? 1 : 0)) {
8149 case 0: return UCLocalize("ENTERED_BY_USER");
8150 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8156 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8157 int count = [sources_ count];
8159 case 0: return (offset_ == 0 ? count : offset_);
8160 case 1: return count - offset_;
8166 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8168 switch (indexPath.section) {
8169 case 0: idx = indexPath.row; break;
8170 case 1: idx = indexPath.row + offset_; break;
8174 return [sources_ objectAtIndex:idx];
8177 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8178 static NSString *cellIdentifier = @"SourceCell";
8180 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8181 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8182 [cell setSource:[self sourceAtIndexPath:indexPath]];
8183 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8188 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8189 Source *source = [self sourceAtIndexPath:indexPath];
8191 SourceController *controller = [[[SourceController alloc]
8192 initWithDatabase:database_
8196 [controller setDelegate:delegate_];
8198 [[self navigationController] pushViewController:controller animated:YES];
8201 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8202 Source *source = [self sourceAtIndexPath:indexPath];
8203 return [source record] != nil;
8206 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8207 Source *source = [self sourceAtIndexPath:indexPath];
8208 [Sources_ removeObjectForKey:[source key]];
8209 [delegate_ syncData];
8213 [delegate_ addTrivialSource:href_];
8214 [delegate_ syncData];
8217 - (NSString *) getWarning {
8218 NSString *href(href_);
8219 NSRange colon([href rangeOfString:@"://"]);
8220 if (colon.location != NSNotFound)
8221 href = [href substringFromIndex:(colon.location + 3)];
8222 href = [href stringByAddingPercentEscapes];
8223 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8224 href = [href stringByCachingURLWithCurrentCDN];
8226 NSURL *url([NSURL URLWithString:href]);
8228 NSStringEncoding encoding;
8229 NSError *error(nil);
8231 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8232 return [warning length] == 0 ? nil : warning;
8236 - (void) _endConnection:(NSURLConnection *)connection {
8237 // XXX: the memory management in this method is horribly awkward
8239 NSURLConnection **field = NULL;
8240 if (connection == trivial_)
8242 else if (connection == trivial_bz2_)
8243 field = &trivial_bz2_;
8244 else if (connection == trivial_gz_)
8245 field = &trivial_gz_;
8246 _assert(field != NULL);
8247 [connection release];
8252 trivial_bz2_ == nil &&
8258 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8261 UIAlertView *alert = [[[UIAlertView alloc]
8262 initWithTitle:UCLocalize("SOURCE_WARNING")
8265 cancelButtonTitle:UCLocalize("CANCEL")
8267 UCLocalize("ADD_ANYWAY"),
8271 [alert setContext:@"warning"];
8272 [alert setNumberOfRows:1];
8276 } else if (error_ != nil) {
8277 UIAlertView *alert = [[[UIAlertView alloc]
8278 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8279 message:[error_ localizedDescription]
8281 cancelButtonTitle:UCLocalize("OK")
8282 otherButtonTitles:nil
8285 [alert setContext:@"urlerror"];
8288 UIAlertView *alert = [[[UIAlertView alloc]
8289 initWithTitle:UCLocalize("NOT_REPOSITORY")
8290 message:UCLocalize("NOT_REPOSITORY_EX")
8292 cancelButtonTitle:UCLocalize("OK")
8293 otherButtonTitles:nil
8296 [alert setContext:@"trivial"];
8300 [delegate_ releaseNetworkActivityIndicator];
8302 [delegate_ removeProgressHUD:hud_];
8311 if (error_ != nil) {
8318 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8319 switch ([response statusCode]) {
8325 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8326 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8328 error_ = [error retain];
8329 [self _endConnection:connection];
8332 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8333 [self _endConnection:connection];
8336 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8337 NSMutableURLRequest *request = [NSMutableURLRequest
8338 requestWithURL:[NSURL URLWithString:href]
8339 cachePolicy:NSURLRequestUseProtocolCachePolicy
8340 timeoutInterval:120.0
8343 [request setHTTPMethod:method];
8345 if (Machine_ != NULL)
8346 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8347 if (UniqueID_ != nil)
8348 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8350 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8352 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8355 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8356 NSString *context([alert context]);
8358 if ([context isEqualToString:@"source"]) {
8361 NSString *href = [[alert textField] text];
8363 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8365 if (![href hasSuffix:@"/"])
8366 href_ = [href stringByAppendingString:@"/"];
8369 href_ = [href_ retain];
8371 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8372 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8373 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8374 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8378 // XXX: this is stupid
8379 hud_ = [[delegate_ addProgressHUD] retain];
8380 [hud_ setText:UCLocalize("VERIFYING_URL")];
8381 [delegate_ retainNetworkActivityIndicator];
8390 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8391 } else if ([context isEqualToString:@"trivial"])
8392 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8393 else if ([context isEqualToString:@"urlerror"])
8394 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8395 else if ([context isEqualToString:@"warning"]) {
8410 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8415 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8417 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8418 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8419 [list_ setRowHeight:56];
8420 [list_ setDataSource:self];
8421 [list_ setDelegate:self];
8422 [[self view] addSubview:list_];
8425 - (void) viewDidLoad {
8426 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8427 [self updateButtonsForEditingStatus:NO animated:NO];
8430 - (void) releaseSubviews {
8435 - (id) initWithDatabase:(Database *)database {
8436 if ((self = [super init]) != nil) {
8437 database_ = database;
8438 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8442 - (void) reloadData {
8446 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8449 [sources_ removeAllObjects];
8450 [sources_ addObjectsFromArray:[database_ sources]];
8452 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8455 int count([sources_ count]);
8457 for (int i = 0; i != count; i++) {
8458 if ([[sources_ objectAtIndex:i] record] == nil)
8463 [list_ setEditing:NO];
8464 [self updateButtonsForEditingStatus:NO animated:NO];
8468 - (void) showAddSourcePrompt {
8469 UIAlertView *alert = [[[UIAlertView alloc]
8470 initWithTitle:UCLocalize("ENTER_APT_URL")
8473 cancelButtonTitle:UCLocalize("CANCEL")
8475 UCLocalize("ADD_SOURCE"),
8479 [alert setContext:@"source"];
8480 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8482 [alert setNumberOfRows:1];
8483 [alert addTextFieldWithValue:@"http://" label:@""];
8485 UITextInputTraits *traits = [[alert textField] textInputTraits];
8486 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8487 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8488 [traits setKeyboardType:UIKeyboardTypeURL];
8489 // XXX: UIReturnKeyDone
8490 [traits setReturnKeyType:UIReturnKeyNext];
8495 - (void) addButtonClicked {
8496 [self showAddSourcePrompt];
8499 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8500 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8501 initWithTitle:UCLocalize("ADD")
8502 style:UIBarButtonItemStylePlain
8504 action:@selector(addButtonClicked)
8505 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8507 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8508 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8509 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8511 action:@selector(editButtonClicked)
8512 ] autorelease] animated:animated];
8514 if (IsWildcat_ && !editing)
8515 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8516 initWithTitle:UCLocalize("SETTINGS")
8517 style:UIBarButtonItemStylePlain
8519 action:@selector(settingsButtonClicked)
8523 - (void) settingsButtonClicked {
8524 [delegate_ showSettings];
8527 - (void) editButtonClicked {
8528 [list_ setEditing:![list_ isEditing] animated:YES];
8530 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8536 /* Settings Controller {{{ */
8537 @interface SettingsController : CYViewController <
8538 UITableViewDataSource,
8541 _transient Database *database_;
8542 // XXX: ok, "roledelegate_"?...
8543 _transient id roledelegate_;
8544 UITableView *table_;
8545 UISegmentedControl *segment_;
8549 - (void) showDoneButton;
8550 - (void) resizeSegmentedControl;
8554 @implementation SettingsController
8557 [self releaseSubviews];
8563 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8565 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8566 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8567 [table_ setDelegate:self];
8568 [table_ setDataSource:self];
8569 [[self view] addSubview:table_];
8571 NSArray *items = [NSArray arrayWithObjects:
8573 UCLocalize("HACKER"),
8574 UCLocalize("DEVELOPER"),
8576 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8577 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8578 [container_ addSubview:segment_];
8581 - (void) viewDidLoad {
8582 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8585 if ([Role_ isEqualToString:@"User"]) index = 0;
8586 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8587 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8589 [segment_ setSelectedSegmentIndex:index];
8590 [self showDoneButton];
8593 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8594 [self resizeSegmentedControl];
8597 - (void) releaseSubviews {
8604 [container_ release];
8608 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8609 if ((self = [super init]) != nil) {
8610 database_ = database;
8611 roledelegate_ = delegate;
8615 - (void) resizeSegmentedControl {
8616 CGFloat width = [[self view] frame].size.width;
8617 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8620 - (void) viewWillAppear:(BOOL)animated {
8621 [super viewWillAppear:animated];
8623 [self resizeSegmentedControl];
8626 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8627 [self resizeSegmentedControl];
8630 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8631 [self resizeSegmentedControl];
8635 NSString *role(nil);
8637 switch ([segment_ selectedSegmentIndex]) {
8638 case 0: role = @"User"; break;
8639 case 1: role = @"Hacker"; break;
8640 case 2: role = @"Developer"; break;
8645 if (![role isEqualToString:Role_]) {
8646 bool rolling(Role_ == nil);
8649 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8653 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8657 [roledelegate_ loadData];
8659 [roledelegate_ updateData];
8663 - (void) segmentChanged:(UISegmentedControl *)control {
8664 [self showDoneButton];
8667 - (void) saveAndClose {
8670 [[self navigationItem] setRightBarButtonItem:nil];
8671 [[self navigationController] dismissModalViewControllerAnimated:YES];
8674 - (void) doneButtonClicked {
8675 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8676 [spinner startAnimating];
8677 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8678 [[self navigationItem] setRightBarButtonItem:spinItem];
8680 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8683 - (void) showDoneButton {
8684 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8685 initWithTitle:UCLocalize("DONE")
8686 style:UIBarButtonItemStyleDone
8688 action:@selector(doneButtonClicked)
8689 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8692 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8693 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8697 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8701 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8702 return nil; // This method is required by the protocol.
8705 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8707 return UCLocalize("ROLE_EX");
8709 return [NSString stringWithFormat:
8710 @"%@: %@\n%@: %@\n%@: %@",
8711 UCLocalize("USER"), UCLocalize("USER_EX"),
8712 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8713 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8718 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8719 return section == 3 ? 44.0f : 0;
8722 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8723 return section == 3 ? container_ : nil;
8726 - (void) reloadData {
8728 [table_ reloadData];
8733 /* Stash Controller {{{ */
8734 @interface StashController : CYViewController {
8735 UIActivityIndicatorView *spinner_;
8742 @implementation StashController
8745 [self releaseSubviews];
8751 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8752 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8754 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8755 CGRect spinrect = [spinner_ frame];
8756 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8757 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8758 [spinner_ setFrame:spinrect];
8759 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8760 [[self view] addSubview:spinner_];
8761 [spinner_ startAnimating];
8764 captrect.size.width = [[self view] frame].size.width;
8765 captrect.size.height = 40.0f;
8766 captrect.origin.x = 0;
8767 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8768 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8769 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8770 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8771 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8772 [caption_ setTextColor:[UIColor whiteColor]];
8773 [caption_ setBackgroundColor:[UIColor clearColor]];
8774 [caption_ setShadowColor:[UIColor blackColor]];
8775 [caption_ setTextAlignment:UITextAlignmentCenter];
8776 [[self view] addSubview:caption_];
8779 statusrect.size.width = [[self view] frame].size.width;
8780 statusrect.size.height = 30.0f;
8781 statusrect.origin.x = 0;
8782 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8783 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8784 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8785 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8786 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8787 [status_ setTextColor:[UIColor whiteColor]];
8788 [status_ setBackgroundColor:[UIColor clearColor]];
8789 [status_ setShadowColor:[UIColor blackColor]];
8790 [status_ setTextAlignment:UITextAlignmentCenter];
8791 [[self view] addSubview:status_];
8794 - (void) releaseSubviews {
8808 @interface Cydia : UIApplication <
8809 ConfirmationControllerDelegate,
8812 UINavigationControllerDelegate,
8813 UITabBarControllerDelegate
8815 // XXX: evaluate all fields for _transient
8818 CYTabBarController *tabbar_;
8819 CYEmulatedLoadingController *emulated_;
8821 NSMutableArray *essential_;
8822 NSMutableArray *broken_;
8824 Database *database_;
8831 StashController *stash_;
8840 @implementation Cydia
8842 - (void) beginUpdate {
8843 [tabbar_ beginUpdate];
8847 return [tabbar_ updating];
8851 if ([broken_ count] != 0) {
8852 int count = [broken_ count];
8854 UIAlertView *alert = [[[UIAlertView alloc]
8855 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8856 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8858 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8860 UCLocalize("TEMPORARY_IGNORE"),
8864 [alert setContext:@"fixhalf"];
8865 [alert setNumberOfRows:2];
8867 } else if (!Ignored_ && [essential_ count] != 0) {
8868 int count = [essential_ count];
8870 UIAlertView *alert = [[[UIAlertView alloc]
8871 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8872 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8874 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8876 UCLocalize("UPGRADE_ESSENTIAL"),
8877 UCLocalize("COMPLETE_UPGRADE"),
8881 [alert setContext:@"upgrade"];
8886 - (void) _saveConfig {
8892 NSString *error(nil);
8894 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8896 NSError *error(nil);
8897 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8898 NSLog(@"failure to save metadata data: %@", error);
8903 NSLog(@"failure to serialize metadata: %@", error);
8908 // Navigation controller for the queuing badge.
8909 - (CYNavigationController *) queueNavigationController {
8910 NSArray *controllers = [tabbar_ viewControllers];
8911 return [controllers objectAtIndex:3];
8914 - (void) _updateData {
8917 [tabbar_ reloadData];
8919 CYNavigationController *navigation = [self queueNavigationController];
8921 id queuedelegate = nil;
8922 if ([[navigation viewControllers] count] > 0)
8923 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8925 [queuedelegate queueStatusDidChange];
8926 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8929 - (void) _refreshIfPossible:(NSDate *)update {
8930 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8932 bool recently = false;
8933 if (update != nil) {
8934 NSTimeInterval interval([update timeIntervalSinceNow]);
8935 if (interval <= 0 && interval > -(15*60))
8939 // Don't automatic refresh if:
8940 // - We already refreshed recently.
8941 // - We already auto-refreshed this launch.
8942 // - Auto-refresh is disabled.
8943 if (recently || loaded_ || ManualRefresh) {
8944 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8946 // If we are cancelling, we need to make sure it knows it's already loaded.
8950 // We are going to load, so remember that.
8954 SCNetworkReachabilityFlags flags; {
8955 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8956 SCNetworkReachabilityGetFlags(reachability, &flags);
8957 CFRelease(reachability);
8960 // XXX: this elaborate mess is what Apple is using to determine this? :(
8961 // XXX: do we care if the user has to intervene? maybe that's ok?
8963 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8964 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8965 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8966 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8967 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8968 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8972 // If we can reach the server, auto-refresh!
8974 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8979 - (void) refreshIfPossible {
8980 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8983 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8984 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8985 [hud setText:UCLocalize("RELOADING_DATA")];
8987 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8990 [self removeProgressHUD:hud];
8994 [essential_ removeAllObjects];
8995 [broken_ removeAllObjects];
8997 NSArray *packages([database_ packages]);
8998 for (Package *package in packages) {
9000 [broken_ addObject:package];
9001 if ([package upgradableAndEssential:NO]) {
9002 if ([package essential])
9003 [essential_ addObject:package];
9008 NSLog(@"changes:#%u", changes);
9010 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9013 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9014 [changesItem setBadgeValue:badge];
9015 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9016 [self setApplicationIconBadgeNumber:changes];
9019 [changesItem setBadgeValue:nil];
9020 [changesItem setAnimatedBadge:NO];
9021 [self setApplicationIconBadgeNumber:0];
9026 [self refreshIfPossible];
9029 - (void) updateData {
9038 @synchronized (self) {
9039 [self _reloadDataWithInvocation:nil];
9043 - (void) disemulate {
9044 if (emulated_ == nil)
9047 [window_ addSubview:[tabbar_ view]];
9048 [[emulated_ view] removeFromSuperview];
9049 [emulated_ release];
9051 [window_ setUserInteractionEnabled:YES];
9054 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9055 UINavigationController *navigation([[[CYNavigationController alloc] initWithRootViewController:controller] autorelease]);
9057 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9059 UIViewController *parent;
9060 if (emulated_ == nil)
9069 [parent presentModalViewController:navigation animated:YES];
9072 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9073 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9075 if (navigation != nil)
9076 [navigation pushViewController:progress animated:YES];
9078 [self presentModalViewController:progress force:YES];
9080 [progress invoke:invocation withTitle:title];
9084 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9085 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9088 - (void) repairWithInvocation:(NSInvocation *)invocation {
9090 [self invokeNewProgress:invocation forController:nil withTitle:UCLocalize("REPAIRING")];
9094 - (void) repairWithSelector:(SEL)selector {
9095 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9101 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9102 _assert(file != NULL);
9104 for (NSString *key in [Sources_ allKeys]) {
9105 NSDictionary *source([Sources_ objectForKey:key]);
9107 fprintf(file, "%s %s %s\n",
9108 [[source objectForKey:@"Type"] UTF8String],
9109 [[source objectForKey:@"URI"] UTF8String],
9110 [[source objectForKey:@"Distribution"] UTF8String]
9116 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:UCLocalize("UPDATING_SOURCES")];
9121 - (void) addTrivialSource:(NSString *)href {
9122 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9125 @"./", @"Distribution",
9126 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9131 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9132 @synchronized (self) {
9133 [self _reloadDataWithInvocation:invocation];
9137 - (void) reloadData {
9138 [self reloadDataWithInvocation:nil];
9142 pkgProblemResolver *resolver = [database_ resolver];
9144 resolver->InstallProtect();
9145 if (!resolver->Resolve(true))
9150 // XXX: this is a really crappy way of doing this.
9151 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9152 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9153 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9154 if ([tabbar_ updating])
9155 [tabbar_ cancelUpdate];
9157 if (![database_ prepare])
9160 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9161 [page setDelegate:self];
9162 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
9163 [confirm_ setDelegate:self];
9166 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9167 [tabbar_ presentModalViewController:confirm_ animated:YES];
9173 @synchronized (self) {
9178 - (void) clearPackage:(Package *)package {
9179 @synchronized (self) {
9186 - (void) installPackages:(NSArray *)packages {
9187 @synchronized (self) {
9188 for (Package *package in packages)
9195 - (void) installPackage:(Package *)package {
9196 @synchronized (self) {
9203 - (void) removePackage:(Package *)package {
9204 @synchronized (self) {
9211 - (void) distUpgrade {
9212 @synchronized (self) {
9213 if (![database_ upgrade])
9219 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9222 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:UCLocalize("RUNNING")];
9227 - (void) showSettings {
9228 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9229 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9231 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9232 [tabbar_ presentModalViewController:nav animated:YES];
9235 - (void) retainNetworkActivityIndicator {
9236 if (activity_++ == 0)
9237 [self setNetworkActivityIndicatorVisible:YES];
9240 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9244 - (void) releaseNetworkActivityIndicator {
9245 if (--activity_ == 0)
9246 [self setNetworkActivityIndicatorVisible:NO];
9249 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9254 - (void) cancelAndClear:(bool)clear {
9255 @synchronized (self) {
9267 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9268 NSString *context([alert context]);
9270 if ([context isEqualToString:@"conffile"]) {
9271 FILE *input = [database_ input];
9272 if (button == [alert cancelButtonIndex])
9273 fprintf(input, "N\n");
9274 else if (button == [alert firstOtherButtonIndex])
9275 fprintf(input, "Y\n");
9278 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9279 } else if ([context isEqualToString:@"fixhalf"]) {
9280 if (button == [alert cancelButtonIndex]) {
9281 @synchronized (self) {
9282 for (Package *broken in broken_) {
9285 NSString *id = [broken id];
9286 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9287 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9288 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9289 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9295 } else if (button == [alert firstOtherButtonIndex]) {
9296 [broken_ removeAllObjects];
9300 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9301 } else if ([context isEqualToString:@"upgrade"]) {
9302 if (button == [alert firstOtherButtonIndex]) {
9303 @synchronized (self) {
9304 for (Package *essential in essential_)
9305 [essential install];
9310 } else if (button == [alert firstOtherButtonIndex] + 1) {
9312 } else if (button == [alert cancelButtonIndex]) {
9316 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9320 - (void) system:(NSString *)command { _pooled
9322 system([command UTF8String]);
9326 - (void) applicationWillSuspend {
9328 [super applicationWillSuspend];
9331 - (BOOL) isSafeToSuspend {
9332 // Use external process status API internally.
9333 // This is probably a really bad idea.
9334 // XXX: what is the point of this? does this solve anything at all?
9335 uint64_t status = 0;
9337 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9338 notify_get_state(notify_token, &status);
9339 notify_cancel(notify_token);
9342 return locked_ == 0 && status == 0;
9345 - (void) applicationSuspend:(__GSEvent *)event {
9346 if ([self isSafeToSuspend])
9347 [super applicationSuspend:event];
9350 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9351 if ([self isSafeToSuspend])
9352 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9355 - (void) _setSuspended:(BOOL)value {
9356 if ([self isSafeToSuspend])
9357 [super _setSuspended:value];
9360 - (UIProgressHUD *) addProgressHUD {
9361 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9362 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9364 [window_ setUserInteractionEnabled:NO];
9367 UIViewController *target = tabbar_;
9368 while ([target modalViewController] != nil) target = [target modalViewController];
9369 [[target view] addSubview:hud];
9375 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9377 [hud removeFromSuperview];
9378 [window_ setUserInteractionEnabled:YES];
9382 - (CYViewController *) pageForPackage:(NSString *)name {
9383 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9386 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9387 NSString *scheme([[url scheme] lowercaseString]);
9388 if ([[url absoluteString] length] <= [scheme length] + 3)
9390 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9391 NSArray *components([path pathComponents]);
9393 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9394 return [self pageForPackage:[components objectAtIndex:1]];
9396 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9399 NSString *base([components objectAtIndex:0]);
9401 CYViewController *controller = nil;
9403 if ([base isEqualToString:@"url"]) {
9404 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9405 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9406 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9407 } else if (!external && [components count] == 1) {
9408 if ([base isEqualToString:@"manage"]) {
9409 controller = [[[ManageController alloc] init] autorelease];
9412 if ([base isEqualToString:@"sources"]) {
9413 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9416 if ([base isEqualToString:@"home"]) {
9417 controller = [[[HomeController alloc] init] autorelease];
9420 if ([base isEqualToString:@"sections"]) {
9421 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9424 if ([base isEqualToString:@"search"]) {
9425 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9428 if ([base isEqualToString:@"changes"]) {
9429 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9432 if ([base isEqualToString:@"installed"]) {
9433 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9435 } else if ([components count] == 2) {
9436 NSString *argument = [components objectAtIndex:1];
9438 if ([base isEqualToString:@"package"]) {
9439 controller = [self pageForPackage:argument];
9442 if (!external && [base isEqualToString:@"search"]) {
9443 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9444 [(SearchController *)controller setSearchTerm:argument];
9447 if (!external && [base isEqualToString:@"sections"]) {
9448 if ([argument isEqualToString:@"all"])
9450 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9453 if (!external && [base isEqualToString:@"sources"]) {
9454 if ([argument isEqualToString:@"add"]) {
9455 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9456 [(SourcesController *)controller showAddSourcePrompt];
9458 Source *source = [database_ sourceWithKey:argument];
9459 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9463 if (!external && [base isEqualToString:@"launch"]) {
9464 [self launchApplicationWithIdentifier:argument suspended:NO];
9467 } else if (!external && [components count] == 3) {
9468 NSString *arg1 = [components objectAtIndex:1];
9469 NSString *arg2 = [components objectAtIndex:2];
9471 if ([base isEqualToString:@"package"]) {
9472 if ([arg2 isEqualToString:@"settings"]) {
9473 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9474 } else if ([arg2 isEqualToString:@"files"]) {
9475 if (Package *package = [database_ packageWithName:arg1]) {
9476 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9477 [(FileTable *)controller setPackage:package];
9483 [controller setDelegate:self];
9487 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9488 CYViewController *page([self pageForURL:url forExternal:external]);
9491 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9492 [nav setViewControllers:[NSArray arrayWithObject:page]];
9493 [tabbar_ setUnselectedViewController:nav];
9499 - (void) applicationOpenURL:(NSURL *)url {
9500 [super applicationOpenURL:url];
9502 if (!loaded_) starturl_ = [url retain];
9503 else [self openCydiaURL:url forExternal:YES];
9506 - (void) applicationWillResignActive:(UIApplication *)application {
9507 // Stop refreshing if you get a phone call or lock the device.
9508 if ([tabbar_ updating])
9509 [tabbar_ cancelUpdate];
9511 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9512 [super applicationWillResignActive:application];
9515 - (void) applicationWillTerminate:(UIApplication *)application {
9517 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9518 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9519 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9524 - (void) setConfigurationData:(NSString *)data {
9525 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9527 if (!conffile_r(data)) {
9528 lprintf("E:invalid conffile\n");
9532 NSString *ofile = conffile_r[1];
9533 //NSString *nfile = conffile_r[2];
9535 UIAlertView *alert = [[[UIAlertView alloc]
9536 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9537 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9539 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9541 UCLocalize("ACCEPT_NEW_COPY"),
9542 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9546 [alert setContext:@"conffile"];
9547 [alert setNumberOfRows:2];
9551 - (void) addStashController {
9553 stash_ = [[StashController alloc] init];
9554 [window_ addSubview:[stash_ view]];
9557 - (void) removeStashController {
9558 [[stash_ view] removeFromSuperview];
9564 [self setIdleTimerDisabled:YES];
9566 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9567 UpdateExternalStatus(1);
9568 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9569 UpdateExternalStatus(0);
9571 [self removeStashController];
9573 if (ExecFork() == 0) {
9574 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9575 perror("launchctl stop");
9579 - (void) setupViewControllers {
9580 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9582 NSMutableArray *items([NSMutableArray arrayWithObjects:
9583 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9584 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9585 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9586 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9590 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9591 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9593 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9596 NSMutableArray *controllers([NSMutableArray array]);
9597 for (UITabBarItem *item in items) {
9598 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9599 [controller setTabBarItem:item];
9600 [controllers addObject:controller];
9602 [tabbar_ setViewControllers:controllers];
9604 [tabbar_ setUpdateDelegate:self];
9607 - (void) applicationDidFinishLaunching:(id)unused {
9609 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9610 [self setApplicationSupportsShakeToEdit:NO];
9612 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9613 initWithMemoryCapacity:524288
9614 diskCapacity:10485760
9615 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9618 [CYBrowserController _initialize];
9620 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9622 Font12_ = [[UIFont systemFontOfSize:12] retain];
9623 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9624 Font14_ = [[UIFont systemFontOfSize:14] retain];
9625 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9626 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9628 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9629 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9631 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9632 [window_ orderFront:self];
9633 [window_ makeKey:self];
9634 [window_ setHidden:NO];
9637 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9638 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9639 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9640 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9641 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9642 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9643 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9644 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9645 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9648 [self addStashController];
9649 // XXX: this would be much cleaner as a yieldToSelector:
9650 // that way the removeStashController could happen right here inline
9651 // we also could no longer require the useless stash_ field anymore
9652 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9656 database_ = [Database sharedInstance];
9657 [database_ setDelegate:self];
9659 [window_ setUserInteractionEnabled:NO];
9660 [self setupViewControllers];
9662 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9663 [window_ addSubview:[emulated_ view]];
9665 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9672 [window_ setUserInteractionEnabled:YES];
9673 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9676 if ([emulated_ modalViewController] != nil)
9677 [emulated_ dismissModalViewControllerAnimated:YES];
9678 [window_ setUserInteractionEnabled:NO];
9686 int selectedIndex = 0;
9687 NSMutableArray *items = nil;
9689 bool recently = false;
9690 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9691 if (closed != nil) {
9692 NSTimeInterval interval([closed timeIntervalSinceNow]);
9693 // XXX: Is 15 minutes the optimal time here?
9694 if (interval <= 0 && interval > -(15*60))
9698 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9699 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9702 for (NSArray *entry in items)
9703 if ([entry count] <= 0)
9706 if (!recently || !items || !enough) {
9708 items = [NSMutableArray array];
9709 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9710 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9711 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9713 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9715 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9716 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9718 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9721 [tabbar_ setSelectedIndex:selectedIndex];
9722 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9723 NSArray *stack = [items objectAtIndex:tab];
9724 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9725 NSMutableArray *current = [NSMutableArray array];
9727 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9728 NSString *addr = [stack objectAtIndex:nav];
9729 NSURL *url = [NSURL URLWithString:addr];
9730 CYViewController *page = [self pageForURL:url forExternal:NO];
9732 [current addObject:page];
9735 [navigation setViewControllers:current];
9738 // (Try to) show the startup URL.
9739 if (starturl_ != nil) {
9740 [self openCydiaURL:starturl_ forExternal:NO];
9741 [starturl_ release];
9746 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9747 if (item != nil && IsWildcat_) {
9748 [sheet showFromBarButtonItem:item animated:YES];
9750 [sheet showInView:window_];
9754 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9755 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9756 [progress setTitle:task];
9757 [progress addProgressEvent:event];
9760 - (void) addProgressEventForTask:(NSArray *)data {
9761 CydiaProgressEvent *event([data objectAtIndex:0]);
9762 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9763 [self addProgressEvent:event forTask:task];
9766 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9767 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9773 id Alloc_(id self, SEL selector) {
9774 id object = alloc_(self, selector);
9775 lprintf("[%s]A-%p\n", self->isa->name, object);
9780 id Dealloc_(id self, SEL selector) {
9781 id object = dealloc_(self, selector);
9782 lprintf("[%s]D-%p\n", self->isa->name, object);
9786 Class $WebDefaultUIKitDelegate;
9788 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9789 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9790 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9791 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9794 static NSNumber *shouldPlayKeyboardSounds;
9798 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9800 case 1104: // Keyboard Button Clicked
9801 case 1105: // Keyboard Delete Repeated
9802 if (shouldPlayKeyboardSounds == nil) {
9803 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9804 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9807 if (![shouldPlayKeyboardSounds boolValue])
9811 _UIHardware$_playSystemSound$(self, _cmd, sound);
9815 Class $UIApplication;
9817 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9818 static BOOL initialized = NO;
9819 static BOOL started = NO;
9821 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9822 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9824 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9825 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9826 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9827 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9829 if (initialized && !enabled) {
9831 [bundle performSelector:@selector(_accessibilityStopServer)];
9832 } else if (enabled) {
9836 [bundle performSelector:@selector(_accessibilityStartServer)];
9842 int main(int argc, char *argv[]) { _pooled
9845 UpdateExternalStatus(0);
9847 if (Class $UIDevice = objc_getClass("UIDevice")) {
9848 UIDevice *device([$UIDevice currentDevice]);
9849 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9853 UIScreen *screen([UIScreen mainScreen]);
9854 if ([screen respondsToSelector:@selector(scale)])
9855 ScreenScale_ = [screen scale];
9859 UIDevice *device([UIDevice currentDevice]);
9860 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9863 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9864 if (idiom == UIUserInterfaceIdiomPhone)
9866 else if (idiom == UIUserInterfaceIdiomPad)
9869 NSLog(@"unknown UIUserInterfaceIdiom!");
9872 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9874 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9876 /* Library Hacks {{{ */
9877 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9879 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9880 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9881 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9882 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9883 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9886 $UIHardware = objc_getClass("UIHardware");
9887 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9888 if (UIHardware$_playSystemSound$ != NULL) {
9889 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9890 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9893 $UIApplication = objc_getClass("UIApplication");
9894 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9895 if (UIApplication$_updateApplicationAccessibility != NULL) {
9896 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9897 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9900 /* Set Locale {{{ */
9901 Locale_ = CFLocaleCopyCurrent();
9902 Languages_ = [NSLocale preferredLanguages];
9903 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9904 //NSLog(@"%@", [Languages_ description]);
9907 if (Languages_ == nil || [Languages_ count] == 0)
9908 // XXX: consider just setting to C and then falling through?
9911 lang = [[Languages_ objectAtIndex:0] UTF8String];
9912 setenv("LANG", lang, true);
9913 std::setlocale(LC_ALL, lang);
9916 NSLog(@"Setting Language: %s", lang);
9919 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9921 /* Parse Arguments {{{ */
9922 bool substrate(false);
9928 for (int argi(1); argi != argc; ++argi)
9929 if (strcmp(argv[argi], "--") == 0) {
9931 argv[argi] = argv[0];
9937 for (int argi(1); argi != arge; ++argi)
9938 if (strcmp(args[argi], "--substrate") == 0)
9941 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9945 App_ = [[NSBundle mainBundle] bundlePath];
9951 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9952 alloc_ = alloc->method_imp;
9953 alloc->method_imp = (IMP) &Alloc_;*/
9955 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9956 dealloc_ = dealloc->method_imp;
9957 dealloc->method_imp = (IMP) &Dealloc_;*/
9959 /* System Information {{{ */
9963 size = sizeof(maxproc);
9964 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9965 perror("sysctlbyname(\"kern.maxproc\", ?)");
9966 else if (maxproc < 64) {
9968 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9969 perror("sysctlbyname(\"kern.maxproc\", #)");
9972 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9973 char *osversion = new char[size];
9974 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9975 perror("sysctlbyname(\"kern.osversion\", ?)");
9977 System_ = [NSString stringWithUTF8String:osversion];
9979 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9980 char *machine = new char[size];
9981 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9982 perror("sysctlbyname(\"hw.machine\", ?)");
9986 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9987 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9988 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9989 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9993 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9994 NSData *data((NSData *) ecid);
9995 size_t length([data length]);
9996 uint8_t bytes[length];
9997 [data getBytes:bytes];
9998 char string[length * 2 + 1];
9999 for (size_t i(0); i != length; ++i)
10000 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10001 ChipID_ = [NSString stringWithUTF8String:string];
10005 IOObjectRelease(service);
10009 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10011 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10012 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10013 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10015 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10016 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10017 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10019 if (mcc != NULL && mnc != NULL)
10020 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10027 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10028 Build_ = [system objectForKey:@"ProductBuildVersion"];
10029 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10030 Product_ = [info objectForKey:@"SafariProductVersion"];
10031 Safari_ = [info objectForKey:@"CFBundleVersion"];
10034 /* Load Database {{{ */
10036 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10038 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10040 if (Metadata_ == NULL)
10041 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10043 Settings_ = [Metadata_ objectForKey:@"Settings"];
10045 Packages_ = [Metadata_ objectForKey:@"Packages"];
10046 Sections_ = [Metadata_ objectForKey:@"Sections"];
10047 Sources_ = [Metadata_ objectForKey:@"Sources"];
10049 Token_ = [Metadata_ objectForKey:@"Token"];
10052 if (Settings_ != nil)
10053 Role_ = [Settings_ objectForKey:@"Role"];
10055 if (Sections_ == nil) {
10056 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10057 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10060 if (Sources_ == nil) {
10061 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10062 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10067 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10070 if (Packages_ != nil) {
10072 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10076 [Metadata_ removeObjectForKey:@"Packages"];
10082 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10084 #define MobileSubstrate_(name) \
10085 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10086 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10087 if (handle == NULL) \
10088 NSLog(@"%s", dlerror()); \
10091 MobileSubstrate_(Activator)
10092 MobileSubstrate_(libstatusbar)
10093 MobileSubstrate_(SimulatedKeyEvents)
10094 MobileSubstrate_(WinterBoard)
10096 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10097 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10099 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10101 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10102 unlink("/tmp/.cydia.fw");
10104 } else if (access("/User", F_OK) != 0 || version < 2) {
10107 system("/usr/libexec/cydia/firmware.sh");
10111 _assert([[NSFileManager defaultManager]
10112 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10113 withIntermediateDirectories:YES
10118 if (access("/tmp/cydia.chk", F_OK) == 0) {
10119 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10120 _assert(errno == ENOENT);
10121 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10122 _assert(errno == ENOENT);
10125 /* APT Initialization {{{ */
10126 _assert(pkgInitConfig(*_config));
10127 _assert(pkgInitSystem(*_config, _system));
10130 _config->Set("APT::Acquire::Translation", lang);
10132 // XXX: this timeout might be important :(
10133 //_config->Set("Acquire::http::Timeout", 15);
10135 _config->Set("Acquire::http::MaxParallel", 3);
10137 /* Color Choices {{{ */
10138 space_ = CGColorSpaceCreateDeviceRGB();
10140 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10141 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10142 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10143 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10144 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10145 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10146 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10147 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10148 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10150 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10151 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10153 /* UIKit Configuration {{{ */
10154 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10155 if ($GSFontSetUseLegacyFontMetrics != NULL)
10156 $GSFontSetUseLegacyFontMetrics(YES);
10158 // XXX: I have a feeling this was important
10159 //UIKeyboardDisableAutomaticAppearance();
10162 Colon_ = UCLocalize("COLON_DELIMITED");
10163 Elision_ = UCLocalize("ELISION");
10164 Error_ = UCLocalize("ERROR");
10165 Warning_ = UCLocalize("WARNING");
10168 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10170 CGColorSpaceRelease(space_);
10171 CFRelease(Locale_);