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_;
1031 static NSString *Home_;
1033 static BOOL Advanced_;
1034 static BOOL Ignored_;
1036 static UIFont *Font12_;
1037 static UIFont *Font12Bold_;
1038 static UIFont *Font14_;
1039 static UIFont *Font18Bold_;
1040 static UIFont *Font22Bold_;
1042 static const char *Machine_ = NULL;
1043 static NSString *System_ = nil;
1044 static NSString *SerialNumber_ = nil;
1045 static NSString *ChipID_ = nil;
1046 static _H<NSString> Token_;
1047 static NSString *UniqueID_ = nil;
1048 static NSString *PLMN_ = nil;
1049 static NSString *Build_ = nil;
1050 static NSString *Product_ = nil;
1051 static NSString *Safari_ = nil;
1053 static CFLocaleRef Locale_;
1054 static NSArray *Languages_;
1055 static CGColorSpaceRef space_;
1057 static NSDictionary *SectionMap_;
1058 static NSMutableDictionary *Metadata_;
1059 static _transient NSMutableDictionary *Settings_;
1060 static _transient NSString *Role_;
1061 static _transient NSMutableDictionary *Packages_;
1062 static _transient NSMutableDictionary *Sections_;
1063 static _transient NSMutableDictionary *Sources_;
1064 static bool Changed_;
1068 static CGFloat ScreenScale_;
1069 static NSString *Idiom_;
1072 /* Display Helpers {{{ */
1073 inline float Interpolate(float begin, float end, float fraction) {
1074 return (end - begin) * fraction + begin;
1077 static _finline const char *StripVersion_(const char *version) {
1078 const char *colon(strchr(version, ':'));
1079 return colon == NULL ? version : colon + 1;
1082 NSString *LocalizeSection(NSString *section) {
1083 static Pcre title_r("^(.*?) \\((.*)\\)$");
1084 if (title_r(section)) {
1085 NSString *parent(title_r[1]);
1086 NSString *child(title_r[2]);
1088 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1089 LocalizeSection(parent),
1090 LocalizeSection(child)
1094 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1097 NSString *Simplify(NSString *title) {
1098 const char *data = [title UTF8String];
1099 size_t size = [title length];
1101 static Pcre square_r("^\\[(.*)\\]$");
1102 if (square_r(data, size))
1103 return Simplify(square_r[1]);
1105 static Pcre paren_r("^\\((.*)\\)$");
1106 if (paren_r(data, size))
1107 return Simplify(paren_r[1]);
1109 static Pcre title_r("^(.*?) \\((.*)\\)$");
1110 if (title_r(data, size))
1111 return Simplify(title_r[1]);
1117 NSString *GetLastUpdate() {
1118 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1121 return UCLocalize("NEVER_OR_UNKNOWN");
1123 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1124 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1126 CFRelease(formatter);
1128 return [(NSString *) formatted autorelease];
1131 bool isSectionVisible(NSString *section) {
1132 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1133 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1134 return hidden == nil || ![hidden boolValue];
1139 /* Delegate Prototypes {{{ */
1142 @class CydiaProgressEvent;
1144 @protocol DatabaseDelegate
1145 - (void) repairWithSelector:(SEL)selector;
1146 - (void) setConfigurationData:(NSString *)data;
1147 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
1150 @class CYPackageController;
1152 @protocol CydiaDelegate
1153 - (void) retainNetworkActivityIndicator;
1154 - (void) releaseNetworkActivityIndicator;
1155 - (void) clearPackage:(Package *)package;
1156 - (void) installPackage:(Package *)package;
1157 - (void) installPackages:(NSArray *)packages;
1158 - (void) removePackage:(Package *)package;
1159 - (void) beginUpdate;
1161 - (void) distUpgrade;
1163 - (void) updateData;
1165 - (void) addTrivialSource:(NSString *)href;
1166 - (void) showSettings;
1167 - (UIProgressHUD *) addProgressHUD;
1168 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1169 - (CYViewController *) pageForPackage:(NSString *)name;
1170 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1171 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1175 /* ProgressEvent Interface/Delegate {{{ */
1176 @interface CydiaProgressEvent : NSObject {
1177 _H<NSString> message_;
1181 _H<NSString> package_;
1183 _H<NSString> version_;
1186 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type;
1187 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package;
1188 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item;
1190 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type;
1192 - (NSString *) message;
1193 - (NSString *) type;
1196 - (NSString *) package;
1198 - (NSString *) version;
1200 - (void) setItem:(NSArray *)item;
1201 - (void) setPackage:(NSString *)package;
1202 - (void) setURL:(NSString *)url;
1203 - (void) setVersion:(NSString *)version;
1205 - (NSString *) compound:(NSString *)value;
1206 - (NSString *) compoundMessage;
1207 - (NSString *) compoundTitle;
1211 @protocol ProgressDelegate
1212 - (void) addProgressEvent:(CydiaProgressEvent *)event;
1213 - (void) setProgressPercent:(NSNumber *)percent;
1214 - (void) setProgressStatus:(NSDictionary *)status;
1215 - (void) setProgressCancellable:(NSNumber *)cancellable;
1216 - (bool) isProgressCancelled;
1217 - (void) setTitle:(NSString *)title;
1220 /* Status Delegation {{{ */
1222 public pkgAcquireStatus
1225 _transient NSObject<ProgressDelegate> *delegate_;
1235 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1236 delegate_ = delegate;
1239 NSObject<ProgressDelegate> *getDelegate() const {
1243 virtual bool MediaChange(std::string media, std::string drive) {
1247 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1250 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1251 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1252 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:@"STATUS" forItem:item]);
1253 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1256 virtual void Done(pkgAcquire::ItemDesc &item) {
1259 virtual void Fail(pkgAcquire::ItemDesc &item) {
1261 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1262 item.Owner->Status == pkgAcquire::Item::StatDone
1266 std::string &error(item.Owner->ErrorText);
1270 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:@"ERROR" forItem:item]);
1271 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1274 virtual bool Pulse(pkgAcquire *Owner) {
1275 bool value = pkgAcquireStatus::Pulse(Owner);
1278 double(CurrentBytes + CurrentItems) /
1279 double(TotalBytes + TotalItems)
1282 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1283 [NSNumber numberWithDouble:percent], @"Percent",
1285 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1286 [NSNumber numberWithDouble:TotalBytes], @"Total",
1287 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1288 nil] waitUntilDone:YES];
1290 if (value && ![delegate_ isProgressCancelled])
1298 _finline bool WasCancelled() const {
1302 virtual void Start() {
1303 pkgAcquireStatus::Start();
1304 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1307 virtual void Stop() {
1308 pkgAcquireStatus::Stop();
1309 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1310 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1314 /* Database Interface {{{ */
1315 typedef std::map< unsigned long, _H<Source> > SourceMap;
1317 @interface Database : NSObject {
1323 pkgCacheFile cache_;
1324 pkgDepCache::Policy *policy_;
1325 pkgRecords *records_;
1326 pkgProblemResolver *resolver_;
1327 pkgAcquire *fetcher_;
1329 SPtr<pkgPackageManager> manager_;
1330 pkgSourceList *list_;
1332 SourceMap sourceMap_;
1333 NSMutableArray *sourceList_;
1335 CFMutableArrayRef packages_;
1337 _transient NSObject<DatabaseDelegate> *delegate_;
1338 _transient NSObject<ProgressDelegate> *progress_;
1346 std::map<const char *, _H<NSString> > sections_;
1349 + (Database *) sharedInstance;
1352 - (void) _readCydia:(NSNumber *)fd;
1353 - (void) _readStatus:(NSNumber *)fd;
1354 - (void) _readOutput:(NSNumber *)fd;
1358 - (Package *) packageWithName:(NSString *)name;
1360 - (pkgCacheFile &) cache;
1361 - (pkgDepCache::Policy *) policy;
1362 - (pkgRecords *) records;
1363 - (pkgProblemResolver *) resolver;
1364 - (pkgAcquire &) fetcher;
1365 - (pkgSourceList &) list;
1366 - (NSArray *) packages;
1367 - (NSArray *) sources;
1368 - (Source *) sourceWithKey:(NSString *)key;
1369 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1377 - (void) updateWithStatus:(Status &)status;
1379 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1381 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1382 - (NSObject<ProgressDelegate> *) progressDelegate;
1384 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1386 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1390 /* ProgressEvent Implementation {{{ */
1391 @implementation CydiaProgressEvent
1393 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1394 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1397 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1398 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1399 [event setPackage:package];
1403 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1404 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1406 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1407 NSArray *fields([description componentsSeparatedByString:@" "]);
1408 [event setItem:fields];
1410 if ([fields count] > 3) {
1411 [event setPackage:[fields objectAtIndex:2]];
1412 [event setVersion:[fields objectAtIndex:3]];
1415 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1420 + (NSArray *) _attributeKeys {
1421 return [NSArray arrayWithObjects:
1431 - (NSArray *) attributeKeys {
1432 return [[self class] _attributeKeys];
1435 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1436 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1439 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1440 if ((self = [super init]) != nil) {
1446 - (NSString *) message {
1450 - (NSString *) type {
1454 - (NSArray *) item {
1455 return (id) item_ ?: [NSNull null];
1458 - (void) setItem:(NSArray *)item {
1462 - (NSString *) package {
1463 return (id) package_ ?: [NSNull null];
1466 - (void) setPackage:(NSString *)package {
1470 - (NSString *) url {
1471 return (id) url_ ?: [NSNull null];
1474 - (void) setURL:(NSString *)url {
1478 - (void) setVersion:(NSString *)version {
1482 - (NSString *) version {
1483 return (id) version_ ?: [NSNull null];
1486 - (NSString *) compound:(NSString *)value {
1488 NSString *mode(nil); {
1489 NSString *type([self type]);
1490 if ([type isEqualToString:@"ERROR"])
1491 mode = UCLocalize("ERROR");
1492 else if ([type isEqualToString:@"WARNING"])
1493 mode = UCLocalize("WARNING");
1497 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1503 - (NSString *) compoundMessage {
1504 return [self compound:[self message]];
1507 - (NSString *) compoundTitle {
1510 if (package_ == nil)
1512 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1513 title = [package name];
1517 return [self compound:title];
1523 // Cytore Definitions {{{
1524 struct PackageValue :
1527 Cytore::Offset<PackageValue> next_;
1529 uint32_t index_ : 23;
1530 uint32_t subscribed_ : 1;
1547 Cytore::Offset<PackageValue> packages_[1 << 16];
1550 static Cytore::File<MetaValue> MetaFile_;
1552 // Cytore Helper Functions {{{
1553 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1554 SplitHash nhash = { hashlittle(name, length) };
1556 PackageValue *metadata;
1558 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1559 offset: if (offset->IsNull()) {
1560 *offset = MetaFile_.New<PackageValue>(length + 1);
1561 metadata = &MetaFile_.Get(*offset);
1563 if (metadata == NULL) {
1567 metadata = new PackageValue();
1568 memset(metadata, 0, sizeof(*metadata));
1571 memcpy(metadata->name_, name, length + 1);
1572 metadata->nhash_ = nhash.u16[1];
1574 metadata = &MetaFile_.Get(*offset);
1576 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1577 offset = &metadata->next_;
1585 static void PackageImport(const void *key, const void *value, void *context) {
1586 bool &fail(*reinterpret_cast<bool *>(context));
1589 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1590 NSLog(@"failed to import package %@", key);
1594 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1595 NSDictionary *package((NSDictionary *) value);
1597 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1598 if ([subscribed boolValue] && !metadata->subscribed_)
1599 metadata->subscribed_ = true;
1601 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1602 time_t time([date timeIntervalSince1970]);
1603 if (metadata->first_ > time || metadata->first_ == 0)
1604 metadata->first_ = time;
1607 NSDate *date([package objectForKey:@"LastSeen"]);
1608 NSString *version([package objectForKey:@"LastVersion"]);
1610 if (date != nil && version != nil) {
1611 time_t time([date timeIntervalSince1970]);
1612 if (metadata->last_ < time || metadata->last_ == 0)
1613 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1614 size_t length(strlen(buffer));
1615 uint16_t vhash(hashlittle(buffer, length));
1617 size_t capped(std::min<size_t>(8, length));
1618 char *latest(buffer + length - capped);
1620 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1621 metadata->vhash_ = vhash;
1623 metadata->last_ = time;
1629 /* Source Class {{{ */
1630 @interface Source : NSObject {
1631 CYString depiction_;
1632 CYString description_;
1638 CYString distribution_;
1643 NSString *authority_;
1645 CYString defaultIcon_;
1647 NSDictionary *record_;
1651 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1653 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1655 - (NSString *) depictionForPackage:(NSString *)package;
1656 - (NSString *) supportForPackage:(NSString *)package;
1658 - (NSDictionary *) record;
1662 - (NSString *) distribution;
1663 - (NSString *) type;
1665 - (NSString *) host;
1667 - (NSString *) name;
1668 - (NSString *) description;
1669 - (NSString *) label;
1670 - (NSString *) origin;
1671 - (NSString *) version;
1673 - (NSString *) defaultIcon;
1677 @implementation Source
1681 distribution_.clear();
1684 description_.clear();
1690 defaultIcon_.clear();
1692 if (record_ != nil) {
1702 if (authority_ != nil) {
1703 [authority_ release];
1709 // XXX: this is a very inefficient way to call these deconstructors
1714 + (NSArray *) _attributeKeys {
1715 return [NSArray arrayWithObjects:
1730 - (NSArray *) attributeKeys {
1731 return [[self class] _attributeKeys];
1734 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1735 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1738 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1741 trusted_ = index->IsTrusted();
1743 uri_.set(pool, index->GetURI());
1744 distribution_.set(pool, index->GetDist());
1745 type_.set(pool, index->GetType());
1747 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1748 if (dindex != NULL) {
1750 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1753 pkgTagFile tags(&fd);
1755 pkgTagSection section;
1762 {"default-icon", &defaultIcon_},
1763 {"depiction", &depiction_},
1764 {"description", &description_},
1766 {"origin", &origin_},
1767 {"support", &support_},
1768 {"version", &version_},
1771 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1772 const char *start, *end;
1774 if (section.Find(names[i].name_, start, end)) {
1775 CYString &value(*names[i].value_);
1776 value.set(pool, start, end - start);
1782 record_ = [Sources_ objectForKey:[self key]];
1784 record_ = [record_ retain];
1786 NSURL *url([NSURL URLWithString:uri_]);
1790 host_ = [[host_ lowercaseString] retain];
1795 authority_ = [url path];
1797 if (authority_ != nil)
1798 authority_ = [authority_ retain];
1801 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1802 if ((self = [super init]) != nil) {
1803 [self setMetaIndex:index inPool:pool];
1807 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1808 NSDictionary *lhr = [self record];
1809 NSDictionary *rhr = [source record];
1812 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1814 NSString *lhs = [self name];
1815 NSString *rhs = [source name];
1817 if ([lhs length] != 0 && [rhs length] != 0) {
1818 unichar lhc = [lhs characterAtIndex:0];
1819 unichar rhc = [rhs characterAtIndex:0];
1821 if (isalpha(lhc) && !isalpha(rhc))
1822 return NSOrderedAscending;
1823 else if (!isalpha(lhc) && isalpha(rhc))
1824 return NSOrderedDescending;
1827 return [lhs compare:rhs options:LaxCompareOptions_];
1830 - (NSString *) depictionForPackage:(NSString *)package {
1831 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1834 - (NSString *) supportForPackage:(NSString *)package {
1835 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1838 - (NSDictionary *) record {
1846 - (NSString *) uri {
1850 - (NSString *) distribution {
1851 return distribution_;
1854 - (NSString *) type {
1858 - (NSString *) key {
1859 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1862 - (NSString *) host {
1866 - (NSString *) name {
1867 return origin_.empty() ? authority_ : origin_;
1870 - (NSString *) description {
1871 return description_;
1874 - (NSString *) label {
1875 return label_.empty() ? authority_ : label_;
1878 - (NSString *) origin {
1882 - (NSString *) version {
1886 - (NSString *) defaultIcon {
1887 return defaultIcon_;
1892 /* CydiaOperation Class {{{ */
1893 @interface CydiaOperation : NSObject {
1894 NSString *operator_;
1898 - (NSString *) operator;
1899 - (NSString *) value;
1903 @implementation CydiaOperation
1906 [operator_ release];
1911 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1912 if ((self = [super init]) != nil) {
1913 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1914 value_ = [[NSString alloc] initWithUTF8String:value];
1918 + (NSArray *) _attributeKeys {
1919 return [NSArray arrayWithObjects:
1925 - (NSArray *) attributeKeys {
1926 return [[self class] _attributeKeys];
1929 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1930 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1933 - (NSString *) operator {
1937 - (NSString *) value {
1943 /* CydiaClause Class {{{ */
1944 @interface CydiaClause : NSObject {
1946 CydiaOperation *version_;
1949 - (NSString *) package;
1950 - (CydiaOperation *) version;
1954 @implementation CydiaClause
1962 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1963 if ((self = [super init]) != nil) {
1964 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1966 if (const char *version = dep.TargetVer())
1967 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1969 version_ = [[NSNull null] retain];
1973 + (NSArray *) _attributeKeys {
1974 return [NSArray arrayWithObjects:
1980 - (NSArray *) attributeKeys {
1981 return [[self class] _attributeKeys];
1984 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1985 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1988 - (NSString *) package {
1992 - (CydiaOperation *) version {
1998 /* CydiaRelation Class {{{ */
1999 @interface CydiaRelation : NSObject {
2000 NSString *relationship_;
2001 NSMutableArray *clauses_;
2004 - (NSString *) relationship;
2005 - (NSArray *) clauses;
2009 @implementation CydiaRelation
2012 [relationship_ release];
2017 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2018 if ((self = [super init]) != nil) {
2019 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
2020 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
2022 pkgCache::DepIterator start;
2023 pkgCache::DepIterator end;
2024 dep.GlobOr(start, end); // ++dep
2027 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2029 // yes, seriously. (wtf?)
2037 + (NSArray *) _attributeKeys {
2038 return [NSArray arrayWithObjects:
2044 - (NSArray *) attributeKeys {
2045 return [[self class] _attributeKeys];
2048 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2049 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2052 - (NSString *) relationship {
2053 return relationship_;
2056 - (NSArray *) clauses {
2060 - (void) addClause:(CydiaClause *)clause {
2061 [clauses_ addObject:clause];
2066 /* Package Class {{{ */
2067 struct ParsedPackage {
2072 CYString depiction_;
2082 @interface Package : NSObject {
2085 uint32_t essential_ : 1;
2086 uint32_t obsolete_ : 1;
2087 uint32_t ignored_ : 1;
2091 _transient Database *database_;
2093 pkgCache::VerIterator version_;
2094 pkgCache::PkgIterator iterator_;
2095 pkgCache::VerFileIterator file_;
2101 CYString installed_;
2103 const char *section_;
2104 _transient NSString *section$_;
2108 PackageValue *metadata_;
2109 ParsedPackage *parsed_;
2111 NSMutableArray *tags_;
2114 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2115 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2117 - (pkgCache::PkgIterator) iterator;
2120 - (NSString *) section;
2121 - (NSString *) simpleSection;
2123 - (NSString *) longSection;
2124 - (NSString *) shortSection;
2128 - (Address *) maintainer;
2130 - (NSString *) longDescription;
2131 - (NSString *) shortDescription;
2134 - (PackageValue *) metadata;
2137 - (bool) subscribed;
2138 - (bool) setSubscribed:(bool)subscribed;
2142 - (NSString *) latest;
2143 - (NSString *) installed;
2144 - (BOOL) uninstalled;
2147 - (BOOL) upgradableAndEssential:(BOOL)essential;
2150 - (BOOL) unfiltered;
2154 - (BOOL) halfConfigured;
2155 - (BOOL) halfInstalled;
2157 - (NSString *) mode;
2160 - (NSString *) name;
2162 - (NSString *) homepage;
2163 - (NSString *) depiction;
2164 - (Address *) author;
2166 - (NSString *) support;
2168 - (NSArray *) files;
2169 - (NSArray *) warnings;
2170 - (NSArray *) applications;
2172 - (Source *) source;
2174 - (BOOL) matches:(NSString *)text;
2176 - (bool) hasSupportingRole;
2177 - (BOOL) hasTag:(NSString *)tag;
2178 - (NSString *) primaryPurpose;
2179 - (NSArray *) purposes;
2180 - (bool) isCommercial;
2182 - (void) setIndex:(size_t)index;
2184 - (CYString &) cyname;
2186 - (uint32_t) compareBySection:(NSArray *)sections;
2191 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2192 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2193 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2194 - (bool) isVisibleInSection:(NSString *)section;
2195 - (bool) isVisibleInSource:(Source *)source;
2199 uint32_t PackageChangesRadix(Package *self, void *) {
2204 uint32_t timestamp : 30;
2205 uint32_t ignored : 1;
2206 uint32_t upgradable : 1;
2210 bool upgradable([self upgradableAndEssential:YES]);
2211 value.bits.upgradable = upgradable ? 1 : 0;
2214 value.bits.timestamp = 0;
2215 value.bits.ignored = [self ignored] ? 0 : 1;
2216 value.bits.upgradable = 1;
2218 value.bits.timestamp = [self seen] >> 2;
2219 value.bits.ignored = 0;
2220 value.bits.upgradable = 0;
2223 return _not(uint32_t) - value.key;
2226 uint32_t PackagePrefixRadix(Package *self, void *context) {
2227 size_t offset(reinterpret_cast<size_t>(context));
2228 CYString &name([self cyname]);
2230 size_t size(name.size());
2233 char *text(name.data());
2236 if (!isdigit(text[0]))
2240 while (size != digits && isdigit(text[digits]))
2248 if (offset == 0 && zeros != 0) {
2249 memset(data, '0', zeros);
2250 memcpy(data + zeros, text, 4 - zeros);
2252 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2253 if (size <= offset - zeros)
2256 text += offset - zeros;
2257 size -= offset - zeros;
2260 memcpy(data, text, 4);
2262 memcpy(data, text, size);
2263 memset(data + size, 0, 4 - size);
2266 for (size_t i(0); i != 4; ++i)
2267 if (isalpha(data[i]))
2275 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2277 /* XXX: ntohl may be more honest */
2278 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2281 CYString &(*PackageName)(Package *self, SEL sel);
2283 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2284 _profile(PackageNameCompare)
2285 CYString &lhi(PackageName(lhs, @selector(cyname)));
2286 CYString &rhi(PackageName(rhs, @selector(cyname)));
2287 CFStringRef lhn(lhi), rhn(rhi);
2290 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2291 else if (rhn == NULL)
2292 return NSOrderedDescending;
2294 _profile(PackageNameCompare$NumbersLast)
2295 if (!lhi.empty() && !rhi.empty()) {
2296 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2297 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2298 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2299 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2300 return lha ? NSOrderedAscending : NSOrderedDescending;
2304 CFIndex length = CFStringGetLength(lhn);
2306 _profile(PackageNameCompare$Compare)
2307 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2312 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2313 return PackageNameCompare(*lhs, *rhs, context);
2316 struct PackageNameOrdering :
2317 std::binary_function<Package *, Package *, bool>
2319 _finline bool operator ()(Package *lhs, Package *rhs) const {
2320 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2324 @implementation Package
2326 - (NSString *) description {
2327 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2331 if (parsed_ != NULL)
2340 + (NSString *) webScriptNameForSelector:(SEL)selector {
2342 else if (selector == @selector(clear))
2344 else if (selector == @selector(getField:))
2346 else if (selector == @selector(hasTag:))
2348 else if (selector == @selector(install))
2350 else if (selector == @selector(remove))
2356 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2357 return [self webScriptNameForSelector:selector] == nil;
2360 + (NSArray *) _attributeKeys {
2361 return [NSArray arrayWithObjects:
2379 @"shortDescription",
2390 - (NSArray *) attributeKeys {
2391 return [[self class] _attributeKeys];
2394 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2395 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2398 - (NSArray *) relations {
2399 @synchronized (database_) {
2400 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2401 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2402 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2406 - (NSString *) getField:(NSString *)name {
2407 @synchronized (database_) {
2408 if ([database_ era] != era_ || file_.end())
2411 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2413 const char *start, *end;
2414 if (!parser.Find([name UTF8String], start, end))
2415 return (NSString *) [NSNull null];
2417 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2421 if (parsed_ != NULL)
2423 @synchronized (database_) {
2424 if ([database_ era] != era_ || file_.end())
2427 ParsedPackage *parsed(new ParsedPackage);
2430 _profile(Package$parse)
2431 pkgRecords::Parser *parser;
2433 _profile(Package$parse$Lookup)
2434 parser = &[database_ records]->Lookup(file_);
2439 _profile(Package$parse$Find)
2444 {"icon", &parsed->icon_},
2445 {"depiction", &parsed->depiction_},
2446 {"homepage", &parsed->homepage_},
2447 {"website", &website},
2448 {"bugs", &parsed->bugs_},
2449 {"support", &parsed->support_},
2450 {"sponsor", &parsed->sponsor_},
2451 {"author", &parsed->author_},
2454 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2455 const char *start, *end;
2457 if (parser->Find(names[i].name_, start, end)) {
2458 CYString &value(*names[i].value_);
2459 _profile(Package$parse$Value)
2460 value.set(pool_, start, end - start);
2466 _profile(Package$parse$Tagline)
2467 const char *start, *end;
2468 if (parser->ShortDesc(start, end)) {
2469 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2472 while (stop != start && stop[-1] == '\r')
2474 parsed->tagline_.set(pool_, start, stop - start);
2478 _profile(Package$parse$Retain)
2479 if (parsed->homepage_.empty())
2480 parsed->homepage_ = website;
2481 if (parsed->homepage_ == parsed->depiction_)
2482 parsed->homepage_.clear();
2487 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2488 if ((self = [super init]) != nil) {
2489 _profile(Package$initWithVersion)
2492 database_ = database;
2493 era_ = [database era];
2497 pkgCache::PkgIterator iterator(version.ParentPkg());
2498 iterator_ = iterator;
2500 _profile(Package$initWithVersion$Version)
2501 if (!version_.end())
2502 file_ = version_.FileList();
2504 pkgCache &cache([database_ cache]);
2505 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2509 _profile(Package$initWithVersion$Cache)
2510 name_.set(NULL, iterator.Display());
2512 latest_.set(NULL, StripVersion_(version_.VerStr()));
2514 pkgCache::VerIterator current(iterator.CurrentVer());
2516 installed_.set(NULL, StripVersion_(current.VerStr()));
2519 _profile(Package$initWithVersion$Tags)
2520 pkgCache::TagIterator tag(iterator.TagList());
2522 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2524 const char *name(tag.Name());
2525 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2527 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2528 if (strcmp(name + 6, "enduser") == 0)
2530 else if (strcmp(name + 6, "hacker") == 0)
2532 else if (strcmp(name + 6, "developer") == 0)
2534 else if (strcmp(name + 6, "cydia") == 0)
2540 if (strncmp(name, "cydia::", 7) == 0) {
2541 if (strcmp(name + 7, "essential") == 0)
2543 else if (strcmp(name + 7, "obsolete") == 0)
2548 } while (!tag.end());
2552 _profile(Package$initWithVersion$Metadata)
2553 const char *mixed(iterator.Name());
2554 size_t size(strlen(mixed));
2555 char lower[size + 1];
2557 for (size_t i(0); i != size; ++i)
2558 lower[i] = mixed[i] | 0x20;
2561 PackageValue *metadata(PackageFind(lower, size));
2562 metadata_ = metadata;
2564 id_.set(NULL, metadata->name_, size);
2566 const char *latest(version_.VerStr());
2567 size_t length(strlen(latest));
2569 uint16_t vhash(hashlittle(latest, length));
2571 size_t capped(std::min<size_t>(8, length));
2572 latest = latest + length - capped;
2574 if (metadata->first_ == 0)
2575 metadata->first_ = now_;
2577 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2578 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2579 metadata->vhash_ = vhash;
2580 metadata->last_ = now_;
2581 } else if (metadata->last_ == 0)
2582 metadata->last_ = metadata->first_;
2585 _profile(Package$initWithVersion$Section)
2586 section_ = iterator.Section();
2589 _profile(Package$initWithVersion$Flags)
2590 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2591 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2596 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2597 pkgCache::VerIterator version;
2599 _profile(Package$packageWithIterator$GetCandidateVer)
2600 version = [database policy]->GetCandidateVer(iterator);
2608 _profile(Package$packageWithIterator$Allocate)
2609 package = [Package allocWithZone:zone];
2612 _profile(Package$packageWithIterator$Initialize)
2614 initWithVersion:version
2621 _profile(Package$packageWithIterator$Autorelease)
2622 package = [package autorelease];
2628 - (pkgCache::PkgIterator) iterator {
2632 - (NSString *) section {
2633 if (section$_ == nil) {
2634 if (section_ == NULL)
2637 _profile(Package$section$mappedSectionForPointer)
2638 section$_ = [database_ mappedSectionForPointer:section_];
2643 - (NSString *) simpleSection {
2644 if (NSString *section = [self section])
2645 return Simplify(section);
2650 - (NSString *) longSection {
2651 return LocalizeSection([self section]);
2654 - (NSString *) shortSection {
2655 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2658 - (NSString *) uri {
2661 pkgIndexFile *index;
2662 pkgCache::PkgFileIterator file(file_.File());
2663 if (![database_ list].FindIndex(file, index))
2665 return [NSString stringWithUTF8String:iterator_->Path];
2666 //return [NSString stringWithUTF8String:file.Site()];
2667 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2671 - (Address *) maintainer {
2672 @synchronized (database_) {
2673 if ([database_ era] != era_ || file_.end())
2676 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2677 const std::string &maintainer(parser->Maintainer());
2678 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2682 @synchronized (database_) {
2683 if ([database_ era] != era_ || version_.end())
2686 return version_->InstalledSize;
2689 - (NSString *) longDescription {
2690 @synchronized (database_) {
2691 if ([database_ era] != era_ || file_.end())
2694 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2695 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2697 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2698 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2699 if ([lines count] < 2)
2702 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2703 for (size_t i(1), e([lines count]); i != e; ++i) {
2704 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2705 [trimmed addObject:trim];
2708 return [trimmed componentsJoinedByString:@"\n"];
2711 - (NSString *) shortDescription {
2712 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2716 _profile(Package$index)
2717 CFStringRef name((CFStringRef) [self name]);
2718 if (CFStringGetLength(name) == 0)
2720 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2721 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2723 return toupper(character);
2727 - (PackageValue *) metadata {
2732 PackageValue *metadata([self metadata]);
2733 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2736 - (bool) subscribed {
2737 return [self metadata]->subscribed_;
2740 - (bool) setSubscribed:(bool)subscribed {
2741 PackageValue *metadata([self metadata]);
2742 if (metadata->subscribed_ == subscribed)
2744 metadata->subscribed_ = subscribed;
2752 - (NSString *) latest {
2756 - (NSString *) installed {
2760 - (BOOL) uninstalled {
2761 return installed_.empty();
2765 return !version_.end();
2768 - (BOOL) upgradableAndEssential:(BOOL)essential {
2769 _profile(Package$upgradableAndEssential)
2770 pkgCache::VerIterator current(iterator_.CurrentVer());
2772 return essential && essential_;
2774 return !version_.end() && version_ != current;
2778 - (BOOL) essential {
2783 return [database_ cache][iterator_].InstBroken();
2786 - (BOOL) unfiltered {
2787 _profile(Package$unfiltered$obsolete)
2788 if (_unlikely(obsolete_))
2792 _profile(Package$unfiltered$hasSupportingRole)
2793 if (_unlikely(![self hasSupportingRole]))
2801 if (![self unfiltered])
2806 _profile(Package$visible$section)
2807 section = [self section];
2810 _profile(Package$visible$isSectionVisible)
2811 if (!isSectionVisible(section))
2819 unsigned char current(iterator_->CurrentState);
2820 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2823 - (BOOL) halfConfigured {
2824 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2827 - (BOOL) halfInstalled {
2828 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2832 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2833 return state.Mode != pkgDepCache::ModeKeep;
2836 - (NSString *) mode {
2837 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2839 switch (state.Mode) {
2840 case pkgDepCache::ModeDelete:
2841 if ((state.iFlags & pkgDepCache::Purge) != 0)
2845 case pkgDepCache::ModeKeep:
2846 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2847 return @"REINSTALL";
2848 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2852 case pkgDepCache::ModeInstall:
2853 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2854 return @"REINSTALL";
2855 else*/ switch (state.Status) {
2857 return @"DOWNGRADE";
2863 return @"NEW_INSTALL";
2874 - (NSString *) name {
2875 return name_.empty() ? id_ : name_;
2878 - (UIImage *) icon {
2879 NSString *section = [self simpleSection];
2882 if (parsed_ != NULL)
2883 if (NSString *href = parsed_->icon_)
2884 if ([href hasPrefix:@"file:///"])
2885 // XXX: correct escaping
2886 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2887 if (icon == nil) if (section != nil)
2888 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2889 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2890 if ([dicon hasPrefix:@"file:///"])
2891 // XXX: correct escaping
2892 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2894 icon = [UIImage applicationImageNamed:@"unknown.png"];
2898 - (NSString *) homepage {
2899 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2902 - (NSString *) depiction {
2903 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2906 - (Address *) sponsor {
2907 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2910 - (Address *) author {
2911 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2914 - (NSString *) support {
2915 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2918 - (NSArray *) files {
2919 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2920 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2923 fin.open([path UTF8String]);
2928 while (std::getline(fin, line))
2929 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2934 - (NSArray *) warnings {
2935 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2936 const char *name(iterator_.Name());
2938 size_t length(strlen(name));
2939 if (length < 2) invalid:
2940 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2941 else for (size_t i(0); i != length; ++i)
2943 /* XXX: technically this is not allowed */
2944 (name[i] < 'A' || name[i] > 'Z') &&
2945 (name[i] < 'a' || name[i] > 'z') &&
2946 (name[i] < '0' || name[i] > '9') &&
2947 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2950 if (strcmp(name, "cydia") != 0) {
2953 bool _private = false;
2956 bool repository = [[self section] isEqualToString:@"Repositories"];
2958 if (NSArray *files = [self files])
2959 for (NSString *file in files)
2960 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2962 else if (!user && [file isEqualToString:@"/User"])
2964 else if (!_private && [file isEqualToString:@"/private"])
2966 else if (!stash && [file isEqualToString:@"/var/stash"])
2969 /* XXX: this is not sensitive enough. only some folders are valid. */
2970 if (cydia && !repository)
2971 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2973 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2975 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2977 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2980 return [warnings count] == 0 ? nil : warnings;
2983 - (NSArray *) applications {
2984 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2986 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2988 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2989 if (NSArray *files = [self files])
2990 for (NSString *file in files)
2991 if (application_r(file)) {
2992 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2993 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2994 if ([id isEqualToString:me])
2997 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2999 display = application_r[1];
3001 NSString *bundle([file stringByDeletingLastPathComponent]);
3002 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3003 if (icon == nil || [icon length] == 0)
3005 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3007 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3008 [applications addObject:application];
3010 [application addObject:id];
3011 [application addObject:display];
3012 [application addObject:url];
3015 return [applications count] == 0 ? nil : applications;
3018 - (Source *) source {
3019 if (source_ == nil) {
3020 @synchronized (database_) {
3021 if ([database_ era] != era_ || file_.end())
3022 source_ = (Source *) [NSNull null];
3024 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
3028 return source_ == (Source *) [NSNull null] ? nil : source_;
3031 - (BOOL) matches:(NSString *)text {
3037 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
3038 if (range.location != NSNotFound)
3041 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
3042 if (range.location != NSNotFound)
3047 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
3048 if (range.location != NSNotFound)
3054 - (bool) hasSupportingRole {
3059 if ([Role_ isEqualToString:@"User"])
3063 if ([Role_ isEqualToString:@"Hacker"])
3067 if ([Role_ isEqualToString:@"Developer"])
3072 - (BOOL) hasTag:(NSString *)tag {
3073 return tags_ == nil ? NO : [tags_ containsObject:tag];
3076 - (NSString *) primaryPurpose {
3077 for (NSString *tag in tags_)
3078 if ([tag hasPrefix:@"purpose::"])
3079 return [tag substringFromIndex:9];
3083 - (NSArray *) purposes {
3084 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3085 for (NSString *tag in tags_)
3086 if ([tag hasPrefix:@"purpose::"])
3087 [purposes addObject:[tag substringFromIndex:9]];
3088 return [purposes count] == 0 ? nil : purposes;
3091 - (bool) isCommercial {
3092 return [self hasTag:@"cydia::commercial"];
3095 - (void) setIndex:(size_t)index {
3096 if (metadata_->index_ != index)
3097 metadata_->index_ = index;
3100 - (CYString &) cyname {
3101 return name_.empty() ? id_ : name_;
3104 - (uint32_t) compareBySection:(NSArray *)sections {
3105 NSString *section([self section]);
3106 for (size_t i(0), e([sections count]); i != e; ++i) {
3107 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3111 return _not(uint32_t);
3115 @synchronized (database_) {
3116 pkgProblemResolver *resolver = [database_ resolver];
3117 resolver->Clear(iterator_);
3119 pkgCacheFile &cache([database_ cache]);
3120 cache->SetReInstall(iterator_, false);
3121 cache->MarkKeep(iterator_, false);
3125 @synchronized (database_) {
3126 pkgProblemResolver *resolver = [database_ resolver];
3127 resolver->Clear(iterator_);
3128 resolver->Protect(iterator_);
3130 pkgCacheFile &cache([database_ cache]);
3131 cache->SetReInstall(iterator_, false);
3132 cache->MarkInstall(iterator_, false);
3134 pkgDepCache::StateCache &state((*cache)[iterator_]);
3135 if (!state.Install())
3136 cache->SetReInstall(iterator_, true);
3140 @synchronized (database_) {
3141 pkgProblemResolver *resolver = [database_ resolver];
3142 resolver->Clear(iterator_);
3143 resolver->Remove(iterator_);
3144 resolver->Protect(iterator_);
3146 pkgCacheFile &cache([database_ cache]);
3147 cache->SetReInstall(iterator_, false);
3148 cache->MarkDelete(iterator_, true);
3151 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3152 _profile(Package$isUnfilteredAndSearchedForBy)
3155 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3156 value &= [self unfiltered];
3159 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3160 value &= [self matches:search];
3167 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3168 if ([search length] == 0)
3171 _profile(Package$isUnfilteredAndSelectedForBy)
3174 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3175 value &= [self unfiltered];
3178 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3179 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3186 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3187 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3190 - (bool) isVisibleInSection:(NSString *)name {
3191 NSString *section([self section]);
3195 section == nil && [name length] == 0 ||
3196 [name isEqualToString:section]
3197 ) && [self visible];
3200 - (bool) isVisibleInSource:(Source *)source {
3201 return [self source] == source && [self visible];
3206 /* Section Class {{{ */
3207 @interface Section : NSObject {
3212 NSString *localized_;
3215 - (NSComparisonResult) compareByLocalized:(Section *)section;
3216 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3217 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3218 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3219 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3220 - (NSString *) name;
3227 - (void) addToCount;
3229 - (void) setCount:(size_t)count;
3230 - (NSString *) localized;
3234 @implementation Section
3238 if (localized_ != nil)
3239 [localized_ release];
3243 - (NSComparisonResult) compareByLocalized:(Section *)section {
3244 NSString *lhs(localized_);
3245 NSString *rhs([section localized]);
3247 /*if ([lhs length] != 0 && [rhs length] != 0) {
3248 unichar lhc = [lhs characterAtIndex:0];
3249 unichar rhc = [rhs characterAtIndex:0];
3251 if (isalpha(lhc) && !isalpha(rhc))
3252 return NSOrderedAscending;
3253 else if (!isalpha(lhc) && isalpha(rhc))
3254 return NSOrderedDescending;
3257 return [lhs compare:rhs options:LaxCompareOptions_];
3260 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3261 if ((self = [self initWithName:name localize:NO]) != nil) {
3262 if (localized != nil)
3263 localized_ = [localized retain];
3267 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3268 return [self initWithName:name row:0 localize:localize];
3271 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3272 if ((self = [super init]) != nil) {
3273 name_ = [name retain];
3277 localized_ = [LocalizeSection(name_) retain];
3281 /* XXX: localize the index thingees */
3282 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3283 if ((self = [super init]) != nil) {
3284 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3290 - (NSString *) name {
3310 - (void) addToCount {
3314 - (void) setCount:(size_t)count {
3318 - (NSString *) localized {
3325 static NSString *Colon_;
3326 static NSString *Elision_;
3327 static NSString *Error_;
3328 static NSString *Warning_;
3330 /* Database Implementation {{{ */
3331 @implementation Database
3333 + (Database *) sharedInstance {
3334 static Database *instance;
3335 if (instance == nil)
3336 instance = [[Database alloc] init];
3344 - (void) releasePackages {
3345 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3346 CFArrayRemoveAllValues(packages_);
3350 // XXX: actually implement this thing
3352 [sourceList_ release];
3353 [self releasePackages];
3354 apr_pool_destroy(pool_);
3355 NSRecycleZone(zone_);
3359 - (void) _readCydia:(NSNumber *)fd { _pooled
3360 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3361 std::istream is(&ib);
3364 static Pcre finish_r("^finish:([^:]*)$");
3366 while (std::getline(is, line)) {
3367 const char *data(line.c_str());
3368 size_t size = line.size();
3369 lprintf("C:%s\n", data);
3371 if (finish_r(data, size)) {
3372 NSString *finish = finish_r[1];
3373 int index = [Finishes_ indexOfObject:finish];
3374 if (index != INT_MAX && index > Finish_)
3382 - (void) _readStatus:(NSNumber *)fd { _pooled
3383 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3384 std::istream is(&ib);
3387 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3388 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3390 while (std::getline(is, line)) {
3391 const char *data(line.c_str());
3392 size_t size(line.size());
3393 lprintf("S:%s\n", data);
3395 if (conffile_r(data, size))
3396 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3397 else if (strncmp(data, "status: ", 8) == 0) {
3398 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:@"STATUS"]);
3399 [progress_ performSelectorOnMainThread:@selector(addProgressEvent) withObject:event waitUntilDone:YES];
3400 } else if (pmstatus_r(data, size)) {
3401 std::string type([pmstatus_r[1] UTF8String]);
3403 NSString *package = pmstatus_r[2];
3404 if ([package isEqualToString:@"dpkg-exec"])
3407 float percent([pmstatus_r[3] floatValue]);
3408 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3410 NSString *string = pmstatus_r[4];
3412 if (type == "pmerror") {
3413 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"ERROR" forPackage:package]);
3414 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3415 } else if (type == "pmstatus") {
3416 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"STATUS" forPackage:package]);
3417 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3418 } else if (type == "pmconffile")
3419 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3421 lprintf("E:unknown pmstatus\n");
3423 lprintf("E:unknown status\n");
3429 - (void) _readOutput:(NSNumber *)fd { _pooled
3430 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3431 std::istream is(&ib);
3434 while (std::getline(is, line)) {
3435 lprintf("O:%s\n", line.c_str());
3437 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:@"INFORMATION"]);
3438 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3448 - (Package *) packageWithName:(NSString *)name {
3449 @synchronized (self) {
3450 if (static_cast<pkgDepCache *>(cache_) == NULL)
3452 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3453 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3457 if ((self = [super init]) != nil) {
3464 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3465 apr_pool_create(&pool_, NULL);
3467 size_t capacity(MetaFile_->active_);
3473 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3474 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3478 _assert(pipe(fds) != -1);
3481 _config->Set("APT::Keep-Fds::", cydiafd_);
3482 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3485 detachNewThreadSelector:@selector(_readCydia:)
3487 withObject:[NSNumber numberWithInt:fds[0]]
3490 _assert(pipe(fds) != -1);
3494 detachNewThreadSelector:@selector(_readStatus:)
3496 withObject:[NSNumber numberWithInt:fds[0]]
3499 _assert(pipe(fds) != -1);
3500 _assert(dup2(fds[0], 0) != -1);
3501 _assert(close(fds[0]) != -1);
3503 input_ = fdopen(fds[1], "a");
3505 _assert(pipe(fds) != -1);
3506 _assert(dup2(fds[1], 1) != -1);
3507 _assert(close(fds[1]) != -1);
3510 detachNewThreadSelector:@selector(_readOutput:)
3512 withObject:[NSNumber numberWithInt:fds[0]]
3517 - (pkgCacheFile &) cache {
3521 - (pkgDepCache::Policy *) policy {
3525 - (pkgRecords *) records {
3529 - (pkgProblemResolver *) resolver {
3533 - (pkgAcquire &) fetcher {
3537 - (pkgSourceList &) list {
3541 - (NSArray *) packages {
3542 return (NSArray *) packages_;
3545 - (NSArray *) sources {
3549 - (Source *) sourceWithKey:(NSString *)key {
3550 for (Source *source in [self sources]) {
3551 if ([[source key] isEqualToString:key])
3556 - (bool) popErrorWithTitle:(NSString *)title {
3559 while (!_error->empty()) {
3561 bool warning(!_error->PopMessage(error));
3566 size_t size(error.size());
3567 if (size == 0 || error[size - 1] != '\n')
3569 error.resize(size - 1);
3572 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3574 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3580 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3581 return [self popErrorWithTitle:title] || !success;
3584 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3585 @synchronized (self) {
3588 [self releasePackages];
3591 [sourceList_ removeAllObjects];
3611 apr_pool_clear(pool_);
3613 NSRecycleZone(zone_);
3614 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3616 int chk(creat("/tmp/cydia.chk", 0644));
3620 if (invocation != nil)
3621 [invocation invoke];
3623 NSString *title(UCLocalize("DATABASE"));
3626 OpProgress progress;
3627 while (!cache_.Open(progress, true)) { pop:
3629 bool warning(!_error->PopMessage(error));
3630 lprintf("cache_.Open():[%s]\n", error.c_str());
3632 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3633 [delegate_ repairWithSelector:@selector(configure)];
3634 else if (error == "The package lists or status file could not be parsed or opened.")
3635 [delegate_ repairWithSelector:@selector(update)];
3636 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3637 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3638 // else if (error == "Malformed Status line")
3639 // else if (error == "The list of sources could not be read.")
3641 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3651 unlink("/tmp/cydia.chk");
3653 now_ = [[NSDate date] timeIntervalSince1970];
3655 policy_ = new pkgDepCache::Policy();
3656 records_ = new pkgRecords(cache_);
3657 resolver_ = new pkgProblemResolver(cache_);
3658 fetcher_ = new pkgAcquire(&status_);
3661 list_ = new pkgSourceList();
3662 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3665 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3666 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:@"ERROR"] forTask:title];
3670 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3673 if (cache_->BrokenCount() != 0) {
3674 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3677 if (cache_->BrokenCount() != 0) {
3678 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:@"ERROR"] forTask:title];
3682 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3686 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3687 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3688 [sourceList_ addObject:object];
3690 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3691 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3692 // XXX: this could be more intelligent
3693 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3694 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3696 sourceMap_[cached->ID] = object;
3701 /*std::vector<Package *> packages;
3702 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3703 [packages_ release];
3708 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3709 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3710 //packages.push_back(package);
3711 CFArrayAppendValue(packages_, [package retain]);
3715 /*if (packages.empty())
3716 packages_ = [[NSArray alloc] init];
3718 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3721 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3722 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3723 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3731 /*if (!packages.empty())
3732 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3733 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3735 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3737 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3739 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3743 size_t count(CFArrayGetCount(packages_));
3744 MetaFile_->active_ = count;
3746 for (size_t index(0); index != count; ++index)
3747 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3751 } } CYPoolEnd() _trace(); }
3754 @synchronized (self) {
3756 resolver_ = new pkgProblemResolver(cache_);
3758 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3759 if (!cache_[iterator].Keep())
3760 cache_->MarkKeep(iterator, false);
3761 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3762 cache_->SetReInstall(iterator, false);
3765 - (void) configure {
3766 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3768 system([dpkg UTF8String]);
3773 // XXX: I don't remember this condition
3778 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3780 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3782 if ([self popErrorWithTitle:title])
3786 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3789 public pkgArchiveCleaner
3792 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3797 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3804 fetcher_->Shutdown();
3806 pkgRecords records(cache_);
3808 lock_ = new FileFd();
3809 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3811 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3813 if ([self popErrorWithTitle:title])
3817 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3820 manager_ = (_system->CreatePM(cache_));
3821 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3828 bool substrate(RestartSubstrate_);
3829 RestartSubstrate_ = false;
3831 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3833 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3835 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3837 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3838 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3841 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3843 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3845 [self popErrorWithTitle:title];
3849 bool failed = false;
3850 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3851 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3853 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3859 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3867 RestartSubstrate_ = true;
3870 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3872 if (_error->PendingError()) {
3877 if (result == pkgPackageManager::Failed) {
3882 if (result != pkgPackageManager::Completed) {
3887 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3889 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3891 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3892 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3895 if (![before isEqualToArray:after])
3900 NSString *title(UCLocalize("UPGRADE"));
3901 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3907 [self updateWithStatus:status_];
3910 - (void) updateWithStatus:(Status &)status {
3911 NSString *title(UCLocalize("REFRESHING_DATA"));
3914 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3918 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3919 if ([self popErrorWithTitle:title])
3922 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3924 bool success(ListUpdate(status, list, PulseInterval_));
3925 if (status.WasCancelled())
3928 [self popErrorWithTitle:title forOperation:success];
3930 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3932 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3936 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3937 delegate_ = delegate;
3940 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3941 progress_ = delegate;
3942 status_.setDelegate(delegate);
3945 - (NSObject<ProgressDelegate> *) progressDelegate {
3949 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3950 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3951 return i == sourceMap_.end() ? nil : i->second;
3954 - (NSString *) mappedSectionForPointer:(const char *)section {
3955 _H<NSString> *mapped;
3957 _profile(Database$mappedSectionForPointer$Cache)
3958 mapped = §ions_[section];
3961 if (*mapped == NULL) {
3962 size_t length(strlen(section));
3963 char spaced[length + 1];
3965 _profile(Database$mappedSectionForPointer$Replace)
3966 for (size_t index(0); index != length; ++index)
3967 spaced[index] = section[index] == '_' ? ' ' : section[index];
3968 spaced[length] = '\0';
3973 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3974 string = [NSString stringWithUTF8String:spaced];
3977 _profile(Database$mappedSectionForPointer$Map)
3978 string = [SectionMap_ objectForKey:string] ?: string;
3988 /* Web Scripting {{{ */
3989 @interface CydiaObject : NSObject {
3991 _transient id delegate_;
3994 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3998 @implementation CydiaObject
4001 [indirect_ release];
4005 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4006 if ((self = [super init]) != nil) {
4007 indirect_ = [indirect retain];
4011 - (void) setDelegate:(id)delegate {
4012 delegate_ = delegate;
4015 + (NSArray *) _attributeKeys {
4016 return [NSArray arrayWithObjects:
4031 - (NSArray *) attributeKeys {
4032 return [[self class] _attributeKeys];
4035 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4036 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4039 - (NSString *) version {
4043 - (NSString *) device {
4044 return [[UIDevice currentDevice] uniqueIdentifier];
4047 - (NSString *) firmware {
4048 return [[UIDevice currentDevice] systemVersion];
4051 - (NSString *) hostname {
4052 return [[UIDevice currentDevice] name];
4055 - (NSString *) idiom {
4056 return (id) Idiom_ ?: [NSNull null];
4059 - (NSString *) plmn {
4060 return (id) PLMN_ ?: [NSNull null];
4063 - (NSString *) ecid {
4064 return (id) ChipID_ ?: [NSNull null];
4067 - (NSString *) serial {
4068 return SerialNumber_;
4071 - (NSString *) role {
4072 return (id) Role_ ?: [NSNull null];
4075 - (NSString *) model {
4076 return [NSString stringWithUTF8String:Machine_];
4079 - (NSString *) token {
4080 return (id) Token_ ?: [NSNull null];
4083 + (NSString *) webScriptNameForSelector:(SEL)selector {
4085 else if (selector == @selector(addTrivialSource:))
4086 return @"addTrivialSource";
4087 else if (selector == @selector(close))
4089 else if (selector == @selector(du:))
4091 else if (selector == @selector(stringWithFormat:arguments:))
4093 else if (selector == @selector(getAllSources))
4094 return @"getAllSourcs";
4095 else if (selector == @selector(getKernelNumber:))
4096 return @"getKernelNumber";
4097 else if (selector == @selector(getKernelString:))
4098 return @"getKernelString";
4099 else if (selector == @selector(getInstalledPackages))
4100 return @"getInstalledPackages";
4101 else if (selector == @selector(getPackageById:))
4102 return @"getPackageById";
4103 else if (selector == @selector(installPackages:))
4104 return @"installPackages";
4105 else if (selector == @selector(localizedStringForKey:value:table:))
4107 else if (selector == @selector(refreshSources))
4108 return @"refreshSources";
4109 else if (selector == @selector(removeButton))
4110 return @"removeButton";
4111 else if (selector == @selector(scrollToBottom:))
4112 return @"scrollToBottom";
4113 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4114 return @"setButtonImage";
4115 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4116 return @"setButtonTitle";
4117 else if (selector == @selector(setHidesBackButton:))
4118 return @"setHidesBackButton";
4119 else if (selector == @selector(setNavigationBarStyle:))
4120 return @"setNavigationBarStyle";
4121 else if (selector == @selector(setPopupHook:))
4122 return @"setPopupHook";
4123 else if (selector == @selector(setToken:))
4125 else if (selector == @selector(setViewportWidth:))
4126 return @"setViewportWidth";
4127 else if (selector == @selector(statfs:))
4129 else if (selector == @selector(supports:))
4135 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4136 return [self webScriptNameForSelector:selector] == nil;
4139 - (BOOL) supports:(NSString *)feature {
4140 return [feature isEqualToString:@"window.open"];
4143 - (NSNumber *) getKernelNumber:(NSString *)name {
4144 const char *string([name UTF8String]);
4147 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4148 return (id) [NSNull null];
4150 if (size != sizeof(int))
4151 return (id) [NSNull null];
4154 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4155 return (id) [NSNull null];
4157 return [NSNumber numberWithInt:value];
4160 - (NSString *) getKernelString:(NSString *)name {
4161 const char *string([name UTF8String]);
4164 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4165 return (id) [NSNull null];
4167 char value[size + 1];
4168 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4169 return (id) [NSNull null];
4171 // XXX: just in case you request something ludicrous
4174 return [NSString stringWithCString:value];
4177 - (void) addTrivialSource:(NSString *)href {
4178 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4181 - (void) refreshSources {
4182 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4185 - (NSArray *) getAllSources {
4186 return [[Database sharedInstance] sources];
4189 - (NSArray *) getInstalledPackages {
4190 Database *database([Database sharedInstance]);
4191 @synchronized (database) {
4192 NSArray *packages([database packages]);
4193 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4194 for (Package *package in packages)
4195 if (![package uninstalled])
4196 [installed addObject:package];
4200 - (Package *) getPackageById:(NSString *)id {
4201 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4205 return (Package *) [NSNull null];
4208 - (NSArray *) statfs:(NSString *)path {
4211 if (path == nil || statfs([path UTF8String], &stat) == -1)
4214 return [NSArray arrayWithObjects:
4215 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4216 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4217 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4221 - (NSNumber *) du:(NSString *)path {
4222 NSNumber *value(nil);
4225 _assert(pipe(fds) != -1);
4227 pid_t pid(ExecFork());
4229 _assert(dup2(fds[1], 1) != -1);
4230 _assert(close(fds[0]) != -1);
4231 _assert(close(fds[1]) != -1);
4232 /* XXX: this should probably not use du */
4233 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4238 _assert(close(fds[1]) != -1);
4240 if (FILE *du = fdopen(fds[0], "r")) {
4242 while (fgets(line, sizeof(line), du) != NULL) {
4243 size_t length(strlen(line));
4244 while (length != 0 && line[length - 1] == '\n')
4245 line[--length] = '\0';
4246 if (char *tab = strchr(line, '\t')) {
4248 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4253 } else _assert(close(fds[0]));
4257 if (waitpid(pid, &status, 0) == -1)
4260 else _assert(false);
4266 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4269 - (void) installPackages:(NSArray *)packages {
4270 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4273 - (void) removeButton {
4274 [indirect_ removeButton];
4277 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4278 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4281 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4282 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4285 - (void) setHidesBackButton:(NSString *)value {
4286 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4289 - (void) setNavigationBarStyle:(NSString *)value {
4290 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4293 - (void) _setToken:(NSString *)token {
4297 [Metadata_ removeObjectForKey:@"Token"];
4299 [Metadata_ setObject:Token_ forKey:@"Token"];
4304 - (void) setToken:(NSString *)token {
4305 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4308 - (void) setPopupHook:(id)function {
4309 [indirect_ setPopupHook:function];
4312 - (void) scrollToBottom:(NSNumber *)animated {
4313 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4316 - (void) setViewportWidth:(float)width {
4317 [indirect_ setViewportWidthOnMainThread:width];
4320 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4321 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4322 unsigned count([arguments count]);
4324 for (unsigned i(0); i != count; ++i)
4325 values[i] = [arguments objectAtIndex:i];
4326 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4329 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4330 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4332 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4334 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4340 /* @ Loading... Indicator {{{ */
4341 @interface CYLoadingIndicator : UIView {
4342 _H<UIActivityIndicatorView> spinner_;
4344 _H<UIView> container_;
4347 @property (readonly, nonatomic) UILabel *label;
4348 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4352 @implementation CYLoadingIndicator
4354 - (id) initWithFrame:(CGRect)frame {
4355 if ((self = [super initWithFrame:frame]) != nil) {
4356 container_ = [[[UIView alloc] init] autorelease];
4357 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4359 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4360 [spinner_ startAnimating];
4361 [container_ addSubview:spinner_];
4363 label_ = [[[UILabel alloc] init] autorelease];
4364 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4365 [label_ setBackgroundColor:[UIColor clearColor]];
4366 [label_ setTextColor:[UIColor blackColor]];
4367 [label_ setShadowColor:[UIColor whiteColor]];
4368 [label_ setShadowOffset:CGSizeMake(0, 1)];
4369 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4370 [container_ addSubview:label_];
4372 CGSize viewsize = frame.size;
4373 CGSize spinnersize = [spinner_ bounds].size;
4374 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4375 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4377 CGRect containrect = {
4378 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4379 CGSizeMake(bothwidth, spinnersize.height)
4382 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4390 [container_ setFrame:containrect];
4391 [spinner_ setFrame:spinrect];
4392 [label_ setFrame:textrect];
4393 [self addSubview:container_];
4397 - (UILabel *) label {
4401 - (UIActivityIndicatorView *) activityIndicatorView {
4407 /* Emulated Loading Controller {{{ */
4408 @interface CYEmulatedLoadingController : CYViewController {
4409 _transient Database *database_;
4410 _H<CYLoadingIndicator> indicator_;
4411 _H<UITabBar> tabbar_;
4412 _H<UINavigationBar> navbar_;
4417 @implementation CYEmulatedLoadingController
4419 - (id) initWithDatabase:(Database *)database {
4420 if ((self = [super init]) != nil) {
4421 database_ = database;
4426 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4427 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4429 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4430 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4431 [[self view] addSubview:indicator_];
4433 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4434 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4435 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4436 [[self view] addSubview:tabbar_];
4438 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4439 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4440 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4441 [[self view] addSubview:navbar_];
4444 - (void) releaseSubviews {
4453 /* Cydia Browser Controller {{{ */
4454 @interface CYBrowserController : BrowserController {
4455 CydiaObject *cydia_;
4460 @implementation CYBrowserController
4467 - (NSURL *) navigationURL {
4468 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4471 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4474 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4475 [super webView:view didClearWindowObject:window forFrame:frame];
4477 WebDataSource *source([frame dataSource]);
4478 NSURLResponse *response([source response]);
4480 NSURL *url([response URL]);
4481 NSString *scheme([url scheme]);
4482 NSString *host([url host]);
4484 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4485 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4486 NSDictionary *headers([http allHeaderFields]);
4487 [self setHeaders:headers forHost:host];
4491 [host isEqualToString:@"cydia.saurik.com"] ||
4492 [host hasSuffix:@".cydia.saurik.com"] ||
4493 [scheme isEqualToString:@"file"]
4495 [window setValue:cydia_ forKey:@"cydia"];
4498 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4499 if (System_ != NULL)
4500 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4501 if (Machine_ != NULL)
4502 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4504 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4506 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4509 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4510 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4511 [self _setMoreHeaders:copy];
4515 - (void) setDelegate:(id)delegate {
4516 [super setDelegate:delegate];
4517 [cydia_ setDelegate:delegate];
4521 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4522 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4524 WebView *webview([[webview_ _documentView] webView]);
4526 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4529 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4531 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4532 if (Product_ != nil)
4533 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4535 [webview setApplicationNameForUserAgent:application];
4543 @interface NSObject (CydiaScript)
4544 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4547 @implementation NSObject (CydiaScript)
4549 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4555 @implementation NSArray (CydiaScript)
4557 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4558 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4559 for (size_t i(0), e([self count]); i != e; ++i)
4560 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4566 @implementation NSDictionary (CydiaScript)
4568 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4569 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4571 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4578 /* Confirmation Controller {{{ */
4579 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4580 if (!iterator.end())
4581 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4582 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4584 pkgCache::PkgIterator package(dep.TargetPkg());
4587 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4594 @protocol ConfirmationControllerDelegate
4595 - (void) cancelAndClear:(bool)clear;
4596 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4600 @interface ConfirmationController : CYBrowserController {
4601 _transient Database *database_;
4603 UIAlertView *essential_;
4605 NSDictionary *changes_;
4606 NSMutableArray *issues_;
4607 NSDictionary *sizes_;
4612 - (id) initWithDatabase:(Database *)database;
4616 @implementation ConfirmationController
4623 if (essential_ != nil)
4624 [essential_ release];
4631 RestartSubstrate_ = true;
4632 [delegate_ confirmWithNavigationController:[self navigationController]];
4635 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4636 NSString *context([alert context]);
4638 if ([context isEqualToString:@"remove"]) {
4639 if (button == [alert cancelButtonIndex])
4640 [self dismissModalViewControllerAnimated:YES];
4641 else if (button == [alert firstOtherButtonIndex]) {
4645 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4646 } else if ([context isEqualToString:@"unable"]) {
4647 [self dismissModalViewControllerAnimated:YES];
4648 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4650 [super alertView:alert clickedButtonAtIndex:button];
4654 - (void) _doContinue {
4655 [self dismissModalViewControllerAnimated:YES];
4656 [delegate_ cancelAndClear:NO];
4659 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4660 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4664 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4665 [super webView:view didClearWindowObject:window forFrame:frame];
4667 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4668 changes_, @"changes",
4672 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4675 - (id) initWithDatabase:(Database *)database {
4676 if ((self = [super init]) != nil) {
4677 database_ = database;
4679 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4680 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4681 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4682 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4683 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4687 pkgCacheFile &cache([database_ cache]);
4688 NSArray *packages([database_ packages]);
4689 pkgDepCache::Policy *policy([database_ policy]);
4691 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4693 for (Package *package in packages) {
4694 pkgCache::PkgIterator iterator([package iterator]);
4695 NSString *name([package id]);
4697 if ([package broken]) {
4698 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4700 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4702 reasons, @"reasons",
4705 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4709 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4710 pkgCache::DepIterator start;
4711 pkgCache::DepIterator end;
4712 dep.GlobOr(start, end); // ++dep
4714 if (!cache->IsImportantDep(end))
4716 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4719 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4721 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4722 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4723 clauses, @"clauses",
4727 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4729 pkgCache::PkgIterator target(start.TargetPkg());
4730 if (target->ProvidesList != 0)
4731 reason = @"missing";
4733 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4735 reason = @"installed";
4736 installed = [NSString stringWithUTF8String:ver.VerStr()];
4737 } else if (!cache[target].CandidateVerIter(cache).end())
4738 reason = @"uninstalled";
4739 else if (target->ProvidesList == 0)
4740 reason = @"uninstallable";
4742 reason = @"virtual";
4745 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4746 [NSString stringWithUTF8String:start.CompType()], @"operator",
4747 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4750 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4751 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4752 version, @"version",
4754 installed, @"installed",
4757 // yes, seriously. (wtf?)
4765 pkgDepCache::StateCache &state(cache[iterator]);
4767 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4769 if (state.NewInstall())
4770 [installs addObject:name];
4771 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4772 [reinstalls addObject:name];
4773 else if (state.Upgrade())
4774 [upgrades addObject:name];
4775 else if (state.Downgrade())
4776 [downgrades addObject:name];
4777 else if (!state.Delete())
4779 else if (special_r(name))
4780 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4781 [NSNull null], @"package",
4782 [NSArray arrayWithObjects:
4783 [NSDictionary dictionaryWithObjectsAndKeys:
4784 @"Conflicts", @"relationship",
4785 [NSArray arrayWithObjects:
4786 [NSDictionary dictionaryWithObjectsAndKeys:
4788 [NSNull null], @"version",
4789 @"installed", @"reason",
4796 if ([package essential])
4798 [removes addObject:name];
4801 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4802 substrate_ |= DepSubstrate(iterator.CurrentVer());
4807 else if (Advanced_) {
4808 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4810 essential_ = [[UIAlertView alloc]
4811 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4812 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4814 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4816 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4820 [essential_ setContext:@"remove"];
4822 essential_ = [[UIAlertView alloc]
4823 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4824 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4826 cancelButtonTitle:UCLocalize("OKAY")
4827 otherButtonTitles:nil
4830 [essential_ setContext:@"unable"];
4833 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4834 installs, @"installs",
4835 reinstalls, @"reinstalls",
4836 upgrades, @"upgrades",
4837 downgrades, @"downgrades",
4838 removes, @"removes",
4841 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4842 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4843 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4846 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4848 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4849 initWithTitle:UCLocalize("CANCEL")
4850 style:UIBarButtonItemStylePlain
4852 action:@selector(cancelButtonClicked)
4858 - (void) applyRightButton {
4859 if ([issues_ count] == 0 && ![self isLoading])
4860 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4861 initWithTitle:UCLocalize("CONFIRM")
4862 style:UIBarButtonItemStyleDone
4864 action:@selector(confirmButtonClicked)
4867 [[self navigationItem] setRightBarButtonItem:nil];
4871 - (void) cancelButtonClicked {
4872 [self dismissModalViewControllerAnimated:YES];
4873 [delegate_ cancelAndClear:YES];
4877 - (void) confirmButtonClicked {
4878 if (essential_ != nil)
4888 /* Progress Data {{{ */
4889 @interface CydiaProgressData : NSObject {
4890 _transient id delegate_;
4899 _H<NSMutableArray> events_;
4900 _H<NSString> title_;
4902 _H<NSString> status_;
4903 _H<NSString> finish_;
4908 @implementation CydiaProgressData
4910 + (NSArray *) _attributeKeys {
4911 return [NSArray arrayWithObjects:
4923 - (NSArray *) attributeKeys {
4924 return [[self class] _attributeKeys];
4927 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4928 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4932 if ((self = [super init]) != nil) {
4933 events_ = [NSMutableArray arrayWithCapacity:32];
4937 - (void) setDelegate:(id)delegate {
4938 delegate_ = delegate;
4941 - (void) setPercent:(float)value {
4945 - (NSNumber *) percent {
4946 return [NSNumber numberWithFloat:percent_];
4949 - (void) setCurrent:(float)value {
4953 - (NSNumber *) current {
4954 return [NSNumber numberWithFloat:current_];
4957 - (void) setTotal:(float)value {
4961 - (NSNumber *) total {
4962 return [NSNumber numberWithFloat:total_];
4965 - (void) setSpeed:(float)value {
4969 - (NSNumber *) speed {
4970 return [NSNumber numberWithFloat:speed_];
4973 - (NSArray *) events {
4977 - (void) removeAllEvents {
4978 [events_ removeAllObjects];
4981 - (void) addEvent:(CydiaProgressEvent *)event {
4982 [events_ addObject:event];
4985 - (void) setTitle:(NSString *)text {
4989 - (NSString *) title {
4993 - (void) setFinish:(NSString *)text {
4997 - (NSString *) finish {
4998 return (id) finish_ ?: [NSNull null];
5001 - (void) setRunning:(bool)running {
5005 - (NSNumber *) running {
5006 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5011 /* Progress Controller {{{ */
5012 @interface ProgressController : CYBrowserController <
5015 _transient Database *database_;
5016 _H<CydiaProgressData> progress_;
5020 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5022 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5024 - (void) setTitle:(NSString *)title;
5025 - (void) setCancellable:(bool)cancellable;
5029 @implementation ProgressController
5032 [database_ setProgressDelegate:nil];
5033 [progress_ setDelegate:nil];
5037 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5038 if ((self = [super init]) != nil) {
5039 database_ = database;
5040 delegate_ = delegate;
5042 [database_ setProgressDelegate:self];
5044 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5045 [progress_ setDelegate:self];
5049 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5050 [super webView:view didClearWindowObject:window forFrame:frame];
5051 [window setValue:progress_ forKey:@"cydiaProgress"];
5054 - (void) updateProgress {
5055 [self dispatchEvent:@"CydiaProgressUpdate"];
5058 - (void) updateCancel {
5059 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5060 initWithTitle:UCLocalize("CANCEL")
5061 style:UIBarButtonItemStylePlain
5063 action:@selector(cancel)
5064 ] autorelease] : nil)];
5067 - (void) viewWillAppear:(BOOL)animated {
5068 if (![self hasLoaded]) {
5069 [scroller_ setBackgroundColor:[UIColor blackColor]];
5070 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/progress/", UI_]]];
5073 [super viewDidAppear:animated];
5075 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5077 [[self navigationItem] setHidesBackButton:YES];
5079 [self updateCancel];
5083 UpdateExternalStatus(0);
5090 [delegate_ terminateWithSuccess];
5091 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5092 [delegate_ suspendWithAnimation:YES];
5094 [delegate_ suspend];*/
5106 system("/usr/bin/sbreload");
5112 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5113 SBReboot(SBSSpringBoardServerPort());
5115 reboot2(RB_AUTOBOOT);
5122 - (void) setTitle:(NSString *)title {
5123 [progress_ setTitle:title];
5124 [self updateProgress];
5127 - (UIBarButtonItem *) rightButton {
5128 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5129 initWithTitle:UCLocalize("CLOSE")
5130 style:UIBarButtonItemStylePlain
5132 action:@selector(close)
5136 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5137 UpdateExternalStatus(1);
5139 [progress_ setRunning:true];
5140 [self setTitle:title];
5141 // implicit updateProgress
5143 SHA1SumValue notifyconf; {
5145 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5148 MMap mmap(file, MMap::ReadOnly);
5150 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5151 notifyconf = sha1.Result();
5155 SHA1SumValue springlist; {
5157 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5160 MMap mmap(file, MMap::ReadOnly);
5162 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5163 springlist = sha1.Result();
5167 if (invocation != nil) {
5168 [invocation yieldToSelector:@selector(invoke)];
5169 [self setTitle:@"COMPLETE"];
5174 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5177 MMap mmap(file, MMap::ReadOnly);
5179 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5180 if (!(notifyconf == sha1.Result()))
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 if (!(springlist == sha1.Result()))
5199 if (RestartSubstrate_)
5203 RestartSubstrate_ = false;
5206 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5207 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5208 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5209 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5210 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5214 system("su -c /usr/bin/uicache mobile");
5217 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5219 [progress_ setRunning:false];
5220 [self updateProgress];
5222 [self applyRightButton];
5225 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5226 [progress_ addEvent:event];
5227 [self updateProgress];
5230 - (bool) isProgressCancelled {
5231 return cancel_ == 2;
5236 [self updateCancel];
5239 - (void) setCancellable:(bool)cancellable {
5240 unsigned cancel(cancel_);
5244 else if (cancel_ == 0)
5247 if (cancel != cancel_)
5248 [self updateCancel];
5251 - (void) setProgressCancellable:(NSNumber *)cancellable {
5252 [self setCancellable:[cancellable boolValue]];
5255 - (void) setProgressPercent:(NSNumber *)percent {
5256 [progress_ setPercent:[percent floatValue]];
5257 [self updateProgress];
5260 - (void) setProgressStatus:(NSDictionary *)status {
5261 if (status == nil) {
5262 [progress_ setCurrent:0];
5263 [progress_ setTotal:0];
5264 [progress_ setSpeed:0];
5266 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5268 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5269 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5270 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5273 [self updateProgress];
5279 /* Cell Content View {{{ */
5280 @protocol ContentDelegate
5281 - (void) drawContentRect:(CGRect)rect;
5284 @interface ContentView : UIView {
5285 _transient id<ContentDelegate> delegate_;
5290 @implementation ContentView
5292 - (id) initWithFrame:(CGRect)frame {
5293 if ((self = [super initWithFrame:frame]) != nil) {
5294 [self setNeedsDisplayOnBoundsChange:YES];
5298 - (void) setDelegate:(id<ContentDelegate>)delegate {
5299 delegate_ = delegate;
5302 - (void) drawRect:(CGRect)rect {
5303 [super drawRect:rect];
5304 [delegate_ drawContentRect:rect];
5309 /* Cydia TableView Cell {{{ */
5310 @interface CYTableViewCell : UITableViewCell {
5311 ContentView *content_;
5317 @implementation CYTableViewCell
5324 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5325 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5327 if (view == content_) {
5328 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5329 highlighted_ = highlighted;
5332 [super _updateHighlightColorsForView:view highlighted:highlighted];
5335 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5336 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5337 highlighted_ = selected;
5339 [super setSelected:selected animated:animated];
5340 [content_ setNeedsDisplay];
5346 /* Package Cell {{{ */
5347 @interface PackageCell : CYTableViewCell <
5352 NSString *description_;
5360 - (PackageCell *) init;
5361 - (void) setPackage:(Package *)package;
5363 - (void) drawContentRect:(CGRect)rect;
5367 @implementation PackageCell
5369 - (void) clearPackage {
5380 if (description_ != nil) {
5381 [description_ release];
5385 if (source_ != nil) {
5390 if (badge_ != nil) {
5395 if (placard_ != nil) {
5405 [self clearPackage];
5409 - (PackageCell *) init {
5410 CGRect frame(CGRectMake(0, 0, 320, 74));
5411 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5412 UIView *content([self contentView]);
5413 CGRect bounds([content bounds]);
5415 content_ = [[ContentView alloc] initWithFrame:bounds];
5416 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5417 [content addSubview:content_];
5419 [content_ setDelegate:self];
5420 [content_ setOpaque:YES];
5424 - (NSString *) accessibilityLabel {
5425 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5428 - (void) setPackage:(Package *)package {
5429 [self clearPackage];
5432 Source *source = [package source];
5434 icon_ = [[package icon] retain];
5435 name_ = [[package name] retain];
5438 description_ = [package longDescription];
5439 if (description_ == nil)
5440 description_ = [package shortDescription];
5441 if (description_ != nil)
5442 description_ = [description_ retain];
5444 commercial_ = [package isCommercial];
5446 package_ = [package retain];
5448 NSString *label = nil;
5449 bool trusted = false;
5451 if (source != nil) {
5452 label = [source label];
5453 trusted = [source trusted];
5454 } else if ([[package id] isEqualToString:@"firmware"])
5455 label = UCLocalize("APPLE");
5457 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5459 NSString *from(label);
5461 NSString *section = [package simpleSection];
5462 if (section != nil && ![section isEqualToString:label]) {
5463 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5464 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5467 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5468 source_ = [from retain];
5470 if (NSString *purpose = [package primaryPurpose])
5471 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5472 badge_ = [badge_ retain];
5477 if (NSString *mode = [package_ mode]) {
5478 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5479 color = RemovingColor_;
5480 //placard = @"removing";
5482 color = InstallingColor_;
5483 //placard = @"installing";
5486 // XXX: the removing/installing placards are not @2x
5489 color = [UIColor whiteColor];
5491 if ([package installed] != nil)
5492 placard = @"installed";
5497 [content_ setBackgroundColor:color];
5500 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5501 placard_ = [placard_ retain];
5503 [self setNeedsDisplay];
5504 [content_ setNeedsDisplay];
5507 - (void) drawContentRect:(CGRect)rect {
5508 bool highlighted(highlighted_);
5509 float width([self bounds].size.width);
5512 CGContextRef context(UIGraphicsGetCurrentContext());
5513 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5514 CGContextFillRect(context, rect);
5519 rect.size = [icon_ size];
5521 rect.size.width /= 2;
5522 rect.size.height /= 2;
5524 rect.origin.x = 25 - rect.size.width / 2;
5525 rect.origin.y = 25 - rect.size.height / 2;
5527 [icon_ drawInRect:rect];
5530 if (badge_ != nil) {
5532 rect.size = [badge_ size];
5534 rect.size.width /= 2;
5535 rect.size.height /= 2;
5537 rect.origin.x = 36 - rect.size.width / 2;
5538 rect.origin.y = 36 - rect.size.height / 2;
5540 [badge_ drawInRect:rect];
5547 UISetColor(commercial_ ? Purple_ : Black_);
5548 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5549 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5552 UISetColor(commercial_ ? Purplish_ : Gray_);
5553 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5555 if (placard_ != nil)
5556 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5561 /* Section Cell {{{ */
5562 @interface SectionCell : CYTableViewCell <
5574 - (void) setSection:(Section *)section editing:(BOOL)editing;
5578 @implementation SectionCell
5580 - (void) clearSection {
5581 if (basic_ != nil) {
5586 if (section_ != nil) {
5596 if (count_ != nil) {
5603 [self clearSection];
5609 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5610 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5611 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5612 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5613 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5615 UIView *content([self contentView]);
5616 CGRect bounds([content bounds]);
5618 content_ = [[ContentView alloc] initWithFrame:bounds];
5619 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5620 [content addSubview:content_];
5621 [content_ setBackgroundColor:[UIColor whiteColor]];
5623 [content_ setDelegate:self];
5627 - (void) onSwitch:(id)sender {
5628 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5629 if (metadata == nil) {
5630 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5631 [Sections_ setObject:metadata forKey:basic_];
5634 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5638 - (void) setSection:(Section *)section editing:(BOOL)editing {
5639 if (editing != editing_) {
5641 [switch_ removeFromSuperview];
5643 [self addSubview:switch_];
5647 [self clearSection];
5649 if (section == nil) {
5650 name_ = [UCLocalize("ALL_PACKAGES") retain];
5653 basic_ = [section name];
5655 basic_ = [basic_ retain];
5657 section_ = [section localized];
5658 if (section_ != nil)
5659 section_ = [section_ retain];
5661 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5662 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5665 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5668 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5669 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5671 [content_ setNeedsDisplay];
5674 - (void) setFrame:(CGRect)frame {
5675 [super setFrame:frame];
5677 CGRect rect([switch_ frame]);
5678 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5681 - (NSString *) accessibilityLabel {
5685 - (void) drawContentRect:(CGRect)rect {
5686 bool highlighted(highlighted_ && !editing_);
5688 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5693 float width(rect.size.width);
5699 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5701 CGSize size = [count_ sizeWithFont:Font14_];
5705 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5711 /* File Table {{{ */
5712 @interface FileTable : CYViewController <
5713 UITableViewDataSource,
5716 _transient Database *database_;
5719 NSMutableArray *files_;
5723 - (id) initWithDatabase:(Database *)database;
5724 - (void) setPackage:(Package *)package;
5728 @implementation FileTable
5731 [self releaseSubviews];
5740 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5741 return files_ == nil ? 0 : [files_ count];
5744 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5748 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5749 static NSString *reuseIdentifier = @"Cell";
5751 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5753 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5754 [cell setFont:[UIFont systemFontOfSize:16]];
5756 [cell setText:[files_ objectAtIndex:indexPath.row]];
5757 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5762 - (NSURL *) navigationURL {
5763 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5767 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5769 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5770 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5771 [list_ setRowHeight:24.0f];
5772 [list_ setDataSource:self];
5773 [list_ setDelegate:self];
5774 [[self view] addSubview:list_];
5777 - (void) viewDidLoad {
5778 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5781 - (void) releaseSubviews {
5786 - (id) initWithDatabase:(Database *)database {
5787 if ((self = [super init]) != nil) {
5788 database_ = database;
5790 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5794 - (void) setPackage:(Package *)package {
5795 if (package_ != nil) {
5796 [package_ autorelease];
5805 [files_ removeAllObjects];
5807 if (package != nil) {
5808 package_ = [package retain];
5809 name_ = [[package id] retain];
5811 if (NSArray *files = [package files])
5812 [files_ addObjectsFromArray:files];
5814 if ([files_ count] != 0) {
5815 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5816 [files_ removeObjectAtIndex:0];
5817 [files_ sortUsingSelector:@selector(compareByPath:)];
5819 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5820 [stack addObject:@"/"];
5822 for (int i(0), e([files_ count]); i != e; ++i) {
5823 NSString *file = [files_ objectAtIndex:i];
5824 while (![file hasPrefix:[stack lastObject]])
5825 [stack removeLastObject];
5826 NSString *directory = [stack lastObject];
5827 [stack addObject:[file stringByAppendingString:@"/"]];
5828 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5829 ([stack count] - 2) * 3, "",
5830 [file substringFromIndex:[directory length]]
5839 - (void) reloadData {
5842 [self setPackage:[database_ packageWithName:name_]];
5847 /* Package Controller {{{ */
5848 @interface CYPackageController : CYBrowserController <
5849 UIActionSheetDelegate
5851 _transient Database *database_;
5855 NSMutableArray *buttons_;
5856 UIBarButtonItem *button_;
5859 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5863 @implementation CYPackageController
5866 if (package_ != nil)
5879 - (NSURL *) navigationURL {
5880 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", name_]];
5883 /* XXX: this is not safe at all... localization of /fail/ */
5884 - (void) _clickButtonWithName:(NSString *)name {
5885 if ([name isEqualToString:UCLocalize("CLEAR")])
5886 [delegate_ clearPackage:package_];
5887 else if ([name isEqualToString:UCLocalize("INSTALL")])
5888 [delegate_ installPackage:package_];
5889 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5890 [delegate_ installPackage:package_];
5891 else if ([name isEqualToString:UCLocalize("REMOVE")])
5892 [delegate_ removePackage:package_];
5893 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5894 [delegate_ installPackage:package_];
5895 else _assert(false);
5898 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5899 NSString *context([sheet context]);
5901 if ([context isEqualToString:@"modify"]) {
5902 if (button != [sheet cancelButtonIndex]) {
5903 NSString *buttonName = [buttons_ objectAtIndex:button];
5904 [self _clickButtonWithName:buttonName];
5907 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5911 - (bool) _allowJavaScriptPanel {
5916 - (void) _customButtonClicked {
5917 int count([buttons_ count]);
5922 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5924 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5925 [buttons addObjectsFromArray:buttons_];
5927 UIActionSheet *sheet = [[[UIActionSheet alloc]
5930 cancelButtonTitle:nil
5931 destructiveButtonTitle:nil
5932 otherButtonTitles:nil
5935 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5937 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5938 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5940 [sheet setContext:@"modify"];
5942 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5946 // We don't want to allow non-commercial packages to do custom things to the install button,
5947 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5948 - (void) customButtonClicked {
5950 [super customButtonClicked];
5952 [self _customButtonClicked];
5955 - (void) reloadButtonClicked {
5956 // Don't reload a commerical package by tapping the loading button,
5957 // but if it's not an Install button, we should forward it on.
5958 if (![package_ uninstalled])
5959 [self _customButtonClicked];
5962 - (void) applyLoadingTitle {
5963 // Don't show "Loading" as the title. Ever.
5966 - (UIBarButtonItem *) rightButton {
5971 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5972 if ((self = [super init]) != nil) {
5973 database_ = database;
5974 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5975 name_ = [[NSString alloc] initWithString:name];
5976 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5980 - (void) reloadData {
5981 if (package_ != nil)
5982 [package_ autorelease];
5983 package_ = [database_ packageWithName:name_];
5985 [buttons_ removeAllObjects];
5987 if (package_ != nil) {
5990 package_ = [package_ retain];
5991 commercial_ = [package_ isCommercial];
5993 if ([package_ mode] != nil)
5994 [buttons_ addObject:UCLocalize("CLEAR")];
5995 if ([package_ source] == nil);
5996 else if ([package_ upgradableAndEssential:NO])
5997 [buttons_ addObject:UCLocalize("UPGRADE")];
5998 else if ([package_ uninstalled])
5999 [buttons_ addObject:UCLocalize("INSTALL")];
6001 [buttons_ addObject:UCLocalize("REINSTALL")];
6002 if (![package_ uninstalled])
6003 [buttons_ addObject:UCLocalize("REMOVE")];
6010 switch ([buttons_ count]) {
6011 case 0: title = nil; break;
6012 case 1: title = [buttons_ objectAtIndex:0]; break;
6013 default: title = UCLocalize("MODIFY"); break;
6016 button_ = [[UIBarButtonItem alloc]
6018 style:UIBarButtonItemStylePlain
6020 action:@selector(customButtonClicked)
6026 - (bool) isLoading {
6027 return commercial_ ? [super isLoading] : false;
6033 /* Package List Controller {{{ */
6034 @interface PackageListController : CYViewController <
6035 UITableViewDataSource,
6038 _transient Database *database_;
6040 NSMutableArray *packages_;
6041 NSMutableArray *sections_;
6043 NSMutableArray *index_;
6044 NSMutableDictionary *indices_;
6048 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6049 - (void) setDelegate:(id)delegate;
6050 - (void) resetCursor;
6054 @implementation PackageListController
6057 [packages_ release];
6058 [sections_ release];
6067 - (void) deselectWithAnimation:(BOOL)animated {
6068 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6071 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6072 CGRect base = [[self view] bounds];
6073 base.size.height -= bounds.size.height;
6074 base.origin = [list_ frame].origin;
6076 [UIView beginAnimations:nil context:NULL];
6077 [UIView setAnimationBeginsFromCurrentState:YES];
6078 [UIView setAnimationCurve:curve];
6079 [UIView setAnimationDuration:duration];
6080 [list_ setFrame:base];
6081 [UIView commitAnimations];
6084 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6085 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6088 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6089 [self resizeForKeyboardBounds:bounds duration:0];
6092 - (void) keyboardWillShow:(NSNotification *)notification {
6095 NSTimeInterval duration;
6096 UIViewAnimationCurve curve;
6097 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6098 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6099 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6100 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6102 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);
6103 UIViewController *base = self;
6104 while ([base parentViewController] != nil)
6105 base = [base parentViewController];
6106 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6107 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6109 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6112 - (void) keyboardWillHide:(NSNotification *)notification {
6113 NSTimeInterval duration;
6114 UIViewAnimationCurve curve;
6115 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6116 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6118 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6121 - (void) viewWillAppear:(BOOL)animated {
6122 [super viewWillAppear:animated];
6124 [self resizeForKeyboardBounds:CGRectZero];
6125 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6126 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6129 - (void) viewWillDisappear:(BOOL)animated {
6130 [super viewWillDisappear:animated];
6132 [self resizeForKeyboardBounds:CGRectZero];
6133 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6134 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6137 - (void) viewDidAppear:(BOOL)animated {
6138 [super viewDidAppear:animated];
6139 [self deselectWithAnimation:animated];
6142 - (void) didSelectPackage:(Package *)package {
6143 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6144 [view setDelegate:delegate_];
6145 [[self navigationController] pushViewController:view animated:YES];
6148 #if TryIndexedCollation
6149 + (BOOL) hasIndexedCollation {
6150 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6154 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6155 NSInteger count([sections_ count]);
6156 return count == 0 ? 1 : count;
6159 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6160 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6162 return [[sections_ objectAtIndex:section] name];
6165 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6166 if ([sections_ count] == 0)
6168 return [[sections_ objectAtIndex:section] count];
6171 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6172 @synchronized (database_) {
6173 if ([database_ era] != era_)
6176 Section *section([sections_ objectAtIndex:[path section]]);
6177 NSInteger row([path row]);
6178 Package *package([packages_ objectAtIndex:([section row] + row)]);
6179 return [[package retain] autorelease];
6182 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6183 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6185 cell = [[[PackageCell alloc] init] autorelease];
6186 [cell setPackage:[self packageAtIndexPath:path]];
6190 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6191 Package *package([self packageAtIndexPath:path]);
6192 package = [database_ packageWithName:[package id]];
6193 [self didSelectPackage:package];
6196 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6197 // XXX: is 20 the most optimal number here?
6198 return [packages_ count] > 20 ? index_ : nil;
6201 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6202 #if TryIndexedCollation
6203 if ([[self class] hasIndexedCollation]) {
6204 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6211 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6212 if ((self = [super init]) != nil) {
6213 database_ = database;
6214 title_ = [title copy];
6215 [[self navigationItem] setTitle:title_];
6217 #if TryIndexedCollation
6218 if ([[self class] hasIndexedCollation])
6219 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6222 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6224 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6226 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6227 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6229 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6230 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6231 [list_ setRowHeight:73];
6232 [[self view] addSubview:list_];
6234 [list_ setDataSource:self];
6235 [list_ setDelegate:self];
6239 - (void) setDelegate:(id)delegate {
6240 delegate_ = delegate;
6243 - (bool) hasPackage:(Package *)package {
6247 - (void) reloadData {
6250 era_ = [database_ era];
6251 NSArray *packages = [database_ packages];
6253 [packages_ removeAllObjects];
6254 [sections_ removeAllObjects];
6256 _profile(PackageTable$reloadData$Filter)
6257 for (Package *package in packages)
6258 if ([self hasPackage:package])
6259 [packages_ addObject:package];
6262 [indices_ removeAllObjects];
6264 Section *section = nil;
6266 #if TryIndexedCollation
6267 if ([[self class] hasIndexedCollation]) {
6268 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6269 NSArray *titles = [collation sectionIndexTitles];
6272 _profile(PackageTable$reloadData$Section)
6273 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6277 _profile(PackageTable$reloadData$Section$Package)
6278 package = [packages_ objectAtIndex:offset];
6279 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6282 while (secidx < index) {
6285 _profile(PackageTable$reloadData$Section$Allocate)
6286 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6289 _profile(PackageTable$reloadData$Section$Add)
6290 [sections_ addObject:section];
6294 [section addToCount];
6300 [index_ removeAllObjects];
6302 _profile(PackageTable$reloadData$Section)
6303 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6307 _profile(PackageTable$reloadData$Section$Package)
6308 package = [packages_ objectAtIndex:offset];
6309 index = [package index];
6312 if (section == nil || [section index] != index) {
6313 _profile(PackageTable$reloadData$Section$Allocate)
6314 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6317 [index_ addObject:[section name]];
6318 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6320 _profile(PackageTable$reloadData$Section$Add)
6321 [sections_ addObject:section];
6325 [section addToCount];
6330 _profile(PackageTable$reloadData$List)
6335 - (void) resetCursor {
6336 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6341 /* Filtered Package List Controller {{{ */
6342 @interface FilteredPackageListController : PackageListController {
6348 - (void) setObject:(id)object;
6349 - (void) setObject:(id)object forFilter:(SEL)filter;
6351 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6355 @implementation FilteredPackageListController
6363 - (void) setFilter:(SEL)filter {
6366 /* XXX: this is an unsafe optimization of doomy hell */
6367 Method method(class_getInstanceMethod([Package class], filter));
6368 _assert(method != NULL);
6369 imp_ = method_getImplementation(method);
6370 _assert(imp_ != NULL);
6373 - (void) setObject:(id)object {
6379 object_ = [object retain];
6382 - (void) setObject:(id)object forFilter:(SEL)filter {
6383 [self setFilter:filter];
6384 [self setObject:object];
6387 - (bool) hasPackage:(Package *)package {
6388 _profile(FilteredPackageTable$hasPackage)
6389 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6393 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6394 if ((self = [super initWithDatabase:database title:title]) != nil) {
6395 [self setFilter:filter];
6396 [self setObject:object];
6403 /* Home Controller {{{ */
6404 @interface HomeController : CYBrowserController {
6409 @implementation HomeController
6411 + (BOOL) shouldHideNavigationBar {
6415 - (NSURL *) navigationURL {
6416 return [NSURL URLWithString:@"cydia://home"];
6419 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6420 [super _setMoreHeaders:request];
6423 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6424 if (UniqueID_ != nil)
6425 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6427 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6430 - (void) aboutButtonClicked {
6431 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6433 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6434 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6435 [alert setCancelButtonIndex:0];
6438 @"Copyright (C) 2008-2011\n"
6439 "Jay Freeman (saurik)\n"
6440 "saurik@saurik.com\n"
6441 "http://www.saurik.com/"
6447 - (void) viewWillDisappear:(BOOL)animated {
6448 [super viewWillDisappear:animated];
6450 if ([[self class] shouldHideNavigationBar])
6451 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6454 - (void) viewWillAppear:(BOOL)animated {
6455 if (![self hasLoaded])
6456 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6458 [super viewWillAppear:animated];
6460 if ([[self class] shouldHideNavigationBar])
6461 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6464 - (void) viewDidLoad {
6465 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6466 initWithTitle:UCLocalize("ABOUT")
6467 style:UIBarButtonItemStylePlain
6469 action:@selector(aboutButtonClicked)
6475 /* Manage Controller {{{ */
6476 @interface ManageController : CYBrowserController {
6479 - (void) queueStatusDidChange;
6483 @implementation ManageController
6485 - (NSURL *) navigationURL {
6486 return [NSURL URLWithString:@"cydia://manage"];
6489 - (void) viewWillAppear:(BOOL)animated {
6490 if (![self hasLoaded])
6491 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6493 [super viewWillAppear:animated];
6496 - (void) viewDidLoad {
6497 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6498 initWithTitle:UCLocalize("SETTINGS")
6499 style:UIBarButtonItemStylePlain
6501 action:@selector(settingsButtonClicked)
6504 [self queueStatusDidChange];
6507 - (void) settingsButtonClicked {
6508 [delegate_ showSettings];
6512 - (void) queueButtonClicked {
6516 - (void) applyLoadingTitle {
6517 // Disable "Loading" title.
6520 - (void) applyRightButton {
6521 // Disable right button.
6525 - (void) queueStatusDidChange {
6527 if (!IsWildcat_ && Queuing_) {
6528 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6529 initWithTitle:UCLocalize("QUEUE")
6530 style:UIBarButtonItemStyleDone
6532 action:@selector(queueButtonClicked)
6535 [[self navigationItem] setRightBarButtonItem:nil];
6540 - (bool) isLoading {
6541 // Never show as loading.
6548 /* Refresh Bar {{{ */
6549 @interface RefreshBar : UINavigationBar {
6550 UIProgressIndicator *indicator_;
6551 UITextLabel *prompt_;
6552 UIProgressBar *progress_;
6553 UINavigationButton *cancel_;
6558 @implementation RefreshBar
6561 [indicator_ release];
6563 [progress_ release];
6568 - (void) positionViews {
6569 CGRect frame = [cancel_ frame];
6570 frame.size = [cancel_ sizeThatFits:frame.size];
6571 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6572 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6573 [cancel_ setFrame:frame];
6575 CGSize prgsize = {75, 100};
6577 [self frame].size.width - prgsize.width - 10,
6578 ([self frame].size.height - prgsize.height) / 2
6580 [progress_ setFrame:prgrect];
6582 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6583 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6584 CGRect indrect = {{indoffset, indoffset}, indsize};
6585 [indicator_ setFrame:indrect];
6587 CGSize prmsize = {215, indsize.height + 4};
6589 indoffset * 2 + indsize.width,
6590 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6592 [prompt_ setFrame:prmrect];
6595 - (void) setFrame:(CGRect)frame {
6596 [super setFrame:frame];
6597 [self positionViews];
6600 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6601 if ((self = [super initWithFrame:frame]) != nil) {
6602 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6604 [self setBarStyle:UIBarStyleBlack];
6606 UIBarStyle barstyle([self _barStyle:NO]);
6607 bool ugly(barstyle == UIBarStyleDefault);
6609 UIProgressIndicatorStyle style = ugly ?
6610 UIProgressIndicatorStyleMediumBrown :
6611 UIProgressIndicatorStyleMediumWhite;
6613 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6614 [indicator_ setStyle:style];
6615 [indicator_ startAnimation];
6616 [self addSubview:indicator_];
6618 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6619 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6620 [prompt_ setBackgroundColor:[UIColor clearColor]];
6621 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6622 [self addSubview:prompt_];
6624 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6625 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6626 [progress_ setStyle:0];
6627 [self addSubview:progress_];
6629 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6630 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6631 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6632 [cancel_ setBarStyle:barstyle];
6634 [self positionViews];
6638 - (void) setCancellable:(bool)cancellable {
6640 [self addSubview:cancel_];
6642 [cancel_ removeFromSuperview];
6646 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6647 [progress_ setProgress:0];
6651 [self setCancellable:NO];
6654 - (void) setPrompt:(NSString *)prompt {
6655 [prompt_ setText:prompt];
6658 - (void) setProgress:(float)progress {
6659 [progress_ setProgress:progress];
6665 @class CYNavigationController;
6667 /* Cydia Tab Bar Controller {{{ */
6668 @interface CYTabBarController : UITabBarController <
6669 UITabBarControllerDelegate,
6672 _transient Database *database_;
6673 RefreshBar *refreshbar_;
6677 // XXX: ok, "updatedelegate_"?...
6678 _transient NSObject<CydiaDelegate> *updatedelegate_;
6681 UIViewController *remembered_;
6682 _transient UIViewController *transient_;
6685 - (NSArray *) navigationURLCollection;
6686 - (void) dropBar:(BOOL)animated;
6687 - (void) beginUpdate;
6688 - (void) raiseBar:(BOOL)animated;
6693 @implementation CYTabBarController
6695 - (void) setUnselectedViewController:(UIViewController *)transient {
6696 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6697 if (transient != nil) {
6698 if (transient_ == nil)
6699 remembered_ = [[controllers objectAtIndex:0] retain];
6700 transient_ = transient;
6701 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6702 [controllers replaceObjectAtIndex:0 withObject:transient_];
6703 [self setSelectedIndex:0];
6704 [self setViewControllers:controllers];
6705 [self concealTabBarSelection];
6706 } else if (remembered_ != nil) {
6707 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6708 transient_ = transient;
6709 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6710 [remembered_ release];
6712 [self setViewControllers:controllers];
6713 [self revealTabBarSelection];
6717 - (UIViewController *) unselectedViewController {
6721 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6722 if ([self unselectedViewController])
6723 [self setUnselectedViewController:nil];
6726 - (NSArray *) navigationURLCollection {
6727 NSMutableArray *items([NSMutableArray array]);
6729 // XXX: Should this deal with transient view controllers?
6730 for (id navigation in [self viewControllers]) {
6731 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6733 [items addObject:stack];
6739 - (void) reloadData {
6740 for (CYViewController *controller in [self viewControllers])
6741 [controller reloadData];
6743 [(CYNavigationController *)[self unselectedViewController] reloadData];
6747 [refreshbar_ release];
6748 [[NSNotificationCenter defaultCenter] removeObserver:self];
6753 - (id) initWithDatabase:(Database *)database {
6754 if ((self = [super init]) != nil) {
6755 database_ = database;
6756 [self setDelegate:self];
6758 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6759 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6761 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6765 - (void) setUpdate:(NSDate *)date {
6769 - (void) beginUpdate {
6770 [refreshbar_ start];
6773 [updatedelegate_ retainNetworkActivityIndicator];
6777 detachNewThreadSelector:@selector(performUpdate)
6783 - (void) performUpdate { _pooled
6785 status.setDelegate(self);
6786 [database_ updateWithStatus:status];
6789 performSelectorOnMainThread:@selector(completeUpdate)
6795 - (void) stopUpdateWithSelector:(SEL)selector {
6797 [updatedelegate_ releaseNetworkActivityIndicator];
6799 [self raiseBar:YES];
6802 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6805 - (void) completeUpdate {
6808 [self stopUpdateWithSelector:@selector(reloadData)];
6811 - (void) cancelUpdate {
6812 [self stopUpdateWithSelector:@selector(updateData)];
6815 - (void) cancelPressed {
6816 [self cancelUpdate];
6823 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6824 [refreshbar_ setPrompt:[event compoundMessage]];
6827 - (bool) isProgressCancelled {
6831 - (void) setProgressCancellable:(NSNumber *)cancellable {
6832 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6835 - (void) setProgressPercent:(NSNumber *)percent {
6836 [refreshbar_ setProgress:[percent floatValue]];
6839 - (void) setProgressStatus:(NSDictionary *)status {
6841 [self setProgressPercent:[status objectForKey:@"Percent"]];
6844 - (void) setUpdateDelegate:(id)delegate {
6845 updatedelegate_ = delegate;
6848 - (CGFloat) statusBarHeight {
6849 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6850 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6852 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6856 - (UIView *) transitionView {
6857 if ([self respondsToSelector:@selector(_transitionView)])
6858 return [self _transitionView];
6860 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6863 - (void) dropBar:(BOOL)animated {
6868 UIView *transition([self transitionView]);
6869 [[self view] addSubview:refreshbar_];
6871 CGRect barframe([refreshbar_ frame]);
6873 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6874 barframe.origin.y = [self statusBarHeight];
6876 barframe.origin.y = 0;
6878 [refreshbar_ setFrame:barframe];
6881 [UIView beginAnimations:nil context:NULL];
6883 CGRect viewframe = [transition frame];
6884 viewframe.origin.y += barframe.size.height;
6885 viewframe.size.height -= barframe.size.height;
6886 [transition setFrame:viewframe];
6889 [UIView commitAnimations];
6891 // Ensure bar has the proper width for our view, it might have changed
6892 barframe.size.width = viewframe.size.width;
6893 [refreshbar_ setFrame:barframe];
6895 // XXX: fix Apple's layout bug
6896 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6899 - (void) raiseBar:(BOOL)animated {
6904 UIView *transition([self transitionView]);
6905 [refreshbar_ removeFromSuperview];
6907 CGRect barframe([refreshbar_ frame]);
6910 [UIView beginAnimations:nil context:NULL];
6912 CGRect viewframe = [transition frame];
6913 viewframe.origin.y -= barframe.size.height;
6914 viewframe.size.height += barframe.size.height;
6915 [transition setFrame:viewframe];
6918 [UIView commitAnimations];
6920 // XXX: fix Apple's layout bug
6921 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6925 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6926 // XXX: fix Apple's layout bug
6927 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6931 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6932 bool dropped(dropped_);
6937 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6942 // XXX: fix Apple's layout bug
6943 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6946 - (void) statusBarFrameChanged:(NSNotification *)notification {
6955 /* Cydia Navigation Controller {{{ */
6956 @interface CYNavigationController : UINavigationController {
6957 _transient Database *database_;
6958 _transient id<UINavigationControllerDelegate> delegate_;
6961 - (NSArray *) navigationURLCollection;
6962 - (id) initWithDatabase:(Database *)database;
6963 - (void) reloadData;
6968 @implementation CYNavigationController
6970 - (NSArray *) navigationURLCollection {
6971 NSMutableArray *stack([NSMutableArray array]);
6973 for (CYViewController *controller in [self viewControllers]) {
6974 NSString *url = [[controller navigationURL] absoluteString];
6976 [stack addObject:url];
6982 - (void) reloadData {
6983 for (CYViewController *page in [self viewControllers]) {
6984 // Only reload controllers that have already loaded.
6985 // This prevents a page from accidentally loading too
6986 // early if it hasn't been shown on the screen yet.
6987 if ([page hasLoaded])
6992 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6993 delegate_ = delegate;
6996 - (id) initWithDatabase:(Database *)database {
6997 if ((self = [super init]) != nil) {
6998 database_ = database;
7005 /* Cydia:// Protocol {{{ */
7006 @interface CydiaURLProtocol : NSURLProtocol {
7011 @implementation CydiaURLProtocol
7013 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7014 NSURL *url([request URL]);
7018 NSString *scheme([[url scheme] lowercaseString]);
7019 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7021 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7027 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7031 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7032 id<NSURLProtocolClient> client([self client]);
7034 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7036 NSData *data(UIImagePNGRepresentation(icon));
7038 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7039 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7040 [client URLProtocol:self didLoadData:data];
7041 [client URLProtocolDidFinishLoading:self];
7045 - (void) startLoading {
7046 id<NSURLProtocolClient> client([self client]);
7047 NSURLRequest *request([self request]);
7049 NSURL *url([request URL]);
7050 NSString *href([url absoluteString]);
7051 NSString *scheme([[url scheme] lowercaseString]);
7055 if ([scheme isEqualToString:@"cydia"])
7056 path = [href substringFromIndex:8];
7057 else if ([scheme isEqualToString:@"about"])
7058 path = [href substringFromIndex:12];
7059 else _assert(false);
7061 NSRange slash([path rangeOfString:@"/"]);
7064 if (slash.location == NSNotFound) {
7068 command = [path substringToIndex:slash.location];
7069 path = [path substringFromIndex:(slash.location + 1)];
7072 Database *database([Database sharedInstance]);
7074 if ([command isEqualToString:@"package-icon"]) {
7077 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7078 Package *package([database packageWithName:path]);
7081 UIImage *icon([package icon]);
7082 [self _returnPNGWithImage:icon forRequest:request];
7083 } else if ([command isEqualToString:@"source-icon"]) {
7086 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7087 NSString *source(Simplify(path));
7088 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7090 icon = [UIImage applicationImageNamed:@"unknown.png"];
7091 [self _returnPNGWithImage:icon forRequest:request];
7092 } else if ([command isEqualToString:@"uikit-image"]) {
7095 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7096 UIImage *icon(_UIImageWithName(path));
7097 [self _returnPNGWithImage:icon forRequest:request];
7098 } else if ([command isEqualToString:@"section-icon"]) {
7101 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7102 NSString *section(Simplify(path));
7103 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7105 icon = [UIImage applicationImageNamed:@"unknown.png"];
7106 [self _returnPNGWithImage:icon forRequest:request];
7108 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7112 - (void) stopLoading {
7118 /* Section Controller {{{ */
7119 @interface SectionController : FilteredPackageListController {
7123 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7127 @implementation SectionController
7129 - (NSURL *) navigationURL {
7130 NSString *name = section_;
7134 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7137 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7140 title = UCLocalize("ALL_PACKAGES");
7141 else if (![name isEqual:@""])
7142 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7144 title = UCLocalize("NO_SECTION");
7146 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7153 /* Sections Controller {{{ */
7154 @interface SectionsController : CYViewController <
7155 UITableViewDataSource,
7158 _transient Database *database_;
7159 NSMutableArray *sections_;
7160 NSMutableArray *filtered_;
7165 - (id) initWithDatabase:(Database *)database;
7166 - (void) editButtonClicked;
7170 @implementation SectionsController
7173 [self releaseSubviews];
7174 [sections_ release];
7175 [filtered_ release];
7180 - (NSURL *) navigationURL {
7181 return [NSURL URLWithString:@"cydia://sections"];
7184 - (void) updateNavigationItem {
7185 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7186 if ([sections_ count] == 0) {
7187 [[self navigationItem] setRightBarButtonItem:nil];
7189 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7190 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7192 action:@selector(editButtonClicked)
7193 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7197 - (BOOL) isEditing {
7201 - (void) setEditing:(BOOL)editing {
7202 if ((editing_ = editing))
7205 [delegate_ updateData];
7207 [self updateNavigationItem];
7210 - (void) viewDidAppear:(BOOL)animated {
7211 [super viewDidAppear:animated];
7212 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7215 - (void) viewWillDisappear:(BOOL)animated {
7216 [super viewWillDisappear:animated];
7217 if (editing_) [self setEditing:NO];
7220 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7221 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7225 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7226 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7229 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7233 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7234 static NSString *reuseIdentifier = @"SectionCell";
7236 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7238 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7240 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7245 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7249 Section *section = [self sectionAtIndexPath:indexPath];
7251 SectionController *controller = [[[SectionController alloc]
7252 initWithDatabase:database_
7253 section:[section name]
7255 [controller setDelegate:delegate_];
7257 [[self navigationController] pushViewController:controller animated:YES];
7261 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7263 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7264 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7265 [list_ setRowHeight:45.0f];
7266 [list_ setDataSource:self];
7267 [list_ setDelegate:self];
7268 [[self view] addSubview:list_];
7271 - (void) viewDidLoad {
7272 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7275 - (void) releaseSubviews {
7280 - (id) initWithDatabase:(Database *)database {
7281 if ((self = [super init]) != nil) {
7282 database_ = database;
7284 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7285 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7289 - (void) reloadData {
7292 NSArray *packages = [database_ packages];
7294 [sections_ removeAllObjects];
7295 [filtered_ removeAllObjects];
7297 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7300 for (Package *package in packages) {
7301 NSString *name([package section]);
7302 NSString *key(name == nil ? @"" : name);
7306 _profile(SectionsView$reloadData$Section)
7307 section = [sections objectForKey:key];
7308 if (section == nil) {
7309 _profile(SectionsView$reloadData$Section$Allocate)
7310 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7311 [sections setObject:section forKey:key];
7316 [section addToCount];
7318 _profile(SectionsView$reloadData$Filter)
7319 if (![package valid] || ![package visible])
7327 [sections_ addObjectsFromArray:[sections allValues]];
7329 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7331 for (Section *section in sections_) {
7332 size_t count([section row]);
7336 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7337 [section setCount:count];
7338 [filtered_ addObject:section];
7341 [self updateNavigationItem];
7346 - (void) editButtonClicked {
7347 [self setEditing:(!editing_)];
7353 /* Changes Controller {{{ */
7354 @interface ChangesController : CYViewController <
7355 UITableViewDataSource,
7358 _transient Database *database_;
7360 CFMutableArrayRef packages_;
7361 NSMutableArray *sections_;
7364 BOOL hasSentFirstLoad_;
7367 - (id) initWithDatabase:(Database *)database;
7371 @implementation ChangesController
7374 [self releaseSubviews];
7375 CFRelease(packages_);
7376 [sections_ release];
7381 - (NSURL *) navigationURL {
7382 return [NSURL URLWithString:@"cydia://changes"];
7385 - (void) viewWillAppear:(BOOL)animated {
7386 // Loads after it appears, so don't load beforehand.
7388 [super viewWillAppear:animated];
7391 - (void) viewDidAppear:(BOOL)animated {
7392 [super viewDidAppear:animated];
7394 if (!hasSentFirstLoad_) {
7395 hasSentFirstLoad_ = YES;
7396 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7398 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7402 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7403 NSInteger count([sections_ count]);
7404 return count == 0 ? 1 : count;
7407 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7408 if ([sections_ count] == 0)
7410 return [[sections_ objectAtIndex:section] name];
7413 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7414 if ([sections_ count] == 0)
7416 return [[sections_ objectAtIndex:section] count];
7419 - (Package *) packageAtIndex:(NSUInteger)index {
7420 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7423 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7424 @synchronized (database_) {
7425 if ([database_ era] != era_)
7428 NSUInteger sectionIndex([path section]);
7429 if (sectionIndex >= [sections_ count])
7431 Section *section([sections_ objectAtIndex:sectionIndex]);
7432 NSInteger row([path row]);
7433 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7436 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7437 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7439 cell = [[[PackageCell alloc] init] autorelease];
7440 [cell setPackage:[self packageAtIndexPath:path]];
7444 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7445 Package *package([self packageAtIndexPath:path]);
7446 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7447 [view setDelegate:delegate_];
7448 [[self navigationController] pushViewController:view animated:YES];
7452 - (void) refreshButtonClicked {
7453 [delegate_ beginUpdate];
7454 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7457 - (void) upgradeButtonClicked {
7458 [delegate_ distUpgrade];
7462 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7464 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7465 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7466 [list_ setRowHeight:73];
7467 [list_ setDataSource:self];
7468 [list_ setDelegate:self];
7469 [[self view] addSubview:list_];
7472 - (void) viewDidLoad {
7473 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7476 - (void) releaseSubviews {
7481 - (id) initWithDatabase:(Database *)database {
7482 if ((self = [super init]) != nil) {
7483 database_ = database;
7485 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7486 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7490 // this mostly works because reloadData (below) is @synchronized (database_)
7491 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7492 - (void) _reloadPackages:(NSArray *)packages {
7493 CFRelease(packages_);
7494 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7497 _profile(ChangesController$_reloadPackages$Filter)
7498 for (Package *package in packages)
7499 if ([package upgradableAndEssential:YES] || [package visible])
7500 CFArrayAppendValue(packages_, package);
7503 _profile(ChangesController$_reloadPackages$radixSort)
7504 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7509 - (void) reloadData {
7510 @synchronized (database_) {
7511 era_ = [database_ era];
7512 NSArray *packages = [database_ packages];
7514 [sections_ removeAllObjects];
7517 UIProgressHUD *hud([delegate_ addProgressHUD]);
7518 [hud setText:UCLocalize("LOADING")];
7519 //NSLog(@"HUD:%@::%@", delegate_, hud);
7520 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7521 [delegate_ removeProgressHUD:hud];
7523 [self _reloadPackages:packages];
7526 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7527 Section *ignored = nil;
7528 Section *section = nil;
7532 bool unseens = false;
7534 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7536 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7537 Package *package = [self packageAtIndex:offset];
7539 BOOL uae = [package upgradableAndEssential:YES];
7543 time_t seen([package seen]);
7545 if (section == nil || last != seen) {
7549 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7552 _profile(ChangesController$reloadData$Allocate)
7553 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7554 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7555 [sections_ addObject:section];
7559 [section addToCount];
7560 } else if ([package ignored]) {
7561 if (ignored == nil) {
7562 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7564 [ignored addToCount];
7567 [upgradable addToCount];
7572 CFRelease(formatter);
7575 Section *last = [sections_ lastObject];
7576 size_t count = [last count];
7577 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7578 [sections_ removeLastObject];
7581 if ([ignored count] != 0)
7582 [sections_ insertObject:ignored atIndex:0];
7584 [sections_ insertObject:upgradable atIndex:0];
7589 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7590 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7591 style:UIBarButtonItemStylePlain
7593 action:@selector(upgradeButtonClicked)
7596 if (![delegate_ updating])
7597 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7598 initWithTitle:UCLocalize("REFRESH")
7599 style:UIBarButtonItemStylePlain
7601 action:@selector(refreshButtonClicked)
7609 /* Search Controller {{{ */
7610 @interface SearchController : FilteredPackageListController <
7613 UISearchBar *search_;
7617 - (id) initWithDatabase:(Database *)database;
7618 - (void) setSearchTerm:(NSString *)term;
7619 - (void) reloadData;
7623 @implementation SearchController
7630 - (NSURL *) navigationURL {
7631 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7632 return [NSURL URLWithString:@"cydia://search"];
7634 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7637 - (void) setSearchTerm:(NSString *)searchTerm {
7638 [search_ setText:searchTerm];
7642 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7643 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7644 [search_ resignFirstResponder];
7648 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7649 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7653 - (id) initWithDatabase:(Database *)database {
7654 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7655 search_ = [[UISearchBar alloc] init];
7659 - (void) viewDidAppear:(BOOL)animated {
7660 [super viewDidAppear:animated];
7662 if (!searchloaded_) {
7663 searchloaded_ = YES;
7664 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7665 [search_ layoutSubviews];
7666 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7668 UITextField *textField;
7669 if ([search_ respondsToSelector:@selector(searchField)])
7670 textField = [search_ searchField];
7672 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7674 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7675 [search_ setDelegate:self];
7676 [textField setEnablesReturnKeyAutomatically:NO];
7677 [[self navigationItem] setTitleView:textField];
7681 - (void) reloadData {
7682 [self setObject:[search_ text]];
7687 - (void) didSelectPackage:(Package *)package {
7688 [search_ resignFirstResponder];
7689 [super didSelectPackage:package];
7694 /* Package Settings Controller {{{ */
7695 @interface PackageSettingsController : CYViewController <
7696 UITableViewDataSource,
7699 _transient Database *database_;
7702 UITableView *table_;
7703 UISwitch *subscribedSwitch_;
7704 UISwitch *ignoredSwitch_;
7705 UITableViewCell *subscribedCell_;
7706 UITableViewCell *ignoredCell_;
7709 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7713 @implementation PackageSettingsController
7716 [self releaseSubviews];
7723 - (NSURL *) navigationURL {
7724 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7727 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7728 if (package_ == nil)
7731 if ([package_ installed] == nil)
7737 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7738 if (package_ == nil)
7741 // both sections contain just one item right now.
7745 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7749 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7751 return UCLocalize("SHOW_ALL_CHANGES_EX");
7753 return UCLocalize("IGNORE_UPGRADES_EX");
7756 - (void) onSubscribed:(id)control {
7757 bool value([control isOn]);
7758 if (package_ == nil)
7760 if ([package_ setSubscribed:value])
7761 [delegate_ updateData];
7764 - (void) _updateIgnored {
7765 const char *package([name_ UTF8String]);
7766 bool on([ignoredSwitch_ isOn]);
7768 pid_t pid(ExecFork());
7770 FILE *dpkg(popen("dpkg --set-selections", "w"));
7771 fwrite(package, strlen(package), 1, dpkg);
7774 fwrite(" hold\n", 6, 1, dpkg);
7776 fwrite(" install\n", 9, 1, dpkg);
7786 int result(waitpid(pid, &status, 0));
7789 _assert(result == pid);
7795 - (void) onIgnored:(id)control {
7796 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7797 [invocation setTarget:self];
7798 [invocation setSelector:@selector(_updateIgnored)];
7800 [delegate_ reloadDataWithInvocation:invocation];
7803 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7804 if (package_ == nil)
7807 switch ([indexPath section]) {
7808 case 0: return subscribedCell_;
7809 case 1: return ignoredCell_;
7818 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7820 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7821 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7822 [table_ setDataSource:self];
7823 [table_ setDelegate:self];
7824 [[self view] addSubview:table_];
7826 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7827 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7828 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7830 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7831 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7832 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7834 subscribedCell_ = [[UITableViewCell alloc] init];
7835 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7836 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7837 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7839 ignoredCell_ = [[UITableViewCell alloc] init];
7840 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7841 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7842 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7845 - (void) viewDidLoad {
7846 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7849 - (void) releaseSubviews {
7850 [ignoredCell_ release];
7853 [subscribedCell_ release];
7854 subscribedCell_ = nil;
7859 [ignoredSwitch_ release];
7860 ignoredSwitch_ = nil;
7862 [subscribedSwitch_ release];
7863 subscribedSwitch_ = nil;
7866 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7867 if ((self = [super init]) != nil) {
7868 database_ = database;
7869 name_ = [package retain];
7873 - (void) reloadData {
7876 if (package_ != nil)
7877 [package_ autorelease];
7878 package_ = [database_ packageWithName:name_];
7880 if (package_ != nil) {
7881 package_ = [package_ retain];
7882 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7883 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7884 } // XXX: what now, G?
7886 [table_ reloadData];
7892 /* Installed Controller {{{ */
7893 @interface InstalledController : FilteredPackageListController {
7897 - (id) initWithDatabase:(Database *)database;
7899 - (void) updateRoleButton;
7900 - (void) queueStatusDidChange;
7904 @implementation InstalledController
7910 - (NSURL *) navigationURL {
7911 return [NSURL URLWithString:@"cydia://installed"];
7914 - (id) initWithDatabase:(Database *)database {
7915 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7916 [self updateRoleButton];
7917 [self queueStatusDidChange];
7922 - (void) queueButtonClicked {
7927 - (void) queueStatusDidChange {
7931 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7932 initWithTitle:UCLocalize("QUEUE")
7933 style:UIBarButtonItemStyleDone
7935 action:@selector(queueButtonClicked)
7938 [[self navigationItem] setLeftBarButtonItem:nil];
7944 - (void) updateRoleButton {
7945 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7946 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7947 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7948 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7950 action:@selector(roleButtonClicked)
7954 - (void) roleButtonClicked {
7955 [self setObject:[NSNumber numberWithBool:expert_]];
7959 [self updateRoleButton];
7965 /* Source Cell {{{ */
7966 @interface SourceCell : CYTableViewCell <
7974 - (void) setSource:(Source *)source;
7978 @implementation SourceCell
7980 - (void) clearSource {
7990 - (void) setSource:(Source *)source {
7994 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7996 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7997 icon_ = [icon_ retain];
7999 origin_ = [[source name] retain];
8000 label_ = [[source uri] retain];
8002 [content_ setNeedsDisplay];
8010 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8011 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8012 UIView *content([self contentView]);
8013 CGRect bounds([content bounds]);
8015 content_ = [[ContentView alloc] initWithFrame:bounds];
8016 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8017 [content_ setBackgroundColor:[UIColor whiteColor]];
8018 [content addSubview:content_];
8020 [content_ setDelegate:self];
8021 [content_ setOpaque:YES];
8025 - (NSString *) accessibilityLabel {
8029 - (void) drawContentRect:(CGRect)rect {
8030 bool highlighted(highlighted_);
8031 float width(rect.size.width);
8034 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8041 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8045 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8050 /* Source Controller {{{ */
8051 @interface SourceController : FilteredPackageListController {
8052 _transient Source *source_;
8056 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8060 @implementation SourceController
8062 - (NSURL *) navigationURL {
8063 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8066 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8067 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8069 key_ = [[source key] retain];
8073 - (void) reloadData {
8074 source_ = [database_ sourceWithKey:key_];
8076 key_ = [[source_ key] retain];
8077 [self setObject:source_];
8078 [[self navigationItem] setTitle:[source_ label]];
8085 /* Sources Controller {{{ */
8086 @interface SourcesController : CYViewController <
8087 UITableViewDataSource,
8090 _transient Database *database_;
8092 NSMutableArray *sources_;
8096 UIProgressHUD *hud_;
8099 //NSURLConnection *installer_;
8100 NSURLConnection *trivial_;
8101 NSURLConnection *trivial_bz2_;
8102 NSURLConnection *trivial_gz_;
8103 //NSURLConnection *automatic_;
8108 - (id) initWithDatabase:(Database *)database;
8109 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8113 @implementation SourcesController
8115 - (void) _releaseConnection:(NSURLConnection *)connection {
8116 if (connection != nil) {
8117 [connection cancel];
8118 //[connection setDelegate:nil];
8119 [connection release];
8124 [self releaseSubviews];
8130 //[self _releaseConnection:installer_];
8131 [self _releaseConnection:trivial_];
8132 [self _releaseConnection:trivial_gz_];
8133 [self _releaseConnection:trivial_bz2_];
8134 //[self _releaseConnection:automatic_];
8140 - (NSURL *) navigationURL {
8141 return [NSURL URLWithString:@"cydia://sources"];
8144 - (void) viewDidAppear:(BOOL)animated {
8145 [super viewDidAppear:animated];
8146 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8149 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8150 return offset_ == 0 ? 1 : 2;
8153 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8154 switch (section + (offset_ == 0 ? 1 : 0)) {
8155 case 0: return UCLocalize("ENTERED_BY_USER");
8156 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8162 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8163 int count = [sources_ count];
8165 case 0: return (offset_ == 0 ? count : offset_);
8166 case 1: return count - offset_;
8172 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8174 switch (indexPath.section) {
8175 case 0: idx = indexPath.row; break;
8176 case 1: idx = indexPath.row + offset_; break;
8180 return [sources_ objectAtIndex:idx];
8183 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8184 static NSString *cellIdentifier = @"SourceCell";
8186 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8187 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8188 [cell setSource:[self sourceAtIndexPath:indexPath]];
8189 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8194 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8195 Source *source = [self sourceAtIndexPath:indexPath];
8197 SourceController *controller = [[[SourceController alloc]
8198 initWithDatabase:database_
8202 [controller setDelegate:delegate_];
8204 [[self navigationController] pushViewController:controller animated:YES];
8207 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8208 Source *source = [self sourceAtIndexPath:indexPath];
8209 return [source record] != nil;
8212 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8213 Source *source = [self sourceAtIndexPath:indexPath];
8214 [Sources_ removeObjectForKey:[source key]];
8215 [delegate_ syncData];
8219 [delegate_ addTrivialSource:href_];
8220 [delegate_ syncData];
8223 - (NSString *) getWarning {
8224 NSString *href(href_);
8225 NSRange colon([href rangeOfString:@"://"]);
8226 if (colon.location != NSNotFound)
8227 href = [href substringFromIndex:(colon.location + 3)];
8228 href = [href stringByAddingPercentEscapes];
8229 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8230 href = [href stringByCachingURLWithCurrentCDN];
8232 NSURL *url([NSURL URLWithString:href]);
8234 NSStringEncoding encoding;
8235 NSError *error(nil);
8237 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8238 return [warning length] == 0 ? nil : warning;
8242 - (void) _endConnection:(NSURLConnection *)connection {
8243 // XXX: the memory management in this method is horribly awkward
8245 NSURLConnection **field = NULL;
8246 if (connection == trivial_)
8248 else if (connection == trivial_bz2_)
8249 field = &trivial_bz2_;
8250 else if (connection == trivial_gz_)
8251 field = &trivial_gz_;
8252 _assert(field != NULL);
8253 [connection release];
8258 trivial_bz2_ == nil &&
8264 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8267 UIAlertView *alert = [[[UIAlertView alloc]
8268 initWithTitle:UCLocalize("SOURCE_WARNING")
8271 cancelButtonTitle:UCLocalize("CANCEL")
8273 UCLocalize("ADD_ANYWAY"),
8277 [alert setContext:@"warning"];
8278 [alert setNumberOfRows:1];
8282 } else if (error_ != nil) {
8283 UIAlertView *alert = [[[UIAlertView alloc]
8284 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8285 message:[error_ localizedDescription]
8287 cancelButtonTitle:UCLocalize("OK")
8288 otherButtonTitles:nil
8291 [alert setContext:@"urlerror"];
8294 UIAlertView *alert = [[[UIAlertView alloc]
8295 initWithTitle:UCLocalize("NOT_REPOSITORY")
8296 message:UCLocalize("NOT_REPOSITORY_EX")
8298 cancelButtonTitle:UCLocalize("OK")
8299 otherButtonTitles:nil
8302 [alert setContext:@"trivial"];
8306 [delegate_ releaseNetworkActivityIndicator];
8308 [delegate_ removeProgressHUD:hud_];
8317 if (error_ != nil) {
8324 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8325 switch ([response statusCode]) {
8331 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8332 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8334 error_ = [error retain];
8335 [self _endConnection:connection];
8338 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8339 [self _endConnection:connection];
8342 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8343 NSMutableURLRequest *request = [NSMutableURLRequest
8344 requestWithURL:[NSURL URLWithString:href]
8345 cachePolicy:NSURLRequestUseProtocolCachePolicy
8346 timeoutInterval:120.0
8349 [request setHTTPMethod:method];
8351 if (Machine_ != NULL)
8352 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8353 if (UniqueID_ != nil)
8354 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8356 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8358 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8361 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8362 NSString *context([alert context]);
8364 if ([context isEqualToString:@"source"]) {
8367 NSString *href = [[alert textField] text];
8369 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8371 if (![href hasSuffix:@"/"])
8372 href_ = [href stringByAppendingString:@"/"];
8375 href_ = [href_ retain];
8377 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8378 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8379 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8380 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8384 // XXX: this is stupid
8385 hud_ = [[delegate_ addProgressHUD] retain];
8386 [hud_ setText:UCLocalize("VERIFYING_URL")];
8387 [delegate_ retainNetworkActivityIndicator];
8396 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8397 } else if ([context isEqualToString:@"trivial"])
8398 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8399 else if ([context isEqualToString:@"urlerror"])
8400 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8401 else if ([context isEqualToString:@"warning"]) {
8416 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8421 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8423 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8424 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8425 [list_ setRowHeight:56];
8426 [list_ setDataSource:self];
8427 [list_ setDelegate:self];
8428 [[self view] addSubview:list_];
8431 - (void) viewDidLoad {
8432 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8433 [self updateButtonsForEditingStatus:NO animated:NO];
8436 - (void) releaseSubviews {
8441 - (id) initWithDatabase:(Database *)database {
8442 if ((self = [super init]) != nil) {
8443 database_ = database;
8444 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8448 - (void) reloadData {
8452 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8455 [sources_ removeAllObjects];
8456 [sources_ addObjectsFromArray:[database_ sources]];
8458 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8461 int count([sources_ count]);
8463 for (int i = 0; i != count; i++) {
8464 if ([[sources_ objectAtIndex:i] record] == nil)
8469 [list_ setEditing:NO];
8470 [self updateButtonsForEditingStatus:NO animated:NO];
8474 - (void) showAddSourcePrompt {
8475 UIAlertView *alert = [[[UIAlertView alloc]
8476 initWithTitle:UCLocalize("ENTER_APT_URL")
8479 cancelButtonTitle:UCLocalize("CANCEL")
8481 UCLocalize("ADD_SOURCE"),
8485 [alert setContext:@"source"];
8486 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8488 [alert setNumberOfRows:1];
8489 [alert addTextFieldWithValue:@"http://" label:@""];
8491 UITextInputTraits *traits = [[alert textField] textInputTraits];
8492 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8493 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8494 [traits setKeyboardType:UIKeyboardTypeURL];
8495 // XXX: UIReturnKeyDone
8496 [traits setReturnKeyType:UIReturnKeyNext];
8501 - (void) addButtonClicked {
8502 [self showAddSourcePrompt];
8505 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8506 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8507 initWithTitle:UCLocalize("ADD")
8508 style:UIBarButtonItemStylePlain
8510 action:@selector(addButtonClicked)
8511 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8513 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8514 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8515 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8517 action:@selector(editButtonClicked)
8518 ] autorelease] animated:animated];
8520 if (IsWildcat_ && !editing)
8521 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8522 initWithTitle:UCLocalize("SETTINGS")
8523 style:UIBarButtonItemStylePlain
8525 action:@selector(settingsButtonClicked)
8529 - (void) settingsButtonClicked {
8530 [delegate_ showSettings];
8533 - (void) editButtonClicked {
8534 [list_ setEditing:![list_ isEditing] animated:YES];
8536 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8542 /* Settings Controller {{{ */
8543 @interface SettingsController : CYViewController <
8544 UITableViewDataSource,
8547 _transient Database *database_;
8548 // XXX: ok, "roledelegate_"?...
8549 _transient id roledelegate_;
8550 UITableView *table_;
8551 UISegmentedControl *segment_;
8555 - (void) showDoneButton;
8556 - (void) resizeSegmentedControl;
8560 @implementation SettingsController
8563 [self releaseSubviews];
8569 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8571 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8572 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8573 [table_ setDelegate:self];
8574 [table_ setDataSource:self];
8575 [[self view] addSubview:table_];
8577 NSArray *items = [NSArray arrayWithObjects:
8579 UCLocalize("HACKER"),
8580 UCLocalize("DEVELOPER"),
8582 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8583 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8584 [container_ addSubview:segment_];
8587 - (void) viewDidLoad {
8588 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8591 if ([Role_ isEqualToString:@"User"]) index = 0;
8592 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8593 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8595 [segment_ setSelectedSegmentIndex:index];
8596 [self showDoneButton];
8599 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8600 [self resizeSegmentedControl];
8603 - (void) releaseSubviews {
8610 [container_ release];
8614 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8615 if ((self = [super init]) != nil) {
8616 database_ = database;
8617 roledelegate_ = delegate;
8621 - (void) resizeSegmentedControl {
8622 CGFloat width = [[self view] frame].size.width;
8623 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8626 - (void) viewWillAppear:(BOOL)animated {
8627 [super viewWillAppear:animated];
8629 [self resizeSegmentedControl];
8632 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8633 [self resizeSegmentedControl];
8636 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8637 [self resizeSegmentedControl];
8641 NSString *role(nil);
8643 switch ([segment_ selectedSegmentIndex]) {
8644 case 0: role = @"User"; break;
8645 case 1: role = @"Hacker"; break;
8646 case 2: role = @"Developer"; break;
8651 if (![role isEqualToString:Role_]) {
8652 bool rolling(Role_ == nil);
8655 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8659 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8663 [roledelegate_ loadData];
8665 [roledelegate_ updateData];
8669 - (void) segmentChanged:(UISegmentedControl *)control {
8670 [self showDoneButton];
8673 - (void) saveAndClose {
8676 [[self navigationItem] setRightBarButtonItem:nil];
8677 [[self navigationController] dismissModalViewControllerAnimated:YES];
8680 - (void) doneButtonClicked {
8681 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8682 [spinner startAnimating];
8683 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8684 [[self navigationItem] setRightBarButtonItem:spinItem];
8686 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8689 - (void) showDoneButton {
8690 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8691 initWithTitle:UCLocalize("DONE")
8692 style:UIBarButtonItemStyleDone
8694 action:@selector(doneButtonClicked)
8695 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8698 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8699 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8703 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8707 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8708 return nil; // This method is required by the protocol.
8711 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8713 return UCLocalize("ROLE_EX");
8715 return [NSString stringWithFormat:
8716 @"%@: %@\n%@: %@\n%@: %@",
8717 UCLocalize("USER"), UCLocalize("USER_EX"),
8718 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8719 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8724 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8725 return section == 3 ? 44.0f : 0;
8728 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8729 return section == 3 ? container_ : nil;
8732 - (void) reloadData {
8734 [table_ reloadData];
8739 /* Stash Controller {{{ */
8740 @interface StashController : CYViewController {
8741 UIActivityIndicatorView *spinner_;
8748 @implementation StashController
8751 [self releaseSubviews];
8757 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8758 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8760 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8761 CGRect spinrect = [spinner_ frame];
8762 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8763 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8764 [spinner_ setFrame:spinrect];
8765 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8766 [[self view] addSubview:spinner_];
8767 [spinner_ startAnimating];
8770 captrect.size.width = [[self view] frame].size.width;
8771 captrect.size.height = 40.0f;
8772 captrect.origin.x = 0;
8773 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8774 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8775 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8776 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8777 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8778 [caption_ setTextColor:[UIColor whiteColor]];
8779 [caption_ setBackgroundColor:[UIColor clearColor]];
8780 [caption_ setShadowColor:[UIColor blackColor]];
8781 [caption_ setTextAlignment:UITextAlignmentCenter];
8782 [[self view] addSubview:caption_];
8785 statusrect.size.width = [[self view] frame].size.width;
8786 statusrect.size.height = 30.0f;
8787 statusrect.origin.x = 0;
8788 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8789 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8790 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8791 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8792 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8793 [status_ setTextColor:[UIColor whiteColor]];
8794 [status_ setBackgroundColor:[UIColor clearColor]];
8795 [status_ setShadowColor:[UIColor blackColor]];
8796 [status_ setTextAlignment:UITextAlignmentCenter];
8797 [[self view] addSubview:status_];
8800 - (void) releaseSubviews {
8814 @interface Cydia : UIApplication <
8815 ConfirmationControllerDelegate,
8818 UINavigationControllerDelegate,
8819 UITabBarControllerDelegate
8821 // XXX: evaluate all fields for _transient
8824 CYTabBarController *tabbar_;
8825 CYEmulatedLoadingController *emulated_;
8827 NSMutableArray *essential_;
8828 NSMutableArray *broken_;
8830 Database *database_;
8837 StashController *stash_;
8846 @implementation Cydia
8848 - (void) beginUpdate {
8849 [tabbar_ beginUpdate];
8853 return [tabbar_ updating];
8857 if ([broken_ count] != 0) {
8858 int count = [broken_ count];
8860 UIAlertView *alert = [[[UIAlertView alloc]
8861 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8862 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8864 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8866 UCLocalize("TEMPORARY_IGNORE"),
8870 [alert setContext:@"fixhalf"];
8871 [alert setNumberOfRows:2];
8873 } else if (!Ignored_ && [essential_ count] != 0) {
8874 int count = [essential_ count];
8876 UIAlertView *alert = [[[UIAlertView alloc]
8877 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8878 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8880 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8882 UCLocalize("UPGRADE_ESSENTIAL"),
8883 UCLocalize("COMPLETE_UPGRADE"),
8887 [alert setContext:@"upgrade"];
8892 - (void) _saveConfig {
8898 NSString *error(nil);
8900 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8902 NSError *error(nil);
8903 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8904 NSLog(@"failure to save metadata data: %@", error);
8909 NSLog(@"failure to serialize metadata: %@", error);
8914 // Navigation controller for the queuing badge.
8915 - (CYNavigationController *) queueNavigationController {
8916 NSArray *controllers = [tabbar_ viewControllers];
8917 return [controllers objectAtIndex:3];
8920 - (void) _updateData {
8923 [tabbar_ reloadData];
8925 CYNavigationController *navigation = [self queueNavigationController];
8927 id queuedelegate = nil;
8928 if ([[navigation viewControllers] count] > 0)
8929 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8931 [queuedelegate queueStatusDidChange];
8932 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8935 - (void) _refreshIfPossible:(NSDate *)update {
8936 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8938 bool recently = false;
8939 if (update != nil) {
8940 NSTimeInterval interval([update timeIntervalSinceNow]);
8941 if (interval <= 0 && interval > -(15*60))
8945 // Don't automatic refresh if:
8946 // - We already refreshed recently.
8947 // - We already auto-refreshed this launch.
8948 // - Auto-refresh is disabled.
8949 if (recently || loaded_ || ManualRefresh) {
8950 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8952 // If we are cancelling, we need to make sure it knows it's already loaded.
8956 // We are going to load, so remember that.
8960 SCNetworkReachabilityFlags flags; {
8961 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8962 SCNetworkReachabilityGetFlags(reachability, &flags);
8963 CFRelease(reachability);
8966 // XXX: this elaborate mess is what Apple is using to determine this? :(
8967 // XXX: do we care if the user has to intervene? maybe that's ok?
8969 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8970 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8971 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8972 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8973 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8974 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8978 // If we can reach the server, auto-refresh!
8980 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8985 - (void) refreshIfPossible {
8986 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8989 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8990 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8991 [hud setText:UCLocalize("RELOADING_DATA")];
8993 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8996 [self removeProgressHUD:hud];
9000 [essential_ removeAllObjects];
9001 [broken_ removeAllObjects];
9003 NSArray *packages([database_ packages]);
9004 for (Package *package in packages) {
9006 [broken_ addObject:package];
9007 if ([package upgradableAndEssential:NO]) {
9008 if ([package essential])
9009 [essential_ addObject:package];
9014 NSLog(@"changes:#%u", changes);
9016 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9019 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9020 [changesItem setBadgeValue:badge];
9021 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9022 [self setApplicationIconBadgeNumber:changes];
9025 [changesItem setBadgeValue:nil];
9026 [changesItem setAnimatedBadge:NO];
9027 [self setApplicationIconBadgeNumber:0];
9032 [self refreshIfPossible];
9035 - (void) updateData {
9044 @synchronized (self) {
9045 [self _reloadDataWithInvocation:nil];
9049 - (void) disemulate {
9050 if (emulated_ == nil)
9053 [window_ addSubview:[tabbar_ view]];
9054 [[emulated_ view] removeFromSuperview];
9055 [emulated_ release];
9057 [window_ setUserInteractionEnabled:YES];
9060 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9061 UINavigationController *navigation([[[CYNavigationController alloc] initWithRootViewController:controller] autorelease]);
9063 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9065 UIViewController *parent;
9066 if (emulated_ == nil)
9075 [parent presentModalViewController:navigation animated:YES];
9078 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9079 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9081 if (navigation != nil)
9082 [navigation pushViewController:progress animated:YES];
9084 [self presentModalViewController:progress force:YES];
9086 [progress invoke:invocation withTitle:title];
9090 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9091 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9094 - (void) repairWithInvocation:(NSInvocation *)invocation {
9096 [self invokeNewProgress:invocation forController:nil withTitle:UCLocalize("REPAIRING")];
9100 - (void) repairWithSelector:(SEL)selector {
9101 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9107 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9108 _assert(file != NULL);
9110 for (NSString *key in [Sources_ allKeys]) {
9111 NSDictionary *source([Sources_ objectForKey:key]);
9113 fprintf(file, "%s %s %s\n",
9114 [[source objectForKey:@"Type"] UTF8String],
9115 [[source objectForKey:@"URI"] UTF8String],
9116 [[source objectForKey:@"Distribution"] UTF8String]
9122 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:UCLocalize("UPDATING_SOURCES")];
9127 - (void) addTrivialSource:(NSString *)href {
9128 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9131 @"./", @"Distribution",
9132 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9137 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9138 @synchronized (self) {
9139 [self _reloadDataWithInvocation:invocation];
9143 - (void) reloadData {
9144 [self reloadDataWithInvocation:nil];
9148 pkgProblemResolver *resolver = [database_ resolver];
9150 resolver->InstallProtect();
9151 if (!resolver->Resolve(true))
9156 // XXX: this is a really crappy way of doing this.
9157 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9158 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9159 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9160 if ([tabbar_ updating])
9161 [tabbar_ cancelUpdate];
9163 if (![database_ prepare])
9166 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9167 [page setDelegate:self];
9168 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
9169 [confirm_ setDelegate:self];
9172 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9173 [tabbar_ presentModalViewController:confirm_ animated:YES];
9179 @synchronized (self) {
9184 - (void) clearPackage:(Package *)package {
9185 @synchronized (self) {
9192 - (void) installPackages:(NSArray *)packages {
9193 @synchronized (self) {
9194 for (Package *package in packages)
9201 - (void) installPackage:(Package *)package {
9202 @synchronized (self) {
9209 - (void) removePackage:(Package *)package {
9210 @synchronized (self) {
9217 - (void) distUpgrade {
9218 @synchronized (self) {
9219 if (![database_ upgrade])
9225 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9228 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:UCLocalize("RUNNING")];
9233 - (void) showSettings {
9234 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9235 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9237 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9238 [tabbar_ presentModalViewController:nav animated:YES];
9241 - (void) retainNetworkActivityIndicator {
9242 if (activity_++ == 0)
9243 [self setNetworkActivityIndicatorVisible:YES];
9246 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9250 - (void) releaseNetworkActivityIndicator {
9251 if (--activity_ == 0)
9252 [self setNetworkActivityIndicatorVisible:NO];
9255 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9260 - (void) cancelAndClear:(bool)clear {
9261 @synchronized (self) {
9273 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9274 NSString *context([alert context]);
9276 if ([context isEqualToString:@"conffile"]) {
9277 FILE *input = [database_ input];
9278 if (button == [alert cancelButtonIndex])
9279 fprintf(input, "N\n");
9280 else if (button == [alert firstOtherButtonIndex])
9281 fprintf(input, "Y\n");
9284 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9285 } else if ([context isEqualToString:@"fixhalf"]) {
9286 if (button == [alert cancelButtonIndex]) {
9287 @synchronized (self) {
9288 for (Package *broken in broken_) {
9291 NSString *id = [broken id];
9292 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9293 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9294 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9295 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9301 } else if (button == [alert firstOtherButtonIndex]) {
9302 [broken_ removeAllObjects];
9306 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9307 } else if ([context isEqualToString:@"upgrade"]) {
9308 if (button == [alert firstOtherButtonIndex]) {
9309 @synchronized (self) {
9310 for (Package *essential in essential_)
9311 [essential install];
9316 } else if (button == [alert firstOtherButtonIndex] + 1) {
9318 } else if (button == [alert cancelButtonIndex]) {
9322 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9326 - (void) system:(NSString *)command { _pooled
9328 system([command UTF8String]);
9332 - (void) applicationWillSuspend {
9334 [super applicationWillSuspend];
9337 - (BOOL) isSafeToSuspend {
9338 // Use external process status API internally.
9339 // This is probably a really bad idea.
9340 // XXX: what is the point of this? does this solve anything at all?
9341 uint64_t status = 0;
9343 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9344 notify_get_state(notify_token, &status);
9345 notify_cancel(notify_token);
9348 return locked_ == 0 && status == 0;
9351 - (void) applicationSuspend:(__GSEvent *)event {
9352 if ([self isSafeToSuspend])
9353 [super applicationSuspend:event];
9356 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9357 if ([self isSafeToSuspend])
9358 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9361 - (void) _setSuspended:(BOOL)value {
9362 if ([self isSafeToSuspend])
9363 [super _setSuspended:value];
9366 - (UIProgressHUD *) addProgressHUD {
9367 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9368 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9370 [window_ setUserInteractionEnabled:NO];
9373 UIViewController *target = tabbar_;
9374 while ([target modalViewController] != nil) target = [target modalViewController];
9375 [[target view] addSubview:hud];
9381 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9383 [hud removeFromSuperview];
9384 [window_ setUserInteractionEnabled:YES];
9388 - (CYViewController *) pageForPackage:(NSString *)name {
9389 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9392 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9393 NSString *scheme([[url scheme] lowercaseString]);
9394 if ([[url absoluteString] length] <= [scheme length] + 3)
9396 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9397 NSArray *components([path pathComponents]);
9399 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9400 return [self pageForPackage:[components objectAtIndex:1]];
9402 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9405 NSString *base([components objectAtIndex:0]);
9407 CYViewController *controller = nil;
9409 if ([base isEqualToString:@"url"]) {
9410 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9411 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9412 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9413 } else if (!external && [components count] == 1) {
9414 if ([base isEqualToString:@"manage"]) {
9415 controller = [[[ManageController alloc] init] autorelease];
9418 if ([base isEqualToString:@"sources"]) {
9419 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9422 if ([base isEqualToString:@"home"]) {
9423 controller = [[[HomeController alloc] init] autorelease];
9426 if ([base isEqualToString:@"sections"]) {
9427 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9430 if ([base isEqualToString:@"search"]) {
9431 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9434 if ([base isEqualToString:@"changes"]) {
9435 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9438 if ([base isEqualToString:@"installed"]) {
9439 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9441 } else if ([components count] == 2) {
9442 NSString *argument = [components objectAtIndex:1];
9444 if ([base isEqualToString:@"package"]) {
9445 controller = [self pageForPackage:argument];
9448 if (!external && [base isEqualToString:@"search"]) {
9449 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9450 [(SearchController *)controller setSearchTerm:argument];
9453 if (!external && [base isEqualToString:@"sections"]) {
9454 if ([argument isEqualToString:@"all"])
9456 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9459 if (!external && [base isEqualToString:@"sources"]) {
9460 if ([argument isEqualToString:@"add"]) {
9461 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9462 [(SourcesController *)controller showAddSourcePrompt];
9464 Source *source = [database_ sourceWithKey:argument];
9465 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9469 if (!external && [base isEqualToString:@"launch"]) {
9470 [self launchApplicationWithIdentifier:argument suspended:NO];
9473 } else if (!external && [components count] == 3) {
9474 NSString *arg1 = [components objectAtIndex:1];
9475 NSString *arg2 = [components objectAtIndex:2];
9477 if ([base isEqualToString:@"package"]) {
9478 if ([arg2 isEqualToString:@"settings"]) {
9479 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9480 } else if ([arg2 isEqualToString:@"files"]) {
9481 if (Package *package = [database_ packageWithName:arg1]) {
9482 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9483 [(FileTable *)controller setPackage:package];
9489 [controller setDelegate:self];
9493 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9494 CYViewController *page([self pageForURL:url forExternal:external]);
9497 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9498 [nav setViewControllers:[NSArray arrayWithObject:page]];
9499 [tabbar_ setUnselectedViewController:nav];
9505 - (void) applicationOpenURL:(NSURL *)url {
9506 [super applicationOpenURL:url];
9508 if (!loaded_) starturl_ = [url retain];
9509 else [self openCydiaURL:url forExternal:YES];
9512 - (void) applicationWillResignActive:(UIApplication *)application {
9513 // Stop refreshing if you get a phone call or lock the device.
9514 if ([tabbar_ updating])
9515 [tabbar_ cancelUpdate];
9517 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9518 [super applicationWillResignActive:application];
9521 - (void) applicationWillTerminate:(UIApplication *)application {
9523 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9524 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9525 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9530 - (void) setConfigurationData:(NSString *)data {
9531 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9533 if (!conffile_r(data)) {
9534 lprintf("E:invalid conffile\n");
9538 NSString *ofile = conffile_r[1];
9539 //NSString *nfile = conffile_r[2];
9541 UIAlertView *alert = [[[UIAlertView alloc]
9542 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9543 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9545 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9547 UCLocalize("ACCEPT_NEW_COPY"),
9548 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9552 [alert setContext:@"conffile"];
9556 - (void) addStashController {
9558 stash_ = [[StashController alloc] init];
9559 [window_ addSubview:[stash_ view]];
9562 - (void) removeStashController {
9563 [[stash_ view] removeFromSuperview];
9569 [self setIdleTimerDisabled:YES];
9571 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9572 UpdateExternalStatus(1);
9573 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9574 UpdateExternalStatus(0);
9576 [self removeStashController];
9578 if (ExecFork() == 0) {
9579 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9580 perror("launchctl stop");
9584 - (void) setupViewControllers {
9585 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9587 NSMutableArray *items([NSMutableArray arrayWithObjects:
9588 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9589 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9590 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9591 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9595 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9596 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9598 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9601 NSMutableArray *controllers([NSMutableArray array]);
9602 for (UITabBarItem *item in items) {
9603 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9604 [controller setTabBarItem:item];
9605 [controllers addObject:controller];
9607 [tabbar_ setViewControllers:controllers];
9609 [tabbar_ setUpdateDelegate:self];
9612 - (void) applicationDidFinishLaunching:(id)unused {
9614 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9615 [self setApplicationSupportsShakeToEdit:NO];
9617 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9618 initWithMemoryCapacity:524288
9619 diskCapacity:10485760
9620 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9623 [CYBrowserController _initialize];
9625 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9627 Font12_ = [[UIFont systemFontOfSize:12] retain];
9628 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9629 Font14_ = [[UIFont systemFontOfSize:14] retain];
9630 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9631 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9633 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9634 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9636 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9637 [window_ orderFront:self];
9638 [window_ makeKey:self];
9639 [window_ setHidden:NO];
9642 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9643 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9644 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9645 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9646 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9647 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9648 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9649 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9650 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9653 [self addStashController];
9654 // XXX: this would be much cleaner as a yieldToSelector:
9655 // that way the removeStashController could happen right here inline
9656 // we also could no longer require the useless stash_ field anymore
9657 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9661 database_ = [Database sharedInstance];
9662 [database_ setDelegate:self];
9664 [window_ setUserInteractionEnabled:NO];
9665 [self setupViewControllers];
9667 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9668 [window_ addSubview:[emulated_ view]];
9670 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9677 [window_ setUserInteractionEnabled:YES];
9678 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9681 if ([emulated_ modalViewController] != nil)
9682 [emulated_ dismissModalViewControllerAnimated:YES];
9683 [window_ setUserInteractionEnabled:NO];
9691 int selectedIndex = 0;
9692 NSMutableArray *items = nil;
9694 bool recently = false;
9695 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9696 if (closed != nil) {
9697 NSTimeInterval interval([closed timeIntervalSinceNow]);
9698 // XXX: Is 15 minutes the optimal time here?
9699 if (interval <= 0 && interval > -(15*60))
9703 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9704 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9707 for (NSArray *entry in items)
9708 if ([entry count] <= 0)
9711 if (!recently || !items || !enough) {
9713 items = [NSMutableArray array];
9714 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9715 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9716 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9718 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9720 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9721 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9723 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9726 [tabbar_ setSelectedIndex:selectedIndex];
9727 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9728 NSArray *stack = [items objectAtIndex:tab];
9729 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9730 NSMutableArray *current = [NSMutableArray array];
9732 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9733 NSString *addr = [stack objectAtIndex:nav];
9734 NSURL *url = [NSURL URLWithString:addr];
9735 CYViewController *page = [self pageForURL:url forExternal:NO];
9737 [current addObject:page];
9740 [navigation setViewControllers:current];
9743 // (Try to) show the startup URL.
9744 if (starturl_ != nil) {
9745 [self openCydiaURL:starturl_ forExternal:NO];
9746 [starturl_ release];
9751 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9752 if (item != nil && IsWildcat_) {
9753 [sheet showFromBarButtonItem:item animated:YES];
9755 [sheet showInView:window_];
9759 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9760 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9761 [progress setTitle:task];
9762 [progress addProgressEvent:event];
9765 - (void) addProgressEventForTask:(NSArray *)data {
9766 CydiaProgressEvent *event([data objectAtIndex:0]);
9767 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9768 [self addProgressEvent:event forTask:task];
9771 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9772 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9778 id Alloc_(id self, SEL selector) {
9779 id object = alloc_(self, selector);
9780 lprintf("[%s]A-%p\n", self->isa->name, object);
9785 id Dealloc_(id self, SEL selector) {
9786 id object = dealloc_(self, selector);
9787 lprintf("[%s]D-%p\n", self->isa->name, object);
9791 Class $WebDefaultUIKitDelegate;
9793 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9794 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9795 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9796 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9799 static NSNumber *shouldPlayKeyboardSounds;
9803 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9805 case 1104: // Keyboard Button Clicked
9806 case 1105: // Keyboard Delete Repeated
9807 if (shouldPlayKeyboardSounds == nil) {
9808 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9809 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9812 if (![shouldPlayKeyboardSounds boolValue])
9816 _UIHardware$_playSystemSound$(self, _cmd, sound);
9820 Class $UIApplication;
9822 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9823 static BOOL initialized = NO;
9824 static BOOL started = NO;
9826 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9827 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9829 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9830 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9831 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9832 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9834 if (initialized && !enabled) {
9836 [bundle performSelector:@selector(_accessibilityStopServer)];
9837 } else if (enabled) {
9841 [bundle performSelector:@selector(_accessibilityStartServer)];
9847 int main(int argc, char *argv[]) { _pooled
9850 UpdateExternalStatus(0);
9852 if (Class $UIDevice = objc_getClass("UIDevice")) {
9853 UIDevice *device([$UIDevice currentDevice]);
9854 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9858 UIScreen *screen([UIScreen mainScreen]);
9859 if ([screen respondsToSelector:@selector(scale)])
9860 ScreenScale_ = [screen scale];
9864 UIDevice *device([UIDevice currentDevice]);
9865 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9868 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9869 if (idiom == UIUserInterfaceIdiomPhone)
9871 else if (idiom == UIUserInterfaceIdiomPad)
9874 NSLog(@"unknown UIUserInterfaceIdiom!");
9877 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9879 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9881 /* Library Hacks {{{ */
9882 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9884 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9885 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9886 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9887 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9888 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9891 $UIHardware = objc_getClass("UIHardware");
9892 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9893 if (UIHardware$_playSystemSound$ != NULL) {
9894 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9895 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9898 $UIApplication = objc_getClass("UIApplication");
9899 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9900 if (UIApplication$_updateApplicationAccessibility != NULL) {
9901 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9902 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9905 /* Set Locale {{{ */
9906 Locale_ = CFLocaleCopyCurrent();
9907 Languages_ = [NSLocale preferredLanguages];
9908 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9909 //NSLog(@"%@", [Languages_ description]);
9912 if (Languages_ == nil || [Languages_ count] == 0)
9913 // XXX: consider just setting to C and then falling through?
9916 lang = [[Languages_ objectAtIndex:0] UTF8String];
9917 setenv("LANG", lang, true);
9920 //std::setlocale(LC_ALL, lang);
9921 NSLog(@"Setting Language: %s", lang);
9924 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9926 /* Parse Arguments {{{ */
9927 bool substrate(false);
9933 for (int argi(1); argi != argc; ++argi)
9934 if (strcmp(argv[argi], "--") == 0) {
9936 argv[argi] = argv[0];
9942 for (int argi(1); argi != arge; ++argi)
9943 if (strcmp(args[argi], "--substrate") == 0)
9946 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9950 App_ = [[NSBundle mainBundle] bundlePath];
9951 Home_ = NSHomeDirectory();
9957 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9958 alloc_ = alloc->method_imp;
9959 alloc->method_imp = (IMP) &Alloc_;*/
9961 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9962 dealloc_ = dealloc->method_imp;
9963 dealloc->method_imp = (IMP) &Dealloc_;*/
9965 /* System Information {{{ */
9969 size = sizeof(maxproc);
9970 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9971 perror("sysctlbyname(\"kern.maxproc\", ?)");
9972 else if (maxproc < 64) {
9974 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9975 perror("sysctlbyname(\"kern.maxproc\", #)");
9978 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9979 char *osversion = new char[size];
9980 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9981 perror("sysctlbyname(\"kern.osversion\", ?)");
9983 System_ = [NSString stringWithUTF8String:osversion];
9985 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9986 char *machine = new char[size];
9987 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9988 perror("sysctlbyname(\"hw.machine\", ?)");
9992 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9993 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9994 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9995 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9999 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
10000 NSData *data((NSData *) ecid);
10001 size_t length([data length]);
10002 uint8_t bytes[length];
10003 [data getBytes:bytes];
10004 char string[length * 2 + 1];
10005 for (size_t i(0); i != length; ++i)
10006 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10007 ChipID_ = [NSString stringWithUTF8String:string];
10011 IOObjectRelease(service);
10015 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10017 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10018 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10019 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10021 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10022 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10023 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10025 if (mcc != NULL && mnc != NULL)
10026 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10033 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10034 Build_ = [system objectForKey:@"ProductBuildVersion"];
10035 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10036 Product_ = [info objectForKey:@"SafariProductVersion"];
10037 Safari_ = [info objectForKey:@"CFBundleVersion"];
10040 /* Load Database {{{ */
10042 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10044 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10046 if (Metadata_ == NULL)
10047 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10049 Settings_ = [Metadata_ objectForKey:@"Settings"];
10051 Packages_ = [Metadata_ objectForKey:@"Packages"];
10052 Sections_ = [Metadata_ objectForKey:@"Sections"];
10053 Sources_ = [Metadata_ objectForKey:@"Sources"];
10055 Token_ = [Metadata_ objectForKey:@"Token"];
10058 if (Settings_ != nil)
10059 Role_ = [Settings_ objectForKey:@"Role"];
10061 if (Sections_ == nil) {
10062 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10063 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10066 if (Sources_ == nil) {
10067 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10068 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10073 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10076 if (Packages_ != nil) {
10078 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10082 [Metadata_ removeObjectForKey:@"Packages"];
10088 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10090 #define MobileSubstrate_(name) \
10091 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) \
10092 dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL);
10094 MobileSubstrate_(Activator)
10095 MobileSubstrate_(libstatusbar)
10096 MobileSubstrate_(SimulatedKeyEvents)
10097 MobileSubstrate_(WinterBoard)
10099 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10100 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10102 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10104 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10105 unlink("/tmp/.cydia.fw");
10107 } else if (access("/User", F_OK) != 0 || version < 2) {
10110 system("/usr/libexec/cydia/firmware.sh");
10114 _assert([[NSFileManager defaultManager]
10115 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10116 withIntermediateDirectories:YES
10121 if (access("/tmp/cydia.chk", F_OK) == 0) {
10122 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10123 _assert(errno == ENOENT);
10124 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10125 _assert(errno == ENOENT);
10128 /* APT Initialization {{{ */
10129 _assert(pkgInitConfig(*_config));
10130 _assert(pkgInitSystem(*_config, _system));
10133 _config->Set("APT::Acquire::Translation", lang);
10135 // XXX: this timeout might be important :(
10136 //_config->Set("Acquire::http::Timeout", 15);
10138 _config->Set("Acquire::http::MaxParallel", 3);
10140 /* Color Choices {{{ */
10141 space_ = CGColorSpaceCreateDeviceRGB();
10143 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10144 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10145 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10146 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10147 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10148 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10149 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10150 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10151 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10153 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10154 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10156 /* UIKit Configuration {{{ */
10157 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10158 if ($GSFontSetUseLegacyFontMetrics != NULL)
10159 $GSFontSetUseLegacyFontMetrics(YES);
10161 // XXX: I have a feeling this was important
10162 //UIKeyboardDisableAutomaticAppearance();
10165 Colon_ = UCLocalize("COLON_DELIMITED");
10166 Elision_ = UCLocalize("ELISION");
10167 Error_ = UCLocalize("ERROR");
10168 Warning_ = UCLocalize("WARNING");
10171 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10173 CGColorSpaceRelease(space_);
10174 CFRelease(Locale_);