1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
122 #include <Cytore.hpp>
124 #include "UICaboodle/BrowserView.h"
125 #include "SDURLCache/SDURLCache.h"
127 #include "substrate.h"
136 #define _timestamp ({ \
138 gettimeofday(&tv, NULL); \
139 tv.tv_sec * 1000000 + tv.tv_usec; \
142 typedef std::vector<class ProfileTime *> TimeList;
152 ProfileTime(const char *name) :
156 times_.push_back(this);
159 void AddTime(uint64_t time) {
166 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
178 ProfileTimer(ProfileTime &time) :
185 time_.AddTime(_timestamp - start_);
190 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
192 std::cerr << "========" << std::endl;
195 #define _profile(name) { \
196 static ProfileTime name(#name); \
197 ProfileTimer _ ## name(name);
202 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
204 #define CYPoolStart() \
205 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
207 #define CYPoolEnd() \
211 // Hash Functions/Structures {{{
212 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
220 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
222 static _finline NSString *CydiaURL(NSString *path) {
224 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
225 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
226 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
227 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
228 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
230 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
233 static _finline void UpdateExternalStatus(uint64_t newStatus) {
235 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
236 notify_set_state(notify_token, newStatus);
237 notify_cancel(notify_token);
239 notify_post("com.saurik.Cydia.status");
242 /* [NSObject yieldToSelector:(withObject:)] {{{*/
243 @interface NSObject (Cydia)
244 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
245 - (id) yieldToSelector:(SEL)selector;
248 @implementation NSObject (Cydia)
253 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
254 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
255 id object([[context objectAtIndex:1] nonretainedObjectValue]);
256 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
258 /* XXX: deal with exceptions */
259 id value([self performSelector:selector withObject:object]);
261 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
262 [context removeAllObjects];
263 if ([signature methodReturnLength] != 0 && value != nil)
264 [context addObject:value];
269 performSelectorOnMainThread:@selector(doNothing)
275 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
276 volatile bool stopped(false);
278 NSMutableArray *context([NSMutableArray arrayWithObjects:
279 [NSValue valueWithPointer:selector],
280 [NSValue valueWithNonretainedObject:object],
281 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
284 NSThread *thread([[[NSThread alloc]
286 selector:@selector(_yieldToContext:)
292 NSRunLoop *loop([NSRunLoop currentRunLoop]);
293 NSDate *future([NSDate distantFuture]);
294 NSString *mode([loop currentMode] ?: NSDefaultRunLoopMode);
296 while (!stopped && [loop runMode:mode beforeDate:future]);
298 return [context count] == 0 ? nil : [context objectAtIndex:0];
301 - (id) yieldToSelector:(SEL)selector {
302 return [self yieldToSelector:selector withObject:nil];
308 /* Cydia Alert View {{{ */
309 @interface CYAlertView : UIAlertView {
313 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
317 @implementation CYAlertView
319 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
320 if ((self = [super init]) != nil) {
321 [self setTitle:title];
322 [self setDelegate:self];
323 for (NSString *button in buttons) [self addButtonWithTitle:button];
324 [self setCancelButtonIndex:index];
328 - (void) _updateFrameForDisplay {
329 [super _updateFrameForDisplay];
330 if ([self cancelButtonIndex] == -1) {
331 NSArray *buttons = [self buttons];
332 if ([buttons count]) {
333 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
334 for (UIThreePartButton *button in buttons)
335 [button setBackground:background forState:0];
340 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
341 button_ = buttonIndex + 1;
345 [self dismissWithClickedButtonIndex:-1 animated:YES];
348 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
349 [self setRunsModal:YES];
358 /* NSForcedOrderingSearch doesn't work on the iPhone */
359 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
360 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
361 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
363 #define lprintf(args...) fprintf(stderr, args)
366 #define TraceLogging (1 && !ForRelease)
367 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
368 #define ProfileTimes (0 && !ForRelease)
369 #define ForSaurik (0 && !ForRelease)
370 #define LogBrowser (0 && !ForRelease)
371 #define TrackResize (0 && !ForRelease)
372 #define ManualRefresh (1 && !ForRelease)
373 #define ShowInternals (0 && !ForRelease)
374 #define AlwaysReload (0 && !ForRelease)
375 #define TryIndexedCollation (0 && !ForRelease)
379 #define _trace(args...)
384 #define _profile(name) {
387 #define PrintTimes() do {} while (false)
391 typedef uint32_t (*SKRadixFunction)(id, void *);
393 @interface NSMutableArray (Radix)
394 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
402 @implementation NSMutableArray (Radix)
404 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
405 size_t count([self count]);
406 struct RadixItem_ *swap(new RadixItem_[count * 2]);
408 for (size_t i(0); i != count; ++i) {
409 RadixItem_ &item(swap[i]);
412 id object([self objectAtIndex:i]);
413 item.key = function(object, argument);
416 struct RadixItem_ *lhs(swap), *rhs(swap + count);
418 static const size_t width = 32;
419 static const size_t bits = 11;
420 static const size_t slots = 1 << bits;
421 static const size_t passes = (width + (bits - 1)) / bits;
423 size_t *hist(new size_t[slots]);
425 for (size_t pass(0); pass != passes; ++pass) {
426 memset(hist, 0, sizeof(size_t) * slots);
428 for (size_t i(0); i != count; ++i) {
429 uint32_t key(lhs[i].key);
431 key &= _not(uint32_t) >> width - bits;
436 for (size_t i(0); i != slots; ++i) {
437 size_t local(offset);
442 for (size_t i(0); i != count; ++i) {
443 uint32_t key(lhs[i].key);
445 key &= _not(uint32_t) >> width - bits;
446 rhs[hist[key]++] = lhs[i];
449 RadixItem_ *tmp(lhs);
456 const void **values(new const void *[count]);
457 for (size_t i(0); i != count; ++i)
458 values[i] = [self objectAtIndex:lhs[i].index];
459 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
467 /* Insertion Sort {{{ */
469 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
470 const char *ptr = (const char *)list;
472 CFIndex half = count / 2;
473 const char *probe = ptr + elementSize * half;
474 CFComparisonResult cr = comparator(element, probe, context);
475 if (0 == cr) return (probe - (const char *)list) / elementSize;
476 ptr = (cr < 0) ? ptr : probe + elementSize;
477 count = (cr < 0) ? half : (half + (count & 1) - 1);
479 return (ptr - (const char *)list) / elementSize;
482 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
483 const char *ptr = (const char *)list;
485 CFIndex half = count / 2;
486 const char *probe = ptr + elementSize * half;
487 CFComparisonResult cr = comparator(element, probe, context);
488 if (0 == cr) return (probe - (const char *)list) / elementSize;
489 ptr = (cr < 0) ? ptr : probe + elementSize;
490 count = (cr < 0) ? half : (half + (count & 1) - 1);
492 return (ptr - (const char *)list) / elementSize;
495 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
496 if (range.length == 0)
498 const void **values(new const void *[range.length]);
499 CFArrayGetValues(array, range, values);
501 #if HistogramInsertionSort > 0
502 uint32_t total(0), *offsets(new uint32_t[range.length]);
505 for (CFIndex index(1); index != range.length; ++index) {
506 const void *value(values[index]);
507 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
508 CFIndex correct(index);
509 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
510 #if HistogramInsertionSort > 1
511 NSLog(@"%@ < %@", value, values[correct - 1]);
516 if (correct != index) {
517 size_t offset(index - correct);
518 #if HistogramInsertionSort
522 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
524 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
525 values[correct] = value;
529 CFArrayReplaceValues(array, range, values, range.length);
532 #if HistogramInsertionSort > 0
533 for (CFIndex index(0); index != range.length; ++index)
534 if (offsets[index] != 0)
535 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
536 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
543 /* Apple Bug Fixes {{{ */
544 @implementation UIWebDocumentView (Cydia)
546 - (void) _setScrollerOffset:(CGPoint)offset {
547 UIScroller *scroller([self _scroller]);
549 CGSize size([scroller contentSize]);
550 CGSize bounds([scroller bounds].size);
553 max.x = size.width - bounds.width;
554 max.y = size.height - bounds.height;
562 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
563 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
565 [scroller setOffset:offset];
571 @interface NSInvocation (Cydia)
572 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target;
575 @implementation NSInvocation (Cydia)
577 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target {
578 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]]);
579 [invocation setTarget:target];
580 [invocation setSelector:selector];
586 @implementation WebScriptObject (NSFastEnumeration)
588 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
589 size_t length([self count] - state->state);
592 else if (length > count)
594 for (size_t i(0); i != length; ++i)
595 objects[i] = [self objectAtIndex:state->state++];
596 state->itemsPtr = objects;
597 state->mutationsPtr = (unsigned long *) self;
603 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
604 size_t length([self length] - state->state);
607 else if (length > count)
609 for (size_t i(0); i != length; ++i)
610 objects[i] = [self item:state->state++];
611 state->itemsPtr = objects;
612 state->mutationsPtr = (unsigned long *) self;
616 /* Cydia NSString Additions {{{ */
617 @interface NSString (Cydia)
618 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
619 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
620 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
621 - (NSComparisonResult) compareByPath:(NSString *)other;
622 - (NSString *) stringByCachingURLWithCurrentCDN;
623 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
626 @implementation NSString (Cydia)
628 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
629 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
632 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
633 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
634 memcpy(data, bytes, length);
635 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
638 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
639 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
642 - (NSComparisonResult) compareByPath:(NSString *)other {
643 NSString *prefix = [self commonPrefixWithString:other options:0];
644 size_t length = [prefix length];
646 NSRange lrange = NSMakeRange(length, [self length] - length);
647 NSRange rrange = NSMakeRange(length, [other length] - length);
649 lrange = [self rangeOfString:@"/" options:0 range:lrange];
650 rrange = [other rangeOfString:@"/" options:0 range:rrange];
652 NSComparisonResult value;
654 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
655 value = NSOrderedSame;
656 else if (lrange.location == NSNotFound)
657 value = NSOrderedAscending;
658 else if (rrange.location == NSNotFound)
659 value = NSOrderedDescending;
661 value = NSOrderedSame;
663 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
664 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
665 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
666 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
668 NSComparisonResult result = [lpath compare:rpath];
669 return result == NSOrderedSame ? value : result;
672 - (NSString *) stringByCachingURLWithCurrentCDN {
674 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
675 withString:@"://cache.cydia.saurik.com/"
679 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
680 return [(id)CFURLCreateStringByAddingPercentEscapes(
685 kCFStringEncodingUTF8
692 /* C++ NSString Wrapper Cache {{{ */
693 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
694 return size == 0 ? NULL :
695 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
696 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
699 static _finline CFStringRef CYStringCreate(const char *data) {
700 return CYStringCreate(data, strlen(data));
709 _finline void clear_() {
710 if (cache_ != NULL) {
717 _finline bool empty() const {
721 _finline size_t size() const {
725 _finline char *data() const {
729 _finline void clear() {
734 _finline CYString() :
741 _finline ~CYString() {
745 void operator =(const CYString &rhs) {
749 if (rhs.cache_ == nil)
752 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
755 void copy(apr_pool_t *pool) {
756 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
757 memcpy(temp, data_, size_);
762 void set(apr_pool_t *pool, const char *data, size_t size) {
768 data_ = const_cast<char *>(data);
776 _finline void set(apr_pool_t *pool, const char *data) {
777 set(pool, data, data == NULL ? 0 : strlen(data));
780 _finline void set(apr_pool_t *pool, const std::string &rhs) {
781 set(pool, rhs.data(), rhs.size());
784 bool operator ==(const CYString &rhs) const {
785 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
788 _finline operator CFStringRef() {
790 cache_ = CYStringCreate(data_, size_);
794 _finline operator id() {
795 return (NSString *) static_cast<CFStringRef>(*this);
798 _finline operator const char *() {
799 return reinterpret_cast<const char *>(data_);
803 /* C++ NSString Algorithm Adapters {{{ */
805 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
808 struct NSStringMapHash :
809 std::unary_function<NSString *, size_t>
811 _finline size_t operator ()(NSString *value) const {
812 return CFStringHashNSString((CFStringRef) value);
816 struct NSStringMapLess :
817 std::binary_function<NSString *, NSString *, bool>
819 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
820 return [lhs compare:rhs] == NSOrderedAscending;
824 struct NSStringMapEqual :
825 std::binary_function<NSString *, NSString *, bool>
827 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
828 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
829 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
830 //[lhs isEqualToString:rhs];
835 /* Perl-Compatible RegEx {{{ */
845 Pcre(const char *regex) :
850 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
853 lprintf("%d:%s\n", offset, error);
857 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
858 matches_ = new int[(capture_ + 1) * 3];
866 NSString *operator [](size_t match) {
867 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
870 bool operator ()(NSString *data) {
871 // XXX: length is for characters, not for bytes
872 return operator ()([data UTF8String], [data length]);
875 bool operator ()(const char *data, size_t size) {
877 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
881 /* Mime Addresses {{{ */
882 @interface Address : NSObject {
888 - (NSString *) address;
890 - (void) setAddress:(NSString *)address;
892 + (Address *) addressWithString:(NSString *)string;
893 - (Address *) initWithString:(NSString *)string;
897 @implementation Address
906 - (NSString *) name {
910 - (NSString *) address {
914 - (void) setAddress:(NSString *)address {
916 [address_ autorelease];
920 address_ = [address retain];
923 + (Address *) addressWithString:(NSString *)string {
924 return [[[Address alloc] initWithString:string] autorelease];
927 + (NSArray *) _attributeKeys {
928 return [NSArray arrayWithObjects:
934 - (NSArray *) attributeKeys {
935 return [[self class] _attributeKeys];
938 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
939 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
942 - (Address *) initWithString:(NSString *)string {
943 if ((self = [super init]) != nil) {
944 const char *data = [string UTF8String];
945 size_t size = [string length];
947 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
949 if (address_r(data, size)) {
950 name_ = [address_r[1] retain];
951 address_ = [address_r[2] retain];
953 name_ = [string retain];
961 /* CoreGraphics Primitives {{{ */
966 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
967 CGFloat color[] = {red, green, blue, alpha};
968 return CGColorCreate(space, color);
977 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
978 color_(Create_(space, red, green, blue, alpha))
980 Set(space, red, green, blue, alpha);
985 CGColorRelease(color_);
992 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
994 color_ = Create_(space, red, green, blue, alpha);
997 operator CGColorRef() {
1003 /* Random Global Variables {{{ */
1004 static const int PulseInterval_ = 50000;
1006 static const NSString *UI_;
1009 static bool RestartSubstrate_;
1010 static NSArray *Finishes_;
1012 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1013 #define NotifyConfig_ "/etc/notify.conf"
1015 static bool Queuing_;
1017 static CYColor Blue_;
1018 static CYColor Blueish_;
1019 static CYColor Black_;
1020 static CYColor Off_;
1021 static CYColor White_;
1022 static CYColor Gray_;
1023 static CYColor Green_;
1024 static CYColor Purple_;
1025 static CYColor Purplish_;
1027 static UIColor *InstallingColor_;
1028 static UIColor *RemovingColor_;
1030 static NSString *App_;
1032 static BOOL Advanced_;
1033 static BOOL Ignored_;
1035 static UIFont *Font12_;
1036 static UIFont *Font12Bold_;
1037 static UIFont *Font14_;
1038 static UIFont *Font18Bold_;
1039 static UIFont *Font22Bold_;
1041 static const char *Machine_ = NULL;
1042 static NSString *System_ = nil;
1043 static NSString *SerialNumber_ = nil;
1044 static NSString *ChipID_ = nil;
1045 static _H<NSString> Token_;
1046 static NSString *UniqueID_ = nil;
1047 static NSString *PLMN_ = nil;
1048 static NSString *Build_ = nil;
1049 static NSString *Product_ = nil;
1050 static NSString *Safari_ = nil;
1052 static CFLocaleRef Locale_;
1053 static NSArray *Languages_;
1054 static CGColorSpaceRef space_;
1056 static NSDictionary *SectionMap_;
1057 static NSMutableDictionary *Metadata_;
1058 static _transient NSMutableDictionary *Settings_;
1059 static _transient NSString *Role_;
1060 static _transient NSMutableDictionary *Packages_;
1061 static _transient NSMutableDictionary *Sections_;
1062 static _transient NSMutableDictionary *Sources_;
1063 static bool Changed_;
1067 static CGFloat ScreenScale_;
1068 static NSString *Idiom_;
1071 /* Display Helpers {{{ */
1072 inline float Interpolate(float begin, float end, float fraction) {
1073 return (end - begin) * fraction + begin;
1076 static _finline const char *StripVersion_(const char *version) {
1077 const char *colon(strchr(version, ':'));
1078 return colon == NULL ? version : colon + 1;
1081 NSString *LocalizeSection(NSString *section) {
1082 static Pcre title_r("^(.*?) \\((.*)\\)$");
1083 if (title_r(section)) {
1084 NSString *parent(title_r[1]);
1085 NSString *child(title_r[2]);
1087 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1088 LocalizeSection(parent),
1089 LocalizeSection(child)
1093 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1096 NSString *Simplify(NSString *title) {
1097 const char *data = [title UTF8String];
1098 size_t size = [title length];
1100 static Pcre square_r("^\\[(.*)\\]$");
1101 if (square_r(data, size))
1102 return Simplify(square_r[1]);
1104 static Pcre paren_r("^\\((.*)\\)$");
1105 if (paren_r(data, size))
1106 return Simplify(paren_r[1]);
1108 static Pcre title_r("^(.*?) \\((.*)\\)$");
1109 if (title_r(data, size))
1110 return Simplify(title_r[1]);
1116 NSString *GetLastUpdate() {
1117 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1120 return UCLocalize("NEVER_OR_UNKNOWN");
1122 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1123 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1125 CFRelease(formatter);
1127 return [(NSString *) formatted autorelease];
1130 bool isSectionVisible(NSString *section) {
1131 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1132 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1133 return hidden == nil || ![hidden boolValue];
1138 /* Delegate Prototypes {{{ */
1141 @class CydiaProgressEvent;
1143 @protocol DatabaseDelegate
1144 - (void) repairWithSelector:(SEL)selector;
1145 - (void) setConfigurationData:(NSString *)data;
1146 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
1149 @class CYPackageController;
1151 @protocol CydiaDelegate
1152 - (void) retainNetworkActivityIndicator;
1153 - (void) releaseNetworkActivityIndicator;
1154 - (void) clearPackage:(Package *)package;
1155 - (void) installPackage:(Package *)package;
1156 - (void) installPackages:(NSArray *)packages;
1157 - (void) removePackage:(Package *)package;
1158 - (void) beginUpdate;
1160 - (void) distUpgrade;
1162 - (void) updateData;
1164 - (void) addTrivialSource:(NSString *)href;
1165 - (void) showSettings;
1166 - (UIProgressHUD *) addProgressHUD;
1167 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1168 - (CYViewController *) pageForPackage:(NSString *)name;
1169 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1170 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1174 /* ProgressEvent Interface/Delegate {{{ */
1175 @interface CydiaProgressEvent : NSObject {
1176 _H<NSString> message_;
1180 _H<NSString> package_;
1182 _H<NSString> version_;
1185 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type;
1186 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package;
1187 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item;
1189 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type;
1191 - (NSString *) message;
1192 - (NSString *) type;
1195 - (NSString *) package;
1197 - (NSString *) version;
1199 - (void) setItem:(NSArray *)item;
1200 - (void) setPackage:(NSString *)package;
1201 - (void) setURL:(NSString *)url;
1202 - (void) setVersion:(NSString *)version;
1204 - (NSString *) compound:(NSString *)value;
1205 - (NSString *) compoundMessage;
1206 - (NSString *) compoundTitle;
1210 @protocol ProgressDelegate
1211 - (void) addProgressEvent:(CydiaProgressEvent *)event;
1212 - (void) setProgressPercent:(NSNumber *)percent;
1213 - (void) setProgressStatus:(NSDictionary *)status;
1214 - (void) setProgressCancellable:(NSNumber *)cancellable;
1215 - (bool) isProgressCancelled;
1216 - (void) setTitle:(NSString *)title;
1219 /* Status Delegation {{{ */
1221 public pkgAcquireStatus
1224 _transient NSObject<ProgressDelegate> *delegate_;
1234 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1235 delegate_ = delegate;
1238 NSObject<ProgressDelegate> *getDelegate() const {
1242 virtual bool MediaChange(std::string media, std::string drive) {
1246 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1249 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1250 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1251 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:@"STATUS" forItem:item]);
1252 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1255 virtual void Done(pkgAcquire::ItemDesc &item) {
1258 virtual void Fail(pkgAcquire::ItemDesc &item) {
1260 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1261 item.Owner->Status == pkgAcquire::Item::StatDone
1265 std::string &error(item.Owner->ErrorText);
1269 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:@"ERROR" forItem:item]);
1270 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1273 virtual bool Pulse(pkgAcquire *Owner) {
1274 bool value = pkgAcquireStatus::Pulse(Owner);
1277 double(CurrentBytes + CurrentItems) /
1278 double(TotalBytes + TotalItems)
1281 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1282 [NSNumber numberWithDouble:percent], @"Percent",
1284 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1285 [NSNumber numberWithDouble:TotalBytes], @"Total",
1286 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1287 nil] waitUntilDone:YES];
1289 if (value && ![delegate_ isProgressCancelled])
1297 _finline bool WasCancelled() const {
1301 virtual void Start() {
1302 pkgAcquireStatus::Start();
1303 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1306 virtual void Stop() {
1307 pkgAcquireStatus::Stop();
1308 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1309 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1313 /* Database Interface {{{ */
1314 typedef std::map< unsigned long, _H<Source> > SourceMap;
1316 @interface Database : NSObject {
1322 pkgCacheFile cache_;
1323 pkgDepCache::Policy *policy_;
1324 pkgRecords *records_;
1325 pkgProblemResolver *resolver_;
1326 pkgAcquire *fetcher_;
1328 SPtr<pkgPackageManager> manager_;
1329 pkgSourceList *list_;
1331 SourceMap sourceMap_;
1332 NSMutableArray *sourceList_;
1334 CFMutableArrayRef packages_;
1336 _transient NSObject<DatabaseDelegate> *delegate_;
1337 _transient NSObject<ProgressDelegate> *progress_;
1345 std::map<const char *, _H<NSString> > sections_;
1348 + (Database *) sharedInstance;
1351 - (void) _readCydia:(NSNumber *)fd;
1352 - (void) _readStatus:(NSNumber *)fd;
1353 - (void) _readOutput:(NSNumber *)fd;
1357 - (Package *) packageWithName:(NSString *)name;
1359 - (pkgCacheFile &) cache;
1360 - (pkgDepCache::Policy *) policy;
1361 - (pkgRecords *) records;
1362 - (pkgProblemResolver *) resolver;
1363 - (pkgAcquire &) fetcher;
1364 - (pkgSourceList &) list;
1365 - (NSArray *) packages;
1366 - (NSArray *) sources;
1367 - (Source *) sourceWithKey:(NSString *)key;
1368 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1376 - (void) updateWithStatus:(Status &)status;
1378 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1380 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1381 - (NSObject<ProgressDelegate> *) progressDelegate;
1383 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1385 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1389 /* ProgressEvent Implementation {{{ */
1390 @implementation CydiaProgressEvent
1392 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1393 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1396 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1397 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1398 [event setPackage:package];
1402 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1403 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1405 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1406 NSArray *fields([description componentsSeparatedByString:@" "]);
1407 [event setItem:fields];
1409 if ([fields count] > 3) {
1410 [event setPackage:[fields objectAtIndex:2]];
1411 [event setVersion:[fields objectAtIndex:3]];
1414 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1419 + (NSArray *) _attributeKeys {
1420 return [NSArray arrayWithObjects:
1430 - (NSArray *) attributeKeys {
1431 return [[self class] _attributeKeys];
1434 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1435 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1438 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1439 if ((self = [super init]) != nil) {
1445 - (NSString *) message {
1449 - (NSString *) type {
1453 - (NSArray *) item {
1454 return (id) item_ ?: [NSNull null];
1457 - (void) setItem:(NSArray *)item {
1461 - (NSString *) package {
1462 return (id) package_ ?: [NSNull null];
1465 - (void) setPackage:(NSString *)package {
1469 - (NSString *) url {
1470 return (id) url_ ?: [NSNull null];
1473 - (void) setURL:(NSString *)url {
1477 - (void) setVersion:(NSString *)version {
1481 - (NSString *) version {
1482 return (id) version_ ?: [NSNull null];
1485 - (NSString *) compound:(NSString *)value {
1487 NSString *mode(nil); {
1488 NSString *type([self type]);
1489 if ([type isEqualToString:@"ERROR"])
1490 mode = UCLocalize("ERROR");
1491 else if ([type isEqualToString:@"WARNING"])
1492 mode = UCLocalize("WARNING");
1496 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1502 - (NSString *) compoundMessage {
1503 return [self compound:[self message]];
1506 - (NSString *) compoundTitle {
1509 if (package_ == nil)
1511 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1512 title = [package name];
1516 return [self compound:title];
1522 // Cytore Definitions {{{
1523 struct PackageValue :
1526 Cytore::Offset<PackageValue> next_;
1528 uint32_t index_ : 23;
1529 uint32_t subscribed_ : 1;
1546 Cytore::Offset<PackageValue> packages_[1 << 16];
1549 static Cytore::File<MetaValue> MetaFile_;
1551 // Cytore Helper Functions {{{
1552 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1553 SplitHash nhash = { hashlittle(name, length) };
1555 PackageValue *metadata;
1557 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1558 offset: if (offset->IsNull()) {
1559 *offset = MetaFile_.New<PackageValue>(length + 1);
1560 metadata = &MetaFile_.Get(*offset);
1562 if (metadata == NULL) {
1566 metadata = new PackageValue();
1567 memset(metadata, 0, sizeof(*metadata));
1570 memcpy(metadata->name_, name, length + 1);
1571 metadata->nhash_ = nhash.u16[1];
1573 metadata = &MetaFile_.Get(*offset);
1575 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1576 offset = &metadata->next_;
1584 static void PackageImport(const void *key, const void *value, void *context) {
1585 bool &fail(*reinterpret_cast<bool *>(context));
1588 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1589 NSLog(@"failed to import package %@", key);
1593 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1594 NSDictionary *package((NSDictionary *) value);
1596 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1597 if ([subscribed boolValue] && !metadata->subscribed_)
1598 metadata->subscribed_ = true;
1600 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1601 time_t time([date timeIntervalSince1970]);
1602 if (metadata->first_ > time || metadata->first_ == 0)
1603 metadata->first_ = time;
1606 NSDate *date([package objectForKey:@"LastSeen"]);
1607 NSString *version([package objectForKey:@"LastVersion"]);
1609 if (date != nil && version != nil) {
1610 time_t time([date timeIntervalSince1970]);
1611 if (metadata->last_ < time || metadata->last_ == 0)
1612 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1613 size_t length(strlen(buffer));
1614 uint16_t vhash(hashlittle(buffer, length));
1616 size_t capped(std::min<size_t>(8, length));
1617 char *latest(buffer + length - capped);
1619 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1620 metadata->vhash_ = vhash;
1622 metadata->last_ = time;
1628 /* Source Class {{{ */
1629 @interface Source : NSObject {
1630 CYString depiction_;
1631 CYString description_;
1637 CYString distribution_;
1642 _H<NSString> authority_;
1644 CYString defaultIcon_;
1646 _H<NSDictionary> record_;
1650 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1652 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1654 - (NSString *) depictionForPackage:(NSString *)package;
1655 - (NSString *) supportForPackage:(NSString *)package;
1657 - (NSDictionary *) record;
1661 - (NSString *) distribution;
1662 - (NSString *) type;
1664 - (NSString *) host;
1666 - (NSString *) name;
1667 - (NSString *) description;
1668 - (NSString *) label;
1669 - (NSString *) origin;
1670 - (NSString *) version;
1672 - (NSString *) defaultIcon;
1676 @implementation Source
1680 distribution_.clear();
1683 description_.clear();
1689 defaultIcon_.clear();
1697 // XXX: this is a very inefficient way to call these deconstructors
1702 + (NSArray *) _attributeKeys {
1703 return [NSArray arrayWithObjects:
1718 - (NSArray *) attributeKeys {
1719 return [[self class] _attributeKeys];
1722 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1723 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1726 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1729 trusted_ = index->IsTrusted();
1731 uri_.set(pool, index->GetURI());
1732 distribution_.set(pool, index->GetDist());
1733 type_.set(pool, index->GetType());
1735 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1736 if (dindex != NULL) {
1738 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1741 pkgTagFile tags(&fd);
1743 pkgTagSection section;
1750 {"default-icon", &defaultIcon_},
1751 {"depiction", &depiction_},
1752 {"description", &description_},
1754 {"origin", &origin_},
1755 {"support", &support_},
1756 {"version", &version_},
1759 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1760 const char *start, *end;
1762 if (section.Find(names[i].name_, start, end)) {
1763 CYString &value(*names[i].value_);
1764 value.set(pool, start, end - start);
1770 record_ = [Sources_ objectForKey:[self key]];
1772 NSURL *url([NSURL URLWithString:uri_]);
1776 host_ = [host_ lowercaseString];
1779 // XXX: this is due to a bug in _H<>
1780 authority_ = (id) host_;
1782 authority_ = [url path];
1785 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1786 if ((self = [super init]) != nil) {
1787 [self setMetaIndex:index inPool:pool];
1791 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1792 NSDictionary *lhr = [self record];
1793 NSDictionary *rhr = [source record];
1796 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1798 NSString *lhs = [self name];
1799 NSString *rhs = [source name];
1801 if ([lhs length] != 0 && [rhs length] != 0) {
1802 unichar lhc = [lhs characterAtIndex:0];
1803 unichar rhc = [rhs characterAtIndex:0];
1805 if (isalpha(lhc) && !isalpha(rhc))
1806 return NSOrderedAscending;
1807 else if (!isalpha(lhc) && isalpha(rhc))
1808 return NSOrderedDescending;
1811 return [lhs compare:rhs options:LaxCompareOptions_];
1814 - (NSString *) depictionForPackage:(NSString *)package {
1815 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1818 - (NSString *) supportForPackage:(NSString *)package {
1819 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1822 - (NSDictionary *) record {
1830 - (NSString *) uri {
1834 - (NSString *) distribution {
1835 return distribution_;
1838 - (NSString *) type {
1842 - (NSString *) key {
1843 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1846 - (NSString *) host {
1850 - (NSString *) name {
1851 return origin_.empty() ? (id) authority_ : origin_;
1854 - (NSString *) description {
1855 return description_;
1858 - (NSString *) label {
1859 return label_.empty() ? (id) authority_ : label_;
1862 - (NSString *) origin {
1866 - (NSString *) version {
1870 - (NSString *) defaultIcon {
1871 return defaultIcon_;
1876 /* CydiaOperation Class {{{ */
1877 @interface CydiaOperation : NSObject {
1878 NSString *operator_;
1882 - (NSString *) operator;
1883 - (NSString *) value;
1887 @implementation CydiaOperation
1890 [operator_ release];
1895 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1896 if ((self = [super init]) != nil) {
1897 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1898 value_ = [[NSString alloc] initWithUTF8String:value];
1902 + (NSArray *) _attributeKeys {
1903 return [NSArray arrayWithObjects:
1909 - (NSArray *) attributeKeys {
1910 return [[self class] _attributeKeys];
1913 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1914 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1917 - (NSString *) operator {
1921 - (NSString *) value {
1927 /* CydiaClause Class {{{ */
1928 @interface CydiaClause : NSObject {
1930 CydiaOperation *version_;
1933 - (NSString *) package;
1934 - (CydiaOperation *) version;
1938 @implementation CydiaClause
1946 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1947 if ((self = [super init]) != nil) {
1948 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1950 if (const char *version = dep.TargetVer())
1951 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1953 version_ = [[NSNull null] retain];
1957 + (NSArray *) _attributeKeys {
1958 return [NSArray arrayWithObjects:
1964 - (NSArray *) attributeKeys {
1965 return [[self class] _attributeKeys];
1968 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1969 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1972 - (NSString *) package {
1976 - (CydiaOperation *) version {
1982 /* CydiaRelation Class {{{ */
1983 @interface CydiaRelation : NSObject {
1984 NSString *relationship_;
1985 NSMutableArray *clauses_;
1988 - (NSString *) relationship;
1989 - (NSArray *) clauses;
1993 @implementation CydiaRelation
1996 [relationship_ release];
2001 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2002 if ((self = [super init]) != nil) {
2003 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
2004 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
2006 pkgCache::DepIterator start;
2007 pkgCache::DepIterator end;
2008 dep.GlobOr(start, end); // ++dep
2011 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2013 // yes, seriously. (wtf?)
2021 + (NSArray *) _attributeKeys {
2022 return [NSArray arrayWithObjects:
2028 - (NSArray *) attributeKeys {
2029 return [[self class] _attributeKeys];
2032 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2033 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2036 - (NSString *) relationship {
2037 return relationship_;
2040 - (NSArray *) clauses {
2044 - (void) addClause:(CydiaClause *)clause {
2045 [clauses_ addObject:clause];
2050 /* Package Class {{{ */
2051 struct ParsedPackage {
2056 CYString depiction_;
2066 @interface Package : NSObject {
2069 uint32_t essential_ : 1;
2070 uint32_t obsolete_ : 1;
2071 uint32_t ignored_ : 1;
2075 _transient Database *database_;
2077 pkgCache::VerIterator version_;
2078 pkgCache::PkgIterator iterator_;
2079 pkgCache::VerFileIterator file_;
2085 CYString installed_;
2087 const char *section_;
2088 _transient NSString *section$_;
2092 PackageValue *metadata_;
2093 ParsedPackage *parsed_;
2095 NSMutableArray *tags_;
2098 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2099 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2101 - (pkgCache::PkgIterator) iterator;
2104 - (NSString *) section;
2105 - (NSString *) simpleSection;
2107 - (NSString *) longSection;
2108 - (NSString *) shortSection;
2112 - (Address *) maintainer;
2114 - (NSString *) longDescription;
2115 - (NSString *) shortDescription;
2118 - (PackageValue *) metadata;
2121 - (bool) subscribed;
2122 - (bool) setSubscribed:(bool)subscribed;
2126 - (NSString *) latest;
2127 - (NSString *) installed;
2128 - (BOOL) uninstalled;
2131 - (BOOL) upgradableAndEssential:(BOOL)essential;
2134 - (BOOL) unfiltered;
2138 - (BOOL) halfConfigured;
2139 - (BOOL) halfInstalled;
2141 - (NSString *) mode;
2144 - (NSString *) name;
2146 - (NSString *) homepage;
2147 - (NSString *) depiction;
2148 - (Address *) author;
2150 - (NSString *) support;
2152 - (NSArray *) files;
2153 - (NSArray *) warnings;
2154 - (NSArray *) applications;
2156 - (Source *) source;
2158 - (BOOL) matches:(NSString *)text;
2160 - (bool) hasSupportingRole;
2161 - (BOOL) hasTag:(NSString *)tag;
2162 - (NSString *) primaryPurpose;
2163 - (NSArray *) purposes;
2164 - (bool) isCommercial;
2166 - (void) setIndex:(size_t)index;
2168 - (CYString &) cyname;
2170 - (uint32_t) compareBySection:(NSArray *)sections;
2175 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2176 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2177 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2178 - (bool) isVisibleInSection:(NSString *)section;
2179 - (bool) isVisibleInSource:(Source *)source;
2183 uint32_t PackageChangesRadix(Package *self, void *) {
2188 uint32_t timestamp : 30;
2189 uint32_t ignored : 1;
2190 uint32_t upgradable : 1;
2194 bool upgradable([self upgradableAndEssential:YES]);
2195 value.bits.upgradable = upgradable ? 1 : 0;
2198 value.bits.timestamp = 0;
2199 value.bits.ignored = [self ignored] ? 0 : 1;
2200 value.bits.upgradable = 1;
2202 value.bits.timestamp = [self seen] >> 2;
2203 value.bits.ignored = 0;
2204 value.bits.upgradable = 0;
2207 return _not(uint32_t) - value.key;
2210 uint32_t PackagePrefixRadix(Package *self, void *context) {
2211 size_t offset(reinterpret_cast<size_t>(context));
2212 CYString &name([self cyname]);
2214 size_t size(name.size());
2217 char *text(name.data());
2220 if (!isdigit(text[0]))
2224 while (size != digits && isdigit(text[digits]))
2232 if (offset == 0 && zeros != 0) {
2233 memset(data, '0', zeros);
2234 memcpy(data + zeros, text, 4 - zeros);
2236 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2237 if (size <= offset - zeros)
2240 text += offset - zeros;
2241 size -= offset - zeros;
2244 memcpy(data, text, 4);
2246 memcpy(data, text, size);
2247 memset(data + size, 0, 4 - size);
2250 for (size_t i(0); i != 4; ++i)
2251 if (isalpha(data[i]))
2259 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2261 /* XXX: ntohl may be more honest */
2262 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2265 CYString &(*PackageName)(Package *self, SEL sel);
2267 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2268 _profile(PackageNameCompare)
2269 CYString &lhi(PackageName(lhs, @selector(cyname)));
2270 CYString &rhi(PackageName(rhs, @selector(cyname)));
2271 CFStringRef lhn(lhi), rhn(rhi);
2274 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2275 else if (rhn == NULL)
2276 return NSOrderedDescending;
2278 _profile(PackageNameCompare$NumbersLast)
2279 if (!lhi.empty() && !rhi.empty()) {
2280 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2281 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2282 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2283 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2284 return lha ? NSOrderedAscending : NSOrderedDescending;
2288 CFIndex length = CFStringGetLength(lhn);
2290 _profile(PackageNameCompare$Compare)
2291 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2296 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2297 return PackageNameCompare(*lhs, *rhs, context);
2300 struct PackageNameOrdering :
2301 std::binary_function<Package *, Package *, bool>
2303 _finline bool operator ()(Package *lhs, Package *rhs) const {
2304 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2308 @implementation Package
2310 - (NSString *) description {
2311 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2315 if (parsed_ != NULL)
2324 + (NSString *) webScriptNameForSelector:(SEL)selector {
2326 else if (selector == @selector(clear))
2328 else if (selector == @selector(getField:))
2330 else if (selector == @selector(hasTag:))
2332 else if (selector == @selector(install))
2334 else if (selector == @selector(remove))
2340 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2341 return [self webScriptNameForSelector:selector] == nil;
2344 + (NSArray *) _attributeKeys {
2345 return [NSArray arrayWithObjects:
2363 @"shortDescription",
2375 - (NSArray *) attributeKeys {
2376 return [[self class] _attributeKeys];
2379 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2380 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2383 - (NSArray *) relations {
2384 @synchronized (database_) {
2385 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2386 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2387 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2391 - (NSString *) getField:(NSString *)name {
2392 @synchronized (database_) {
2393 if ([database_ era] != era_ || file_.end())
2396 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2398 const char *start, *end;
2399 if (!parser.Find([name UTF8String], start, end))
2400 return (NSString *) [NSNull null];
2402 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2406 if (parsed_ != NULL)
2408 @synchronized (database_) {
2409 if ([database_ era] != era_ || file_.end())
2412 ParsedPackage *parsed(new ParsedPackage);
2415 _profile(Package$parse)
2416 pkgRecords::Parser *parser;
2418 _profile(Package$parse$Lookup)
2419 parser = &[database_ records]->Lookup(file_);
2424 _profile(Package$parse$Find)
2429 {"icon", &parsed->icon_},
2430 {"depiction", &parsed->depiction_},
2431 {"homepage", &parsed->homepage_},
2432 {"website", &website},
2433 {"bugs", &parsed->bugs_},
2434 {"support", &parsed->support_},
2435 {"sponsor", &parsed->sponsor_},
2436 {"author", &parsed->author_},
2439 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2440 const char *start, *end;
2442 if (parser->Find(names[i].name_, start, end)) {
2443 CYString &value(*names[i].value_);
2444 _profile(Package$parse$Value)
2445 value.set(pool_, start, end - start);
2451 _profile(Package$parse$Tagline)
2452 const char *start, *end;
2453 if (parser->ShortDesc(start, end)) {
2454 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2457 while (stop != start && stop[-1] == '\r')
2459 parsed->tagline_.set(pool_, start, stop - start);
2463 _profile(Package$parse$Retain)
2464 if (parsed->homepage_.empty())
2465 parsed->homepage_ = website;
2466 if (parsed->homepage_ == parsed->depiction_)
2467 parsed->homepage_.clear();
2472 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2473 if ((self = [super init]) != nil) {
2474 _profile(Package$initWithVersion)
2477 database_ = database;
2478 era_ = [database era];
2482 pkgCache::PkgIterator iterator(version.ParentPkg());
2483 iterator_ = iterator;
2485 _profile(Package$initWithVersion$Version)
2486 if (!version_.end())
2487 file_ = version_.FileList();
2489 pkgCache &cache([database_ cache]);
2490 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2494 _profile(Package$initWithVersion$Cache)
2495 name_.set(NULL, iterator.Display());
2497 latest_.set(NULL, StripVersion_(version_.VerStr()));
2499 pkgCache::VerIterator current(iterator.CurrentVer());
2501 installed_.set(NULL, StripVersion_(current.VerStr()));
2504 _profile(Package$initWithVersion$Tags)
2505 pkgCache::TagIterator tag(iterator.TagList());
2507 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2509 const char *name(tag.Name());
2510 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2512 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2513 if (strcmp(name + 6, "enduser") == 0)
2515 else if (strcmp(name + 6, "hacker") == 0)
2517 else if (strcmp(name + 6, "developer") == 0)
2519 else if (strcmp(name + 6, "cydia") == 0)
2525 if (strncmp(name, "cydia::", 7) == 0) {
2526 if (strcmp(name + 7, "essential") == 0)
2528 else if (strcmp(name + 7, "obsolete") == 0)
2533 } while (!tag.end());
2537 _profile(Package$initWithVersion$Metadata)
2538 const char *mixed(iterator.Name());
2539 size_t size(strlen(mixed));
2540 char lower[size + 1];
2542 for (size_t i(0); i != size; ++i)
2543 lower[i] = mixed[i] | 0x20;
2546 PackageValue *metadata(PackageFind(lower, size));
2547 metadata_ = metadata;
2549 id_.set(NULL, metadata->name_, size);
2551 const char *latest(version_.VerStr());
2552 size_t length(strlen(latest));
2554 uint16_t vhash(hashlittle(latest, length));
2556 size_t capped(std::min<size_t>(8, length));
2557 latest = latest + length - capped;
2559 if (metadata->first_ == 0)
2560 metadata->first_ = now_;
2562 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2563 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2564 metadata->vhash_ = vhash;
2565 metadata->last_ = now_;
2566 } else if (metadata->last_ == 0)
2567 metadata->last_ = metadata->first_;
2570 _profile(Package$initWithVersion$Section)
2571 section_ = iterator.Section();
2574 _profile(Package$initWithVersion$Flags)
2575 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2576 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2581 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2582 pkgCache::VerIterator version;
2584 _profile(Package$packageWithIterator$GetCandidateVer)
2585 version = [database policy]->GetCandidateVer(iterator);
2593 _profile(Package$packageWithIterator$Allocate)
2594 package = [Package allocWithZone:zone];
2597 _profile(Package$packageWithIterator$Initialize)
2599 initWithVersion:version
2606 _profile(Package$packageWithIterator$Autorelease)
2607 package = [package autorelease];
2613 - (pkgCache::PkgIterator) iterator {
2617 - (NSString *) section {
2618 if (section$_ == nil) {
2619 if (section_ == NULL)
2622 _profile(Package$section$mappedSectionForPointer)
2623 section$_ = [database_ mappedSectionForPointer:section_];
2628 - (NSString *) simpleSection {
2629 if (NSString *section = [self section])
2630 return Simplify(section);
2635 - (NSString *) longSection {
2636 return LocalizeSection([self section]);
2639 - (NSString *) shortSection {
2640 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2643 - (NSString *) uri {
2646 pkgIndexFile *index;
2647 pkgCache::PkgFileIterator file(file_.File());
2648 if (![database_ list].FindIndex(file, index))
2650 return [NSString stringWithUTF8String:iterator_->Path];
2651 //return [NSString stringWithUTF8String:file.Site()];
2652 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2656 - (Address *) maintainer {
2657 @synchronized (database_) {
2658 if ([database_ era] != era_ || file_.end())
2661 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2662 const std::string &maintainer(parser->Maintainer());
2663 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2667 @synchronized (database_) {
2668 if ([database_ era] != era_ || version_.end())
2671 return version_->InstalledSize;
2674 - (NSString *) longDescription {
2675 @synchronized (database_) {
2676 if ([database_ era] != era_ || file_.end())
2679 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2680 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2682 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2683 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2684 if ([lines count] < 2)
2687 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2688 for (size_t i(1), e([lines count]); i != e; ++i) {
2689 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2690 [trimmed addObject:trim];
2693 return [trimmed componentsJoinedByString:@"\n"];
2696 - (NSString *) shortDescription {
2697 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2701 _profile(Package$index)
2702 CFStringRef name((CFStringRef) [self name]);
2703 if (CFStringGetLength(name) == 0)
2705 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2706 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2708 return toupper(character);
2712 - (PackageValue *) metadata {
2717 PackageValue *metadata([self metadata]);
2718 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2721 - (bool) subscribed {
2722 return [self metadata]->subscribed_;
2725 - (bool) setSubscribed:(bool)subscribed {
2726 PackageValue *metadata([self metadata]);
2727 if (metadata->subscribed_ == subscribed)
2729 metadata->subscribed_ = subscribed;
2737 - (NSString *) latest {
2741 - (NSString *) installed {
2745 - (BOOL) uninstalled {
2746 return installed_.empty();
2750 return !version_.end();
2753 - (BOOL) upgradableAndEssential:(BOOL)essential {
2754 _profile(Package$upgradableAndEssential)
2755 pkgCache::VerIterator current(iterator_.CurrentVer());
2757 return essential && essential_;
2759 return !version_.end() && version_ != current;
2763 - (BOOL) essential {
2768 return [database_ cache][iterator_].InstBroken();
2771 - (BOOL) unfiltered {
2772 _profile(Package$unfiltered$obsolete)
2773 if (_unlikely(obsolete_))
2777 _profile(Package$unfiltered$hasSupportingRole)
2778 if (_unlikely(![self hasSupportingRole]))
2786 if (![self unfiltered])
2791 _profile(Package$visible$section)
2792 section = [self section];
2795 _profile(Package$visible$isSectionVisible)
2796 if (!isSectionVisible(section))
2804 unsigned char current(iterator_->CurrentState);
2805 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2808 - (BOOL) halfConfigured {
2809 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2812 - (BOOL) halfInstalled {
2813 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2817 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2818 return state.Mode != pkgDepCache::ModeKeep;
2821 - (NSString *) mode {
2822 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2824 switch (state.Mode) {
2825 case pkgDepCache::ModeDelete:
2826 if ((state.iFlags & pkgDepCache::Purge) != 0)
2830 case pkgDepCache::ModeKeep:
2831 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2832 return @"REINSTALL";
2833 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2837 case pkgDepCache::ModeInstall:
2838 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2839 return @"REINSTALL";
2840 else*/ switch (state.Status) {
2842 return @"DOWNGRADE";
2848 return @"NEW_INSTALL";
2859 - (NSString *) name {
2860 return name_.empty() ? id_ : name_;
2863 - (UIImage *) icon {
2864 NSString *section = [self simpleSection];
2867 if (parsed_ != NULL)
2868 if (NSString *href = parsed_->icon_)
2869 if ([href hasPrefix:@"file:///"])
2870 // XXX: correct escaping
2871 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2872 if (icon == nil) if (section != nil)
2873 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2874 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2875 if ([dicon hasPrefix:@"file:///"])
2876 // XXX: correct escaping
2877 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2879 icon = [UIImage applicationImageNamed:@"unknown.png"];
2883 - (NSString *) homepage {
2884 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2887 - (NSString *) depiction {
2888 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2891 - (Address *) sponsor {
2892 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2895 - (Address *) author {
2896 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2899 - (NSString *) support {
2900 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2903 - (NSArray *) files {
2904 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2905 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2908 fin.open([path UTF8String]);
2913 while (std::getline(fin, line))
2914 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2919 - (NSArray *) warnings {
2920 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2921 const char *name(iterator_.Name());
2923 size_t length(strlen(name));
2924 if (length < 2) invalid:
2925 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2926 else for (size_t i(0); i != length; ++i)
2928 /* XXX: technically this is not allowed */
2929 (name[i] < 'A' || name[i] > 'Z') &&
2930 (name[i] < 'a' || name[i] > 'z') &&
2931 (name[i] < '0' || name[i] > '9') &&
2932 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2935 if (strcmp(name, "cydia") != 0) {
2938 bool _private = false;
2941 bool repository = [[self section] isEqualToString:@"Repositories"];
2943 if (NSArray *files = [self files])
2944 for (NSString *file in files)
2945 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2947 else if (!user && [file isEqualToString:@"/User"])
2949 else if (!_private && [file isEqualToString:@"/private"])
2951 else if (!stash && [file isEqualToString:@"/var/stash"])
2954 /* XXX: this is not sensitive enough. only some folders are valid. */
2955 if (cydia && !repository)
2956 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2958 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2960 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2962 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2965 return [warnings count] == 0 ? nil : warnings;
2968 - (NSArray *) applications {
2969 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2971 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2973 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2974 if (NSArray *files = [self files])
2975 for (NSString *file in files)
2976 if (application_r(file)) {
2977 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2978 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2979 if ([id isEqualToString:me])
2982 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2984 display = application_r[1];
2986 NSString *bundle([file stringByDeletingLastPathComponent]);
2987 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2988 if (icon == nil || [icon length] == 0)
2990 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2992 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2993 [applications addObject:application];
2995 [application addObject:id];
2996 [application addObject:display];
2997 [application addObject:url];
3000 return [applications count] == 0 ? nil : applications;
3003 - (Source *) source {
3004 if (source_ == nil) {
3005 @synchronized (database_) {
3006 if ([database_ era] != era_ || file_.end())
3007 source_ = (Source *) [NSNull null];
3009 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
3013 return source_ == (Source *) [NSNull null] ? nil : source_;
3016 - (BOOL) matches:(NSString *)text {
3022 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
3023 if (range.location != NSNotFound)
3026 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
3027 if (range.location != NSNotFound)
3032 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
3033 if (range.location != NSNotFound)
3039 - (bool) hasSupportingRole {
3044 if ([Role_ isEqualToString:@"User"])
3048 if ([Role_ isEqualToString:@"Hacker"])
3052 if ([Role_ isEqualToString:@"Developer"])
3057 - (NSArray *) tags {
3061 - (BOOL) hasTag:(NSString *)tag {
3062 return tags_ == nil ? NO : [tags_ containsObject:tag];
3065 - (NSString *) primaryPurpose {
3066 for (NSString *tag in tags_)
3067 if ([tag hasPrefix:@"purpose::"])
3068 return [tag substringFromIndex:9];
3072 - (NSArray *) purposes {
3073 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3074 for (NSString *tag in tags_)
3075 if ([tag hasPrefix:@"purpose::"])
3076 [purposes addObject:[tag substringFromIndex:9]];
3077 return [purposes count] == 0 ? nil : purposes;
3080 - (bool) isCommercial {
3081 return [self hasTag:@"cydia::commercial"];
3084 - (void) setIndex:(size_t)index {
3085 if (metadata_->index_ != index)
3086 metadata_->index_ = index;
3089 - (CYString &) cyname {
3090 return name_.empty() ? id_ : name_;
3093 - (uint32_t) compareBySection:(NSArray *)sections {
3094 NSString *section([self section]);
3095 for (size_t i(0), e([sections count]); i != e; ++i) {
3096 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3100 return _not(uint32_t);
3104 @synchronized (database_) {
3105 pkgProblemResolver *resolver = [database_ resolver];
3106 resolver->Clear(iterator_);
3108 pkgCacheFile &cache([database_ cache]);
3109 cache->SetReInstall(iterator_, false);
3110 cache->MarkKeep(iterator_, false);
3114 @synchronized (database_) {
3115 pkgProblemResolver *resolver = [database_ resolver];
3116 resolver->Clear(iterator_);
3117 resolver->Protect(iterator_);
3119 pkgCacheFile &cache([database_ cache]);
3120 cache->SetReInstall(iterator_, false);
3121 cache->MarkInstall(iterator_, false);
3123 pkgDepCache::StateCache &state((*cache)[iterator_]);
3124 if (!state.Install())
3125 cache->SetReInstall(iterator_, true);
3129 @synchronized (database_) {
3130 pkgProblemResolver *resolver = [database_ resolver];
3131 resolver->Clear(iterator_);
3132 resolver->Remove(iterator_);
3133 resolver->Protect(iterator_);
3135 pkgCacheFile &cache([database_ cache]);
3136 cache->SetReInstall(iterator_, false);
3137 cache->MarkDelete(iterator_, true);
3140 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3141 _profile(Package$isUnfilteredAndSearchedForBy)
3144 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3145 value &= [self unfiltered];
3148 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3149 value &= [self matches:search];
3156 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3157 if ([search length] == 0)
3160 _profile(Package$isUnfilteredAndSelectedForBy)
3163 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3164 value &= [self unfiltered];
3167 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3168 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3175 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3176 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3179 - (bool) isVisibleInSection:(NSString *)name {
3180 NSString *section([self section]);
3184 section == nil && [name length] == 0 ||
3185 [name isEqualToString:section]
3186 ) && [self visible];
3189 - (bool) isVisibleInSource:(Source *)source {
3190 return [self source] == source && [self visible];
3195 /* Section Class {{{ */
3196 @interface Section : NSObject {
3201 NSString *localized_;
3204 - (NSComparisonResult) compareByLocalized:(Section *)section;
3205 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3206 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3207 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3208 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3209 - (NSString *) name;
3216 - (void) addToCount;
3218 - (void) setCount:(size_t)count;
3219 - (NSString *) localized;
3223 @implementation Section
3227 if (localized_ != nil)
3228 [localized_ release];
3232 - (NSComparisonResult) compareByLocalized:(Section *)section {
3233 NSString *lhs(localized_);
3234 NSString *rhs([section localized]);
3236 /*if ([lhs length] != 0 && [rhs length] != 0) {
3237 unichar lhc = [lhs characterAtIndex:0];
3238 unichar rhc = [rhs characterAtIndex:0];
3240 if (isalpha(lhc) && !isalpha(rhc))
3241 return NSOrderedAscending;
3242 else if (!isalpha(lhc) && isalpha(rhc))
3243 return NSOrderedDescending;
3246 return [lhs compare:rhs options:LaxCompareOptions_];
3249 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3250 if ((self = [self initWithName:name localize:NO]) != nil) {
3251 if (localized != nil)
3252 localized_ = [localized retain];
3256 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3257 return [self initWithName:name row:0 localize:localize];
3260 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3261 if ((self = [super init]) != nil) {
3262 name_ = [name retain];
3266 localized_ = [LocalizeSection(name_) retain];
3270 /* XXX: localize the index thingees */
3271 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3272 if ((self = [super init]) != nil) {
3273 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3279 - (NSString *) name {
3299 - (void) addToCount {
3303 - (void) setCount:(size_t)count {
3307 - (NSString *) localized {
3314 static NSString *Colon_;
3315 static NSString *Elision_;
3316 static NSString *Error_;
3317 static NSString *Warning_;
3319 /* Database Implementation {{{ */
3320 @implementation Database
3322 + (Database *) sharedInstance {
3323 static Database *instance;
3324 if (instance == nil)
3325 instance = [[Database alloc] init];
3333 - (void) releasePackages {
3334 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3335 CFArrayRemoveAllValues(packages_);
3339 // XXX: actually implement this thing
3341 [sourceList_ release];
3342 [self releasePackages];
3343 apr_pool_destroy(pool_);
3344 NSRecycleZone(zone_);
3348 - (void) _readCydia:(NSNumber *)fd { _pooled
3349 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3350 std::istream is(&ib);
3353 static Pcre finish_r("^finish:([^:]*)$");
3355 while (std::getline(is, line)) {
3356 const char *data(line.c_str());
3357 size_t size = line.size();
3358 lprintf("C:%s\n", data);
3360 if (finish_r(data, size)) {
3361 NSString *finish = finish_r[1];
3362 int index = [Finishes_ indexOfObject:finish];
3363 if (index != INT_MAX && index > Finish_)
3371 - (void) _readStatus:(NSNumber *)fd { _pooled
3372 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3373 std::istream is(&ib);
3376 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3377 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3379 while (std::getline(is, line)) {
3380 const char *data(line.c_str());
3381 size_t size(line.size());
3382 lprintf("S:%s\n", data);
3384 if (conffile_r(data, size)) {
3385 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3386 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3387 } else if (strncmp(data, "status: ", 8) == 0) {
3388 // status: <package>: {unpacked,half-configured,installed}
3389 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:@"STATUS"]);
3390 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3391 } else if (strncmp(data, "processing: ", 12) == 0) {
3392 // processing: configure: config-test
3393 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:@"STATUS"]);
3394 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3395 } else if (pmstatus_r(data, size)) {
3396 std::string type([pmstatus_r[1] UTF8String]);
3398 NSString *package = pmstatus_r[2];
3399 if ([package isEqualToString:@"dpkg-exec"])
3402 float percent([pmstatus_r[3] floatValue]);
3403 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3405 NSString *string = pmstatus_r[4];
3407 if (type == "pmerror") {
3408 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"ERROR" forPackage:package]);
3409 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3410 } else if (type == "pmstatus") {
3411 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"STATUS" forPackage:package]);
3412 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3413 } else if (type == "pmconffile")
3414 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3416 lprintf("E:unknown pmstatus\n");
3418 lprintf("E:unknown status\n");
3424 - (void) _readOutput:(NSNumber *)fd { _pooled
3425 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3426 std::istream is(&ib);
3429 while (std::getline(is, line)) {
3430 lprintf("O:%s\n", line.c_str());
3432 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:@"INFORMATION"]);
3433 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3443 - (Package *) packageWithName:(NSString *)name {
3444 @synchronized (self) {
3445 if (static_cast<pkgDepCache *>(cache_) == NULL)
3447 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3448 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3452 if ((self = [super init]) != nil) {
3459 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3460 apr_pool_create(&pool_, NULL);
3462 size_t capacity(MetaFile_->active_);
3468 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3469 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3473 _assert(pipe(fds) != -1);
3476 _config->Set("APT::Keep-Fds::", cydiafd_);
3477 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3480 detachNewThreadSelector:@selector(_readCydia:)
3482 withObject:[NSNumber numberWithInt:fds[0]]
3485 _assert(pipe(fds) != -1);
3489 detachNewThreadSelector:@selector(_readStatus:)
3491 withObject:[NSNumber numberWithInt:fds[0]]
3494 _assert(pipe(fds) != -1);
3495 _assert(dup2(fds[0], 0) != -1);
3496 _assert(close(fds[0]) != -1);
3498 input_ = fdopen(fds[1], "a");
3500 _assert(pipe(fds) != -1);
3501 _assert(dup2(fds[1], 1) != -1);
3502 _assert(close(fds[1]) != -1);
3505 detachNewThreadSelector:@selector(_readOutput:)
3507 withObject:[NSNumber numberWithInt:fds[0]]
3512 - (pkgCacheFile &) cache {
3516 - (pkgDepCache::Policy *) policy {
3520 - (pkgRecords *) records {
3524 - (pkgProblemResolver *) resolver {
3528 - (pkgAcquire &) fetcher {
3532 - (pkgSourceList &) list {
3536 - (NSArray *) packages {
3537 return (NSArray *) packages_;
3540 - (NSArray *) sources {
3544 - (Source *) sourceWithKey:(NSString *)key {
3545 for (Source *source in [self sources]) {
3546 if ([[source key] isEqualToString:key])
3551 - (bool) popErrorWithTitle:(NSString *)title {
3554 while (!_error->empty()) {
3556 bool warning(!_error->PopMessage(error));
3561 size_t size(error.size());
3562 if (size == 0 || error[size - 1] != '\n')
3564 error.resize(size - 1);
3567 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3569 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3575 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3576 return [self popErrorWithTitle:title] || !success;
3579 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3580 @synchronized (self) {
3583 [self releasePackages];
3586 [sourceList_ removeAllObjects];
3606 apr_pool_clear(pool_);
3608 NSRecycleZone(zone_);
3609 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3611 int chk(creat("/tmp/cydia.chk", 0644));
3615 if (invocation != nil)
3616 [invocation invoke];
3618 NSString *title(UCLocalize("DATABASE"));
3621 OpProgress progress;
3622 while (!cache_.Open(progress, true)) { pop:
3624 bool warning(!_error->PopMessage(error));
3625 lprintf("cache_.Open():[%s]\n", error.c_str());
3627 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3628 [delegate_ repairWithSelector:@selector(configure)];
3629 else if (error == "The package lists or status file could not be parsed or opened.")
3630 [delegate_ repairWithSelector:@selector(update)];
3631 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3632 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3633 // else if (error == "Malformed Status line")
3634 // else if (error == "The list of sources could not be read.")
3636 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3646 unlink("/tmp/cydia.chk");
3648 now_ = [[NSDate date] timeIntervalSince1970];
3650 policy_ = new pkgDepCache::Policy();
3651 records_ = new pkgRecords(cache_);
3652 resolver_ = new pkgProblemResolver(cache_);
3653 fetcher_ = new pkgAcquire(&status_);
3656 list_ = new pkgSourceList();
3657 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3660 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3661 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:@"ERROR"] forTask:title];
3665 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3668 if (cache_->BrokenCount() != 0) {
3669 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3672 if (cache_->BrokenCount() != 0) {
3673 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:@"ERROR"] forTask:title];
3677 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3681 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3682 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3683 [sourceList_ addObject:object];
3685 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3686 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3687 // XXX: this could be more intelligent
3688 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3689 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3691 sourceMap_[cached->ID] = object;
3696 /*std::vector<Package *> packages;
3697 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3698 [packages_ release];
3703 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3704 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3705 //packages.push_back(package);
3706 CFArrayAppendValue(packages_, [package retain]);
3710 /*if (packages.empty())
3711 packages_ = [[NSArray alloc] init];
3713 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3716 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3717 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3718 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3726 /*if (!packages.empty())
3727 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3728 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3730 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3732 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3734 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3738 size_t count(CFArrayGetCount(packages_));
3739 MetaFile_->active_ = count;
3741 for (size_t index(0); index != count; ++index)
3742 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3746 } } CYPoolEnd() _trace(); }
3749 @synchronized (self) {
3751 resolver_ = new pkgProblemResolver(cache_);
3753 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3754 if (!cache_[iterator].Keep())
3755 cache_->MarkKeep(iterator, false);
3756 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3757 cache_->SetReInstall(iterator, false);
3760 - (void) configure {
3761 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3763 system([dpkg UTF8String]);
3768 // XXX: I don't remember this condition
3773 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3775 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3777 if ([self popErrorWithTitle:title])
3781 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3784 public pkgArchiveCleaner
3787 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3792 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3799 fetcher_->Shutdown();
3801 pkgRecords records(cache_);
3803 lock_ = new FileFd();
3804 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3806 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3808 if ([self popErrorWithTitle:title])
3812 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3815 manager_ = (_system->CreatePM(cache_));
3816 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3823 bool substrate(RestartSubstrate_);
3824 RestartSubstrate_ = false;
3826 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3828 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3830 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3832 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3833 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3836 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3838 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3840 [self popErrorWithTitle:title];
3844 bool failed = false;
3845 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3846 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3848 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3854 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3862 RestartSubstrate_ = true;
3865 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3867 if (_error->PendingError()) {
3872 if (result == pkgPackageManager::Failed) {
3877 if (result != pkgPackageManager::Completed) {
3882 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3884 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3886 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3887 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3890 if (![before isEqualToArray:after])
3895 NSString *title(UCLocalize("UPGRADE"));
3896 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3902 [self updateWithStatus:status_];
3905 - (void) updateWithStatus:(Status &)status {
3906 NSString *title(UCLocalize("REFRESHING_DATA"));
3909 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3913 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3914 if ([self popErrorWithTitle:title])
3917 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3919 bool success(ListUpdate(status, list, PulseInterval_));
3920 if (status.WasCancelled())
3923 [self popErrorWithTitle:title forOperation:success];
3925 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3927 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3931 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3932 delegate_ = delegate;
3935 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3936 progress_ = delegate;
3937 status_.setDelegate(delegate);
3940 - (NSObject<ProgressDelegate> *) progressDelegate {
3944 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3945 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3946 return i == sourceMap_.end() ? nil : i->second;
3949 - (NSString *) mappedSectionForPointer:(const char *)section {
3950 _H<NSString> *mapped;
3952 _profile(Database$mappedSectionForPointer$Cache)
3953 mapped = §ions_[section];
3956 if (*mapped == NULL) {
3957 size_t length(strlen(section));
3958 char spaced[length + 1];
3960 _profile(Database$mappedSectionForPointer$Replace)
3961 for (size_t index(0); index != length; ++index)
3962 spaced[index] = section[index] == '_' ? ' ' : section[index];
3963 spaced[length] = '\0';
3968 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3969 string = [NSString stringWithUTF8String:spaced];
3972 _profile(Database$mappedSectionForPointer$Map)
3973 string = [SectionMap_ objectForKey:string] ?: string;
3983 /* Web Scripting {{{ */
3984 @interface CydiaObject : NSObject {
3986 _transient id delegate_;
3989 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3993 @implementation CydiaObject
3996 [indirect_ release];
4000 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4001 if ((self = [super init]) != nil) {
4002 indirect_ = [indirect retain];
4006 - (void) setDelegate:(id)delegate {
4007 delegate_ = delegate;
4010 + (NSArray *) _attributeKeys {
4011 return [NSArray arrayWithObjects:
4026 - (NSArray *) attributeKeys {
4027 return [[self class] _attributeKeys];
4030 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4031 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4034 - (NSString *) version {
4038 - (NSString *) device {
4039 return [[UIDevice currentDevice] uniqueIdentifier];
4042 - (NSString *) firmware {
4043 return [[UIDevice currentDevice] systemVersion];
4046 - (NSString *) hostname {
4047 return [[UIDevice currentDevice] name];
4050 - (NSString *) idiom {
4051 return (id) Idiom_ ?: [NSNull null];
4054 - (NSString *) plmn {
4055 return (id) PLMN_ ?: [NSNull null];
4058 - (NSString *) ecid {
4059 return (id) ChipID_ ?: [NSNull null];
4062 - (NSString *) serial {
4063 return SerialNumber_;
4066 - (NSString *) role {
4067 return (id) Role_ ?: [NSNull null];
4070 - (NSString *) model {
4071 return [NSString stringWithUTF8String:Machine_];
4074 - (NSString *) token {
4075 return (id) Token_ ?: [NSNull null];
4078 + (NSString *) webScriptNameForSelector:(SEL)selector {
4080 else if (selector == @selector(addTrivialSource:))
4081 return @"addTrivialSource";
4082 else if (selector == @selector(close))
4084 else if (selector == @selector(du:))
4086 else if (selector == @selector(stringWithFormat:arguments:))
4088 else if (selector == @selector(getAllSources))
4089 return @"getAllSourcs";
4090 else if (selector == @selector(getKernelNumber:))
4091 return @"getKernelNumber";
4092 else if (selector == @selector(getKernelString:))
4093 return @"getKernelString";
4094 else if (selector == @selector(getInstalledPackages))
4095 return @"getInstalledPackages";
4096 else if (selector == @selector(getPackageById:))
4097 return @"getPackageById";
4098 else if (selector == @selector(installPackages:))
4099 return @"installPackages";
4100 else if (selector == @selector(localizedStringForKey:value:table:))
4102 else if (selector == @selector(refreshSources))
4103 return @"refreshSources";
4104 else if (selector == @selector(removeButton))
4105 return @"removeButton";
4106 else if (selector == @selector(substitutePackageNames:))
4107 return @"substitutePackageNames";
4108 else if (selector == @selector(scrollToBottom:))
4109 return @"scrollToBottom";
4110 else if (selector == @selector(setAllowsNavigationAction:))
4111 return @"setAllowsNavigationAction";
4112 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4113 return @"setButtonImage";
4114 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4115 return @"setButtonTitle";
4116 else if (selector == @selector(setHidesBackButton:))
4117 return @"setHidesBackButton";
4118 else if (selector == @selector(setHidesNavigationBar:))
4119 return @"setHidesNavigationBar";
4120 else if (selector == @selector(setNavigationBarStyle:))
4121 return @"setNavigationBarStyle";
4122 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4123 return @"setNavigationBarTintColor";
4124 else if (selector == @selector(setPopupHook:))
4125 return @"setPopupHook";
4126 else if (selector == @selector(setToken:))
4128 else if (selector == @selector(setViewportWidth:))
4129 return @"setViewportWidth";
4130 else if (selector == @selector(statfs:))
4132 else if (selector == @selector(supports:))
4138 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4139 return [self webScriptNameForSelector:selector] == nil;
4142 - (BOOL) supports:(NSString *)feature {
4143 return [feature isEqualToString:@"window.open"];
4146 - (NSNumber *) getKernelNumber:(NSString *)name {
4147 const char *string([name UTF8String]);
4150 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4151 return (id) [NSNull null];
4153 if (size != sizeof(int))
4154 return (id) [NSNull null];
4157 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4158 return (id) [NSNull null];
4160 return [NSNumber numberWithInt:value];
4163 - (NSString *) getKernelString:(NSString *)name {
4164 const char *string([name UTF8String]);
4167 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4168 return (id) [NSNull null];
4170 char value[size + 1];
4171 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4172 return (id) [NSNull null];
4174 // XXX: just in case you request something ludicrous
4177 return [NSString stringWithCString:value];
4180 - (void) addTrivialSource:(NSString *)href {
4181 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4184 - (void) refreshSources {
4185 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4188 - (NSArray *) getAllSources {
4189 return [[Database sharedInstance] sources];
4192 - (NSArray *) getInstalledPackages {
4193 Database *database([Database sharedInstance]);
4194 @synchronized (database) {
4195 NSArray *packages([database packages]);
4196 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4197 for (Package *package in packages)
4198 if (![package uninstalled])
4199 [installed addObject:package];
4203 - (Package *) getPackageById:(NSString *)id {
4204 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4208 return (Package *) [NSNull null];
4211 - (NSArray *) statfs:(NSString *)path {
4214 if (path == nil || statfs([path UTF8String], &stat) == -1)
4217 return [NSArray arrayWithObjects:
4218 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4219 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4220 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4224 - (NSNumber *) du:(NSString *)path {
4225 NSNumber *value(nil);
4228 _assert(pipe(fds) != -1);
4230 pid_t pid(ExecFork());
4232 _assert(dup2(fds[1], 1) != -1);
4233 _assert(close(fds[0]) != -1);
4234 _assert(close(fds[1]) != -1);
4235 /* XXX: this should probably not use du */
4236 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4241 _assert(close(fds[1]) != -1);
4243 if (FILE *du = fdopen(fds[0], "r")) {
4245 while (fgets(line, sizeof(line), du) != NULL) {
4246 size_t length(strlen(line));
4247 while (length != 0 && line[length - 1] == '\n')
4248 line[--length] = '\0';
4249 if (char *tab = strchr(line, '\t')) {
4251 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4256 } else _assert(close(fds[0]));
4260 if (waitpid(pid, &status, 0) == -1)
4263 else _assert(false);
4269 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4272 - (void) installPackages:(NSArray *)packages {
4273 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4276 - (NSString *) substitutePackageNames:(NSString *)message {
4277 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4278 for (size_t i(0), e([words count]); i != e; ++i) {
4279 NSString *word([words objectAtIndex:i]);
4280 if (Package *package = [[Database sharedInstance] packageWithName:word])
4281 [words replaceObjectAtIndex:i withObject:[package name]];
4284 return [words componentsJoinedByString:@" "];
4287 - (void) removeButton {
4288 [indirect_ removeButton];
4291 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4292 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4295 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4296 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4299 - (void) setAllowsNavigationAction:(NSString *)value {
4300 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4303 - (void) setHidesBackButton:(NSString *)value {
4304 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4307 - (void) setHidesNavigationBar:(NSString *)value {
4308 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4311 - (void) setNavigationBarStyle:(NSString *)value {
4312 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4315 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4316 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4317 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4318 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4321 - (void) _setToken:(NSString *)token {
4325 [Metadata_ removeObjectForKey:@"Token"];
4327 [Metadata_ setObject:Token_ forKey:@"Token"];
4332 - (void) setToken:(NSString *)token {
4333 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4336 - (void) setPopupHook:(id)function {
4337 [indirect_ setPopupHook:function];
4340 - (void) scrollToBottom:(NSNumber *)animated {
4341 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4344 - (void) setViewportWidth:(float)width {
4345 [indirect_ setViewportWidthOnMainThread:width];
4348 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4349 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4350 unsigned count([arguments count]);
4352 for (unsigned i(0); i != count; ++i)
4353 values[i] = [arguments objectAtIndex:i];
4354 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4357 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4358 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4360 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4362 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4368 /* @ Loading... Indicator {{{ */
4369 @interface CYLoadingIndicator : UIView {
4370 _H<UIActivityIndicatorView> spinner_;
4372 _H<UIView> container_;
4375 @property (readonly, nonatomic) UILabel *label;
4376 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4380 @implementation CYLoadingIndicator
4382 - (id) initWithFrame:(CGRect)frame {
4383 if ((self = [super initWithFrame:frame]) != nil) {
4384 container_ = [[[UIView alloc] init] autorelease];
4385 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4387 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4388 [spinner_ startAnimating];
4389 [container_ addSubview:spinner_];
4391 label_ = [[[UILabel alloc] init] autorelease];
4392 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4393 [label_ setBackgroundColor:[UIColor clearColor]];
4394 [label_ setTextColor:[UIColor blackColor]];
4395 [label_ setShadowColor:[UIColor whiteColor]];
4396 [label_ setShadowOffset:CGSizeMake(0, 1)];
4397 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4398 [container_ addSubview:label_];
4400 CGSize viewsize = frame.size;
4401 CGSize spinnersize = [spinner_ bounds].size;
4402 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4403 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4405 CGRect containrect = {
4406 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4407 CGSizeMake(bothwidth, spinnersize.height)
4410 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4418 [container_ setFrame:containrect];
4419 [spinner_ setFrame:spinrect];
4420 [label_ setFrame:textrect];
4421 [self addSubview:container_];
4425 - (UILabel *) label {
4429 - (UIActivityIndicatorView *) activityIndicatorView {
4435 /* Emulated Loading Controller {{{ */
4436 @interface CYEmulatedLoadingController : CYViewController {
4437 _transient Database *database_;
4438 _H<CYLoadingIndicator> indicator_;
4439 _H<UITabBar> tabbar_;
4440 _H<UINavigationBar> navbar_;
4445 @implementation CYEmulatedLoadingController
4447 - (id) initWithDatabase:(Database *)database {
4448 if ((self = [super init]) != nil) {
4449 database_ = database;
4453 // XXX: factor this out somewhere
4454 - (UIColor *) groupTableViewBackgroundColor {
4455 UIDevice *device([UIDevice currentDevice]);
4456 bool iPad([device respondsToSelector:@selector(userInterfaceIdiom)] && [device userInterfaceIdiom] == UIUserInterfaceIdiomPad);
4457 return iPad ? [UIColor colorWithRed:0.821 green:0.834 blue:0.860 alpha:1] : [UIColor groupTableViewBackgroundColor];
4461 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4462 [[self view] setBackgroundColor:[self groupTableViewBackgroundColor]];
4464 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4465 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4466 [[self view] addSubview:indicator_];
4468 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4469 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4470 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4471 [[self view] addSubview:tabbar_];
4473 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4474 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4475 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4476 [[self view] addSubview:navbar_];
4479 - (void) releaseSubviews {
4488 /* Cydia Browser Controller {{{ */
4489 @interface CYBrowserController : BrowserController {
4490 CydiaObject *cydia_;
4495 @implementation CYBrowserController
4502 - (NSURL *) navigationURL {
4503 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4506 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4509 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4510 [super webView:view didClearWindowObject:window forFrame:frame];
4512 WebDataSource *source([frame dataSource]);
4513 NSURLResponse *response([source response]);
4515 NSURL *url([response URL]);
4516 NSString *scheme([url scheme]);
4517 NSString *host([url host]);
4519 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4520 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4521 NSDictionary *headers([http allHeaderFields]);
4522 [self setHeaders:headers forHost:host];
4526 [host isEqualToString:@"cydia.saurik.com"] ||
4527 [host hasSuffix:@".cydia.saurik.com"] ||
4528 [scheme isEqualToString:@"file"]
4530 [window setValue:cydia_ forKey:@"cydia"];
4533 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4534 if (System_ != NULL)
4535 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4536 if (Machine_ != NULL)
4537 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4539 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4541 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4544 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4545 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4546 [self _setMoreHeaders:copy];
4550 - (void) setDelegate:(id)delegate {
4551 [super setDelegate:delegate];
4552 [cydia_ setDelegate:delegate];
4556 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4557 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4559 WebView *webview([[webview_ _documentView] webView]);
4561 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4564 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4566 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4567 if (Product_ != nil)
4568 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4570 [webview setApplicationNameForUserAgent:application];
4578 @interface NSObject (CydiaScript)
4579 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4582 @implementation NSObject (CydiaScript)
4584 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4590 @implementation NSArray (CydiaScript)
4592 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4593 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4594 for (size_t i(0), e([self count]); i != e; ++i)
4595 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4601 @implementation NSDictionary (CydiaScript)
4603 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4604 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4606 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4613 /* Confirmation Controller {{{ */
4614 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4615 if (!iterator.end())
4616 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4617 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4619 pkgCache::PkgIterator package(dep.TargetPkg());
4622 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4629 @protocol ConfirmationControllerDelegate
4630 - (void) cancelAndClear:(bool)clear;
4631 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4635 @interface ConfirmationController : CYBrowserController {
4636 _transient Database *database_;
4638 UIAlertView *essential_;
4640 NSDictionary *changes_;
4641 NSMutableArray *issues_;
4642 NSDictionary *sizes_;
4647 - (id) initWithDatabase:(Database *)database;
4651 @implementation ConfirmationController
4658 if (essential_ != nil)
4659 [essential_ release];
4666 RestartSubstrate_ = true;
4667 [delegate_ confirmWithNavigationController:[self navigationController]];
4670 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4671 NSString *context([alert context]);
4673 if ([context isEqualToString:@"remove"]) {
4674 if (button == [alert cancelButtonIndex])
4675 [self dismissModalViewControllerAnimated:YES];
4676 else if (button == [alert firstOtherButtonIndex]) {
4680 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4681 } else if ([context isEqualToString:@"unable"]) {
4682 [self dismissModalViewControllerAnimated:YES];
4683 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4685 [super alertView:alert clickedButtonAtIndex:button];
4689 - (void) _doContinue {
4690 [self dismissModalViewControllerAnimated:YES];
4691 [delegate_ cancelAndClear:NO];
4694 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4695 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4699 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4700 [super webView:view didClearWindowObject:window forFrame:frame];
4702 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4703 changes_, @"changes",
4707 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4710 - (id) initWithDatabase:(Database *)database {
4711 if ((self = [super init]) != nil) {
4712 database_ = database;
4714 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4715 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4716 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4717 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4718 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4722 pkgCacheFile &cache([database_ cache]);
4723 NSArray *packages([database_ packages]);
4724 pkgDepCache::Policy *policy([database_ policy]);
4726 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4728 for (Package *package in packages) {
4729 pkgCache::PkgIterator iterator([package iterator]);
4730 NSString *name([package id]);
4732 if ([package broken]) {
4733 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4735 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4737 reasons, @"reasons",
4740 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4744 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4745 pkgCache::DepIterator start;
4746 pkgCache::DepIterator end;
4747 dep.GlobOr(start, end); // ++dep
4749 if (!cache->IsImportantDep(end))
4751 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4754 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4756 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4757 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4758 clauses, @"clauses",
4762 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4764 pkgCache::PkgIterator target(start.TargetPkg());
4765 if (target->ProvidesList != 0)
4766 reason = @"missing";
4768 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4770 reason = @"installed";
4771 installed = [NSString stringWithUTF8String:ver.VerStr()];
4772 } else if (!cache[target].CandidateVerIter(cache).end())
4773 reason = @"uninstalled";
4774 else if (target->ProvidesList == 0)
4775 reason = @"uninstallable";
4777 reason = @"virtual";
4780 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4781 [NSString stringWithUTF8String:start.CompType()], @"operator",
4782 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4785 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4786 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4787 version, @"version",
4789 installed, @"installed",
4792 // yes, seriously. (wtf?)
4800 pkgDepCache::StateCache &state(cache[iterator]);
4802 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4804 if (state.NewInstall())
4805 [installs addObject:name];
4806 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4807 [reinstalls addObject:name];
4808 else if (state.Upgrade())
4809 [upgrades addObject:name];
4810 else if (state.Downgrade())
4811 [downgrades addObject:name];
4812 else if (!state.Delete())
4814 else if (special_r(name))
4815 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4816 [NSNull null], @"package",
4817 [NSArray arrayWithObjects:
4818 [NSDictionary dictionaryWithObjectsAndKeys:
4819 @"Conflicts", @"relationship",
4820 [NSArray arrayWithObjects:
4821 [NSDictionary dictionaryWithObjectsAndKeys:
4823 [NSNull null], @"version",
4824 @"installed", @"reason",
4831 if ([package essential])
4833 [removes addObject:name];
4836 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4837 substrate_ |= DepSubstrate(iterator.CurrentVer());
4842 else if (Advanced_) {
4843 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4845 essential_ = [[UIAlertView alloc]
4846 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4847 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4849 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4851 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4855 [essential_ setContext:@"remove"];
4857 essential_ = [[UIAlertView alloc]
4858 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4859 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4861 cancelButtonTitle:UCLocalize("OKAY")
4862 otherButtonTitles:nil
4865 [essential_ setContext:@"unable"];
4868 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4869 installs, @"installs",
4870 reinstalls, @"reinstalls",
4871 upgrades, @"upgrades",
4872 downgrades, @"downgrades",
4873 removes, @"removes",
4876 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4877 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4878 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4881 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4883 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4884 initWithTitle:UCLocalize("CANCEL")
4885 style:UIBarButtonItemStylePlain
4887 action:@selector(cancelButtonClicked)
4893 - (void) applyRightButton {
4894 if ([issues_ count] == 0 && ![self isLoading])
4895 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4896 initWithTitle:UCLocalize("CONFIRM")
4897 style:UIBarButtonItemStyleDone
4899 action:@selector(confirmButtonClicked)
4902 [[self navigationItem] setRightBarButtonItem:nil];
4906 - (void) cancelButtonClicked {
4907 [self dismissModalViewControllerAnimated:YES];
4908 [delegate_ cancelAndClear:YES];
4912 - (void) confirmButtonClicked {
4913 if (essential_ != nil)
4923 /* Progress Data {{{ */
4924 @interface CydiaProgressData : NSObject {
4925 _transient id delegate_;
4934 _H<NSMutableArray> events_;
4935 _H<NSString> title_;
4937 _H<NSString> status_;
4938 _H<NSString> finish_;
4943 @implementation CydiaProgressData
4945 + (NSArray *) _attributeKeys {
4946 return [NSArray arrayWithObjects:
4958 - (NSArray *) attributeKeys {
4959 return [[self class] _attributeKeys];
4962 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4963 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4967 if ((self = [super init]) != nil) {
4968 events_ = [NSMutableArray arrayWithCapacity:32];
4972 - (void) setDelegate:(id)delegate {
4973 delegate_ = delegate;
4976 - (void) setPercent:(float)value {
4980 - (NSNumber *) percent {
4981 return [NSNumber numberWithFloat:percent_];
4984 - (void) setCurrent:(float)value {
4988 - (NSNumber *) current {
4989 return [NSNumber numberWithFloat:current_];
4992 - (void) setTotal:(float)value {
4996 - (NSNumber *) total {
4997 return [NSNumber numberWithFloat:total_];
5000 - (void) setSpeed:(float)value {
5004 - (NSNumber *) speed {
5005 return [NSNumber numberWithFloat:speed_];
5008 - (NSArray *) events {
5012 - (void) removeAllEvents {
5013 [events_ removeAllObjects];
5016 - (void) addEvent:(CydiaProgressEvent *)event {
5017 [events_ addObject:event];
5020 - (void) setTitle:(NSString *)text {
5024 - (NSString *) title {
5028 - (void) setFinish:(NSString *)text {
5032 - (NSString *) finish {
5033 return (id) finish_ ?: [NSNull null];
5036 - (void) setRunning:(bool)running {
5040 - (NSNumber *) running {
5041 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5046 /* Progress Controller {{{ */
5047 @interface ProgressController : CYBrowserController <
5050 _transient Database *database_;
5051 _H<CydiaProgressData> progress_;
5055 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5057 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5059 - (void) setTitle:(NSString *)title;
5060 - (void) setCancellable:(bool)cancellable;
5064 @implementation ProgressController
5067 [database_ setProgressDelegate:nil];
5068 [progress_ setDelegate:nil];
5072 - (void) updateCancel {
5073 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5074 initWithTitle:UCLocalize("CANCEL")
5075 style:UIBarButtonItemStylePlain
5077 action:@selector(cancel)
5078 ] autorelease] : nil)];
5081 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5082 if ((self = [super init]) != nil) {
5083 database_ = database;
5084 delegate_ = delegate;
5086 [database_ setProgressDelegate:self];
5088 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5089 [progress_ setDelegate:self];
5091 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5093 [scroller_ setBackgroundColor:[UIColor blackColor]];
5095 [[self navigationItem] setHidesBackButton:YES];
5097 [self updateCancel];
5101 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5102 [super webView:view didClearWindowObject:window forFrame:frame];
5103 [window setValue:progress_ forKey:@"cydiaProgress"];
5106 - (void) updateProgress {
5107 [self dispatchEvent:@"CydiaProgressUpdate"];
5110 - (void) viewWillAppear:(BOOL)animated {
5111 if (![self hasLoaded])
5112 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5114 [super viewWillAppear:animated];
5118 UpdateExternalStatus(0);
5125 [delegate_ terminateWithSuccess];
5126 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5127 [delegate_ suspendWithAnimation:YES];
5129 [delegate_ suspend];*/
5141 system("/usr/bin/sbreload");
5147 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5148 SBReboot(SBSSpringBoardServerPort());
5150 reboot2(RB_AUTOBOOT);
5157 - (void) setTitle:(NSString *)title {
5158 [progress_ setTitle:title];
5159 [self updateProgress];
5162 - (UIBarButtonItem *) rightButton {
5163 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5164 initWithTitle:UCLocalize("CLOSE")
5165 style:UIBarButtonItemStylePlain
5167 action:@selector(close)
5171 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5172 UpdateExternalStatus(1);
5174 [progress_ setRunning:true];
5175 [self setTitle:title];
5176 // implicit updateProgress
5178 SHA1SumValue notifyconf; {
5180 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5183 MMap mmap(file, MMap::ReadOnly);
5185 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5186 notifyconf = sha1.Result();
5190 SHA1SumValue springlist; {
5192 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5195 MMap mmap(file, MMap::ReadOnly);
5197 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5198 springlist = sha1.Result();
5202 if (invocation != nil) {
5203 [invocation yieldToSelector:@selector(invoke)];
5204 [self setTitle:@"COMPLETE"];
5209 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5212 MMap mmap(file, MMap::ReadOnly);
5214 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5215 if (!(notifyconf == sha1.Result()))
5222 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5225 MMap mmap(file, MMap::ReadOnly);
5227 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5228 if (!(springlist == sha1.Result()))
5234 if (RestartSubstrate_)
5238 RestartSubstrate_ = false;
5241 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5242 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5243 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5244 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5245 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5249 system("su -c /usr/bin/uicache mobile");
5252 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5254 [progress_ setRunning:false];
5255 [self updateProgress];
5257 [self applyRightButton];
5260 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5261 [progress_ addEvent:event];
5262 [self updateProgress];
5265 - (bool) isProgressCancelled {
5266 return cancel_ == 2;
5271 [self updateCancel];
5274 - (void) setCancellable:(bool)cancellable {
5275 unsigned cancel(cancel_);
5279 else if (cancel_ == 0)
5282 if (cancel != cancel_)
5283 [self updateCancel];
5286 - (void) setProgressCancellable:(NSNumber *)cancellable {
5287 [self setCancellable:[cancellable boolValue]];
5290 - (void) setProgressPercent:(NSNumber *)percent {
5291 [progress_ setPercent:[percent floatValue]];
5292 [self updateProgress];
5295 - (void) setProgressStatus:(NSDictionary *)status {
5296 if (status == nil) {
5297 [progress_ setCurrent:0];
5298 [progress_ setTotal:0];
5299 [progress_ setSpeed:0];
5301 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5303 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5304 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5305 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5308 [self updateProgress];
5314 /* Cell Content View {{{ */
5315 @protocol ContentDelegate
5316 - (void) drawContentRect:(CGRect)rect;
5319 @interface ContentView : UIView {
5320 _transient id<ContentDelegate> delegate_;
5325 @implementation ContentView
5327 - (id) initWithFrame:(CGRect)frame {
5328 if ((self = [super initWithFrame:frame]) != nil) {
5329 [self setNeedsDisplayOnBoundsChange:YES];
5333 - (void) setDelegate:(id<ContentDelegate>)delegate {
5334 delegate_ = delegate;
5337 - (void) drawRect:(CGRect)rect {
5338 [super drawRect:rect];
5339 [delegate_ drawContentRect:rect];
5344 /* Cydia TableView Cell {{{ */
5345 @interface CYTableViewCell : UITableViewCell {
5346 ContentView *content_;
5352 @implementation CYTableViewCell
5359 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5360 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5362 if (view == content_) {
5363 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5364 highlighted_ = highlighted;
5367 [super _updateHighlightColorsForView:view highlighted:highlighted];
5370 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5371 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5372 highlighted_ = selected;
5374 [super setSelected:selected animated:animated];
5375 [content_ setNeedsDisplay];
5381 /* Package Cell {{{ */
5382 @interface PackageCell : CYTableViewCell <
5387 NSString *description_;
5395 - (PackageCell *) init;
5396 - (void) setPackage:(Package *)package;
5398 - (void) drawContentRect:(CGRect)rect;
5402 @implementation PackageCell
5404 - (void) clearPackage {
5415 if (description_ != nil) {
5416 [description_ release];
5420 if (source_ != nil) {
5425 if (badge_ != nil) {
5430 if (placard_ != nil) {
5440 [self clearPackage];
5444 - (PackageCell *) init {
5445 CGRect frame(CGRectMake(0, 0, 320, 74));
5446 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5447 UIView *content([self contentView]);
5448 CGRect bounds([content bounds]);
5450 content_ = [[ContentView alloc] initWithFrame:bounds];
5451 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5452 [content addSubview:content_];
5454 [content_ setDelegate:self];
5455 [content_ setOpaque:YES];
5459 - (NSString *) accessibilityLabel {
5460 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5463 - (void) setPackage:(Package *)package {
5464 [self clearPackage];
5467 Source *source = [package source];
5469 icon_ = [[package icon] retain];
5470 name_ = [[package name] retain];
5473 description_ = [package longDescription];
5474 if (description_ == nil)
5475 description_ = [package shortDescription];
5476 if (description_ != nil)
5477 description_ = [description_ retain];
5479 commercial_ = [package isCommercial];
5481 package_ = [package retain];
5483 NSString *label = nil;
5484 bool trusted = false;
5486 if (source != nil) {
5487 label = [source label];
5488 trusted = [source trusted];
5489 } else if ([[package id] isEqualToString:@"firmware"])
5490 label = UCLocalize("APPLE");
5492 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5494 NSString *from(label);
5496 NSString *section = [package simpleSection];
5497 if (section != nil && ![section isEqualToString:label]) {
5498 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5499 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5502 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5503 source_ = [from retain];
5505 if (NSString *purpose = [package primaryPurpose])
5506 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5507 badge_ = [badge_ retain];
5512 if (NSString *mode = [package_ mode]) {
5513 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5514 color = RemovingColor_;
5515 //placard = @"removing";
5517 color = InstallingColor_;
5518 //placard = @"installing";
5521 // XXX: the removing/installing placards are not @2x
5524 color = [UIColor whiteColor];
5526 if ([package installed] != nil)
5527 placard = @"installed";
5532 [content_ setBackgroundColor:color];
5535 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5536 placard_ = [placard_ retain];
5538 [self setNeedsDisplay];
5539 [content_ setNeedsDisplay];
5542 - (void) drawContentRect:(CGRect)rect {
5543 bool highlighted(highlighted_);
5544 float width([self bounds].size.width);
5547 CGContextRef context(UIGraphicsGetCurrentContext());
5548 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5549 CGContextFillRect(context, rect);
5554 rect.size = [icon_ size];
5556 rect.size.width /= 2;
5557 rect.size.height /= 2;
5559 rect.origin.x = 25 - rect.size.width / 2;
5560 rect.origin.y = 25 - rect.size.height / 2;
5562 [icon_ drawInRect:rect];
5565 if (badge_ != nil) {
5567 rect.size = [badge_ size];
5569 rect.size.width /= 2;
5570 rect.size.height /= 2;
5572 rect.origin.x = 36 - rect.size.width / 2;
5573 rect.origin.y = 36 - rect.size.height / 2;
5575 [badge_ drawInRect:rect];
5582 UISetColor(commercial_ ? Purple_ : Black_);
5583 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5584 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5587 UISetColor(commercial_ ? Purplish_ : Gray_);
5588 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5590 if (placard_ != nil)
5591 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5596 /* Section Cell {{{ */
5597 @interface SectionCell : CYTableViewCell <
5609 - (void) setSection:(Section *)section editing:(BOOL)editing;
5613 @implementation SectionCell
5615 - (void) clearSection {
5616 if (basic_ != nil) {
5621 if (section_ != nil) {
5631 if (count_ != nil) {
5638 [self clearSection];
5644 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5645 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5646 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5647 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5648 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5650 UIView *content([self contentView]);
5651 CGRect bounds([content bounds]);
5653 content_ = [[ContentView alloc] initWithFrame:bounds];
5654 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5655 [content addSubview:content_];
5656 [content_ setBackgroundColor:[UIColor whiteColor]];
5658 [content_ setDelegate:self];
5662 - (void) onSwitch:(id)sender {
5663 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5664 if (metadata == nil) {
5665 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5666 [Sections_ setObject:metadata forKey:basic_];
5669 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5673 - (void) setSection:(Section *)section editing:(BOOL)editing {
5674 if (editing != editing_) {
5676 [switch_ removeFromSuperview];
5678 [self addSubview:switch_];
5682 [self clearSection];
5684 if (section == nil) {
5685 name_ = [UCLocalize("ALL_PACKAGES") retain];
5688 basic_ = [section name];
5690 basic_ = [basic_ retain];
5692 section_ = [section localized];
5693 if (section_ != nil)
5694 section_ = [section_ retain];
5696 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5697 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5700 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5703 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5704 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5706 [content_ setNeedsDisplay];
5709 - (void) setFrame:(CGRect)frame {
5710 [super setFrame:frame];
5712 CGRect rect([switch_ frame]);
5713 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5716 - (NSString *) accessibilityLabel {
5720 - (void) drawContentRect:(CGRect)rect {
5721 bool highlighted(highlighted_ && !editing_);
5723 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5728 float width(rect.size.width);
5734 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5736 CGSize size = [count_ sizeWithFont:Font14_];
5740 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5746 /* File Table {{{ */
5747 @interface FileTable : CYViewController <
5748 UITableViewDataSource,
5751 _transient Database *database_;
5754 NSMutableArray *files_;
5758 - (id) initWithDatabase:(Database *)database;
5759 - (void) setPackage:(Package *)package;
5763 @implementation FileTable
5766 [self releaseSubviews];
5775 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5776 return files_ == nil ? 0 : [files_ count];
5779 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5783 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5784 static NSString *reuseIdentifier = @"Cell";
5786 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5788 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5789 [cell setFont:[UIFont systemFontOfSize:16]];
5791 [cell setText:[files_ objectAtIndex:indexPath.row]];
5792 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5797 - (NSURL *) navigationURL {
5798 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5802 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5804 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5805 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5806 [list_ setRowHeight:24.0f];
5807 [list_ setDataSource:self];
5808 [list_ setDelegate:self];
5809 [[self view] addSubview:list_];
5812 - (void) viewDidLoad {
5813 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5816 - (void) releaseSubviews {
5821 - (id) initWithDatabase:(Database *)database {
5822 if ((self = [super init]) != nil) {
5823 database_ = database;
5825 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5829 - (void) setPackage:(Package *)package {
5830 if (package_ != nil) {
5831 [package_ autorelease];
5840 [files_ removeAllObjects];
5842 if (package != nil) {
5843 package_ = [package retain];
5844 name_ = [[package id] retain];
5846 if (NSArray *files = [package files])
5847 [files_ addObjectsFromArray:files];
5849 if ([files_ count] != 0) {
5850 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5851 [files_ removeObjectAtIndex:0];
5852 [files_ sortUsingSelector:@selector(compareByPath:)];
5854 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5855 [stack addObject:@"/"];
5857 for (int i(0), e([files_ count]); i != e; ++i) {
5858 NSString *file = [files_ objectAtIndex:i];
5859 while (![file hasPrefix:[stack lastObject]])
5860 [stack removeLastObject];
5861 NSString *directory = [stack lastObject];
5862 [stack addObject:[file stringByAppendingString:@"/"]];
5863 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5864 ([stack count] - 2) * 3, "",
5865 [file substringFromIndex:[directory length]]
5874 - (void) reloadData {
5877 [self setPackage:[database_ packageWithName:name_]];
5882 /* Package Controller {{{ */
5883 @interface CYPackageController : CYBrowserController <
5884 UIActionSheetDelegate
5886 _transient Database *database_;
5887 _H<Package> package_;
5890 _H<NSMutableArray> buttons_;
5891 _H<UIBarButtonItem> button_;
5894 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5898 @implementation CYPackageController
5900 - (NSURL *) navigationURL {
5901 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5904 /* XXX: this is not safe at all... localization of /fail/ */
5905 - (void) _clickButtonWithName:(NSString *)name {
5906 if ([name isEqualToString:UCLocalize("CLEAR")])
5907 [delegate_ clearPackage:package_];
5908 else if ([name isEqualToString:UCLocalize("INSTALL")])
5909 [delegate_ installPackage:package_];
5910 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5911 [delegate_ installPackage:package_];
5912 else if ([name isEqualToString:UCLocalize("REMOVE")])
5913 [delegate_ removePackage:package_];
5914 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5915 [delegate_ installPackage:package_];
5916 else _assert(false);
5919 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5920 NSString *context([sheet context]);
5922 if ([context isEqualToString:@"modify"]) {
5923 if (button != [sheet cancelButtonIndex]) {
5924 NSString *buttonName = [buttons_ objectAtIndex:button];
5925 [self _clickButtonWithName:buttonName];
5928 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5932 - (bool) _allowJavaScriptPanel {
5937 - (void) _customButtonClicked {
5938 int count([buttons_ count]);
5943 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5945 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5946 [buttons addObjectsFromArray:buttons_];
5948 UIActionSheet *sheet = [[[UIActionSheet alloc]
5951 cancelButtonTitle:nil
5952 destructiveButtonTitle:nil
5953 otherButtonTitles:nil
5956 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5958 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5959 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5961 [sheet setContext:@"modify"];
5963 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5967 // We don't want to allow non-commercial packages to do custom things to the install button,
5968 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5969 - (void) customButtonClicked {
5971 [super customButtonClicked];
5973 [self _customButtonClicked];
5976 - (void) reloadButtonClicked {
5977 // Don't reload a commerical package by tapping the loading button,
5978 // but if it's not an Install button, we should forward it on.
5979 if (![package_ uninstalled])
5980 [self _customButtonClicked];
5983 - (void) applyLoadingTitle {
5984 // Don't show "Loading" as the title. Ever.
5987 - (UIBarButtonItem *) rightButton {
5992 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5993 if ((self = [super init]) != nil) {
5994 database_ = database;
5995 buttons_ = [NSMutableArray arrayWithCapacity:4];
5996 name_ = [NSString stringWithString:name];
5997 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
6001 - (void) reloadData {
6002 package_ = [database_ packageWithName:name_];
6004 [buttons_ removeAllObjects];
6006 if (package_ != nil) {
6007 [(Package *) package_ parse];
6009 commercial_ = [package_ isCommercial];
6011 if ([package_ mode] != nil)
6012 [buttons_ addObject:UCLocalize("CLEAR")];
6013 if ([package_ source] == nil);
6014 else if ([package_ upgradableAndEssential:NO])
6015 [buttons_ addObject:UCLocalize("UPGRADE")];
6016 else if ([package_ uninstalled])
6017 [buttons_ addObject:UCLocalize("INSTALL")];
6019 [buttons_ addObject:UCLocalize("REINSTALL")];
6020 if (![package_ uninstalled])
6021 [buttons_ addObject:UCLocalize("REMOVE")];
6025 switch ([buttons_ count]) {
6026 case 0: title = nil; break;
6027 case 1: title = [buttons_ objectAtIndex:0]; break;
6028 default: title = UCLocalize("MODIFY"); break;
6031 button_ = [[[UIBarButtonItem alloc]
6033 style:UIBarButtonItemStylePlain
6035 action:@selector(customButtonClicked)
6041 - (bool) isLoading {
6042 return commercial_ ? [super isLoading] : false;
6048 /* Package List Controller {{{ */
6049 @interface PackageListController : CYViewController <
6050 UITableViewDataSource,
6053 _transient Database *database_;
6055 NSMutableArray *packages_;
6056 NSMutableArray *sections_;
6058 NSMutableArray *index_;
6059 NSMutableDictionary *indices_;
6063 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6064 - (void) setDelegate:(id)delegate;
6065 - (void) resetCursor;
6069 @implementation PackageListController
6072 [packages_ release];
6073 [sections_ release];
6082 - (void) deselectWithAnimation:(BOOL)animated {
6083 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6086 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6087 CGRect base = [[self view] bounds];
6088 base.size.height -= bounds.size.height;
6089 base.origin = [list_ frame].origin;
6091 [UIView beginAnimations:nil context:NULL];
6092 [UIView setAnimationBeginsFromCurrentState:YES];
6093 [UIView setAnimationCurve:curve];
6094 [UIView setAnimationDuration:duration];
6095 [list_ setFrame:base];
6096 [UIView commitAnimations];
6099 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6100 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6103 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6104 [self resizeForKeyboardBounds:bounds duration:0];
6107 - (void) keyboardWillShow:(NSNotification *)notification {
6110 NSTimeInterval duration;
6111 UIViewAnimationCurve curve;
6112 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6113 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6114 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6115 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6117 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);
6118 UIViewController *base = self;
6119 while ([base parentViewController] != nil)
6120 base = [base parentViewController];
6121 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6122 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6124 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6127 - (void) keyboardWillHide:(NSNotification *)notification {
6128 NSTimeInterval duration;
6129 UIViewAnimationCurve curve;
6130 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6131 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6133 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6136 - (void) viewWillAppear:(BOOL)animated {
6137 [super viewWillAppear:animated];
6139 [self resizeForKeyboardBounds:CGRectZero];
6140 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6141 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6144 - (void) viewWillDisappear:(BOOL)animated {
6145 [super viewWillDisappear:animated];
6147 [self resizeForKeyboardBounds:CGRectZero];
6148 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6149 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6152 - (void) viewDidAppear:(BOOL)animated {
6153 [super viewDidAppear:animated];
6154 [self deselectWithAnimation:animated];
6157 - (void) didSelectPackage:(Package *)package {
6158 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6159 [view setDelegate:delegate_];
6160 [[self navigationController] pushViewController:view animated:YES];
6163 #if TryIndexedCollation
6164 + (BOOL) hasIndexedCollation {
6165 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6169 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6170 NSInteger count([sections_ count]);
6171 return count == 0 ? 1 : count;
6174 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6175 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6177 return [[sections_ objectAtIndex:section] name];
6180 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6181 if ([sections_ count] == 0)
6183 return [[sections_ objectAtIndex:section] count];
6186 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6187 @synchronized (database_) {
6188 if ([database_ era] != era_)
6191 Section *section([sections_ objectAtIndex:[path section]]);
6192 NSInteger row([path row]);
6193 Package *package([packages_ objectAtIndex:([section row] + row)]);
6194 return [[package retain] autorelease];
6197 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6198 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6200 cell = [[[PackageCell alloc] init] autorelease];
6201 [cell setPackage:[self packageAtIndexPath:path]];
6205 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6206 Package *package([self packageAtIndexPath:path]);
6207 package = [database_ packageWithName:[package id]];
6208 [self didSelectPackage:package];
6211 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6212 // XXX: is 20 the most optimal number here?
6213 return [packages_ count] > 20 ? index_ : nil;
6216 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6217 #if TryIndexedCollation
6218 if ([[self class] hasIndexedCollation]) {
6219 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6226 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6227 if ((self = [super init]) != nil) {
6228 database_ = database;
6229 title_ = [title copy];
6230 [[self navigationItem] setTitle:title_];
6232 #if TryIndexedCollation
6233 if ([[self class] hasIndexedCollation])
6234 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6237 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6239 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6241 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6242 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6244 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6245 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6246 [list_ setRowHeight:73];
6247 [[self view] addSubview:list_];
6249 [list_ setDataSource:self];
6250 [list_ setDelegate:self];
6254 - (void) setDelegate:(id)delegate {
6255 delegate_ = delegate;
6258 - (bool) hasPackage:(Package *)package {
6262 - (void) reloadData {
6265 era_ = [database_ era];
6266 NSArray *packages = [database_ packages];
6268 [packages_ removeAllObjects];
6269 [sections_ removeAllObjects];
6271 _profile(PackageTable$reloadData$Filter)
6272 for (Package *package in packages)
6273 if ([self hasPackage:package])
6274 [packages_ addObject:package];
6277 [indices_ removeAllObjects];
6279 Section *section = nil;
6281 #if TryIndexedCollation
6282 if ([[self class] hasIndexedCollation]) {
6283 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6284 NSArray *titles = [collation sectionIndexTitles];
6287 _profile(PackageTable$reloadData$Section)
6288 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6292 _profile(PackageTable$reloadData$Section$Package)
6293 package = [packages_ objectAtIndex:offset];
6294 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6297 while (secidx < index) {
6300 _profile(PackageTable$reloadData$Section$Allocate)
6301 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6304 _profile(PackageTable$reloadData$Section$Add)
6305 [sections_ addObject:section];
6309 [section addToCount];
6315 [index_ removeAllObjects];
6317 _profile(PackageTable$reloadData$Section)
6318 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6322 _profile(PackageTable$reloadData$Section$Package)
6323 package = [packages_ objectAtIndex:offset];
6324 index = [package index];
6327 if (section == nil || [section index] != index) {
6328 _profile(PackageTable$reloadData$Section$Allocate)
6329 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6332 [index_ addObject:[section name]];
6333 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6335 _profile(PackageTable$reloadData$Section$Add)
6336 [sections_ addObject:section];
6340 [section addToCount];
6345 _profile(PackageTable$reloadData$List)
6350 - (void) resetCursor {
6351 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6356 /* Filtered Package List Controller {{{ */
6357 @interface FilteredPackageListController : PackageListController {
6363 - (void) setObject:(id)object;
6364 - (void) setObject:(id)object forFilter:(SEL)filter;
6366 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6370 @implementation FilteredPackageListController
6378 - (void) setFilter:(SEL)filter {
6381 /* XXX: this is an unsafe optimization of doomy hell */
6382 Method method(class_getInstanceMethod([Package class], filter));
6383 _assert(method != NULL);
6384 imp_ = method_getImplementation(method);
6385 _assert(imp_ != NULL);
6388 - (void) setObject:(id)object {
6394 object_ = [object retain];
6397 - (void) setObject:(id)object forFilter:(SEL)filter {
6398 [self setFilter:filter];
6399 [self setObject:object];
6402 - (bool) hasPackage:(Package *)package {
6403 _profile(FilteredPackageTable$hasPackage)
6404 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6408 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6409 if ((self = [super initWithDatabase:database title:title]) != nil) {
6410 [self setFilter:filter];
6411 [self setObject:object];
6418 /* Home Controller {{{ */
6419 @interface HomeController : CYBrowserController {
6424 @implementation HomeController
6427 if ((self = [super init]) != nil) {
6428 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6432 - (NSURL *) navigationURL {
6433 return [NSURL URLWithString:@"cydia://home"];
6436 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6437 [super _setMoreHeaders:request];
6440 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6441 if (UniqueID_ != nil)
6442 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6444 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6447 - (void) aboutButtonClicked {
6448 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6450 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6451 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6452 [alert setCancelButtonIndex:0];
6455 @"Copyright (C) 2008-2011\n"
6456 "Jay Freeman (saurik)\n"
6457 "saurik@saurik.com\n"
6458 "http://www.saurik.com/"
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
6486 if ((self = [super init]) != nil) {
6487 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6491 - (NSURL *) navigationURL {
6492 return [NSURL URLWithString:@"cydia://manage"];
6495 - (void) viewDidLoad {
6496 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6497 initWithTitle:UCLocalize("SETTINGS")
6498 style:UIBarButtonItemStylePlain
6500 action:@selector(settingsButtonClicked)
6503 [self queueStatusDidChange];
6506 - (void) settingsButtonClicked {
6507 [delegate_ showSettings];
6511 - (void) queueButtonClicked {
6515 - (void) applyLoadingTitle {
6516 // Disable "Loading" title.
6519 - (void) applyRightButton {
6520 // Disable right button.
6524 - (void) queueStatusDidChange {
6526 if (!IsWildcat_ && Queuing_) {
6527 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6528 initWithTitle:UCLocalize("QUEUE")
6529 style:UIBarButtonItemStyleDone
6531 action:@selector(queueButtonClicked)
6534 [[self navigationItem] setRightBarButtonItem:nil];
6539 - (bool) isLoading {
6540 // Never show as loading.
6547 /* Refresh Bar {{{ */
6548 @interface RefreshBar : UINavigationBar {
6549 UIProgressIndicator *indicator_;
6550 UITextLabel *prompt_;
6551 UIProgressBar *progress_;
6552 UINavigationButton *cancel_;
6557 @implementation RefreshBar
6560 [indicator_ release];
6562 [progress_ release];
6567 - (void) positionViews {
6568 CGRect frame = [cancel_ frame];
6569 frame.size = [cancel_ sizeThatFits:frame.size];
6570 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6571 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6572 [cancel_ setFrame:frame];
6574 CGSize prgsize = {75, 100};
6576 [self frame].size.width - prgsize.width - 10,
6577 ([self frame].size.height - prgsize.height) / 2
6579 [progress_ setFrame:prgrect];
6581 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6582 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6583 CGRect indrect = {{indoffset, indoffset}, indsize};
6584 [indicator_ setFrame:indrect];
6586 CGSize prmsize = {215, indsize.height + 4};
6588 indoffset * 2 + indsize.width,
6589 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6591 [prompt_ setFrame:prmrect];
6594 - (void) setFrame:(CGRect)frame {
6595 [super setFrame:frame];
6596 [self positionViews];
6599 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6600 if ((self = [super initWithFrame:frame]) != nil) {
6601 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6603 [self setBarStyle:UIBarStyleBlack];
6605 UIBarStyle barstyle([self _barStyle:NO]);
6606 bool ugly(barstyle == UIBarStyleDefault);
6608 UIProgressIndicatorStyle style = ugly ?
6609 UIProgressIndicatorStyleMediumBrown :
6610 UIProgressIndicatorStyleMediumWhite;
6612 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6613 [indicator_ setStyle:style];
6614 [indicator_ startAnimation];
6615 [self addSubview:indicator_];
6617 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6618 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6619 [prompt_ setBackgroundColor:[UIColor clearColor]];
6620 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6621 [self addSubview:prompt_];
6623 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6624 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6625 [progress_ setStyle:0];
6626 [self addSubview:progress_];
6628 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6629 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6630 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6631 [cancel_ setBarStyle:barstyle];
6633 [self positionViews];
6637 - (void) setCancellable:(bool)cancellable {
6639 [self addSubview:cancel_];
6641 [cancel_ removeFromSuperview];
6645 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6646 [progress_ setProgress:0];
6650 [self setCancellable:NO];
6653 - (void) setPrompt:(NSString *)prompt {
6654 [prompt_ setText:prompt];
6657 - (void) setProgress:(float)progress {
6658 [progress_ setProgress:progress];
6664 @class CYNavigationController;
6666 /* Cydia Tab Bar Controller {{{ */
6667 @interface CYTabBarController : UITabBarController <
6668 UITabBarControllerDelegate,
6671 _transient Database *database_;
6672 RefreshBar *refreshbar_;
6676 // XXX: ok, "updatedelegate_"?...
6677 _transient NSObject<CydiaDelegate> *updatedelegate_;
6680 UIViewController *remembered_;
6681 _transient UIViewController *transient_;
6684 - (NSArray *) navigationURLCollection;
6685 - (void) dropBar:(BOOL)animated;
6686 - (void) beginUpdate;
6687 - (void) raiseBar:(BOOL)animated;
6692 @implementation CYTabBarController
6694 - (void) setUnselectedViewController:(UIViewController *)transient {
6695 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6696 if (transient != nil) {
6697 if (transient_ == nil)
6698 remembered_ = [[controllers objectAtIndex:0] retain];
6699 transient_ = transient;
6700 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6701 [controllers replaceObjectAtIndex:0 withObject:transient_];
6702 [self setSelectedIndex:0];
6703 [self setViewControllers:controllers];
6704 [self concealTabBarSelection];
6705 } else if (remembered_ != nil) {
6706 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6707 transient_ = transient;
6708 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6709 [remembered_ release];
6711 [self setViewControllers:controllers];
6712 [self revealTabBarSelection];
6716 - (UIViewController *) unselectedViewController {
6720 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6721 if ([self unselectedViewController])
6722 [self setUnselectedViewController:nil];
6725 - (NSArray *) navigationURLCollection {
6726 NSMutableArray *items([NSMutableArray array]);
6728 // XXX: Should this deal with transient view controllers?
6729 for (id navigation in [self viewControllers]) {
6730 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6732 [items addObject:stack];
6738 - (void) reloadData {
6739 for (CYViewController *controller in [self viewControllers])
6740 [controller reloadData];
6742 [(CYNavigationController *)[self unselectedViewController] reloadData];
6746 [refreshbar_ release];
6747 [[NSNotificationCenter defaultCenter] removeObserver:self];
6752 - (id) initWithDatabase:(Database *)database {
6753 if ((self = [super init]) != nil) {
6754 database_ = database;
6755 [self setDelegate:self];
6757 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6758 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6760 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6764 - (void) setUpdate:(NSDate *)date {
6768 - (void) beginUpdate {
6769 [refreshbar_ start];
6772 [updatedelegate_ retainNetworkActivityIndicator];
6776 detachNewThreadSelector:@selector(performUpdate)
6782 - (void) performUpdate { _pooled
6784 status.setDelegate(self);
6785 [database_ updateWithStatus:status];
6788 performSelectorOnMainThread:@selector(completeUpdate)
6794 - (void) stopUpdateWithSelector:(SEL)selector {
6796 [updatedelegate_ releaseNetworkActivityIndicator];
6798 [self raiseBar:YES];
6801 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6804 - (void) completeUpdate {
6807 [self stopUpdateWithSelector:@selector(reloadData)];
6810 - (void) cancelUpdate {
6811 [self stopUpdateWithSelector:@selector(updateData)];
6814 - (void) cancelPressed {
6815 [self cancelUpdate];
6822 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6823 [refreshbar_ setPrompt:[event compoundMessage]];
6826 - (bool) isProgressCancelled {
6830 - (void) setProgressCancellable:(NSNumber *)cancellable {
6831 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6834 - (void) setProgressPercent:(NSNumber *)percent {
6835 [refreshbar_ setProgress:[percent floatValue]];
6838 - (void) setProgressStatus:(NSDictionary *)status {
6840 [self setProgressPercent:[status objectForKey:@"Percent"]];
6843 - (void) setUpdateDelegate:(id)delegate {
6844 updatedelegate_ = delegate;
6847 - (CGFloat) statusBarHeight {
6848 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6849 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6851 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6855 - (UIView *) transitionView {
6856 if ([self respondsToSelector:@selector(_transitionView)])
6857 return [self _transitionView];
6859 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6862 - (void) dropBar:(BOOL)animated {
6867 UIView *transition([self transitionView]);
6868 [[self view] addSubview:refreshbar_];
6870 CGRect barframe([refreshbar_ frame]);
6872 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6873 barframe.origin.y = [self statusBarHeight];
6875 barframe.origin.y = 0;
6877 [refreshbar_ setFrame:barframe];
6880 [UIView beginAnimations:nil context:NULL];
6882 CGRect viewframe = [transition frame];
6883 viewframe.origin.y += barframe.size.height;
6884 viewframe.size.height -= barframe.size.height;
6885 [transition setFrame:viewframe];
6888 [UIView commitAnimations];
6890 // Ensure bar has the proper width for our view, it might have changed
6891 barframe.size.width = viewframe.size.width;
6892 [refreshbar_ setFrame:barframe];
6894 // XXX: fix Apple's layout bug
6895 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6898 - (void) raiseBar:(BOOL)animated {
6903 UIView *transition([self transitionView]);
6904 [refreshbar_ removeFromSuperview];
6906 CGRect barframe([refreshbar_ frame]);
6909 [UIView beginAnimations:nil context:NULL];
6911 CGRect viewframe = [transition frame];
6912 viewframe.origin.y -= barframe.size.height;
6913 viewframe.size.height += barframe.size.height;
6914 [transition setFrame:viewframe];
6917 [UIView commitAnimations];
6919 // XXX: fix Apple's layout bug
6920 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6924 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6925 // XXX: fix Apple's layout bug
6926 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6930 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6931 bool dropped(dropped_);
6936 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6941 // XXX: fix Apple's layout bug
6942 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6945 - (void) statusBarFrameChanged:(NSNotification *)notification {
6954 /* Cydia Navigation Controller {{{ */
6955 @interface CYNavigationController : UINavigationController {
6956 _transient Database *database_;
6957 _transient id<UINavigationControllerDelegate> delegate_;
6960 - (NSArray *) navigationURLCollection;
6961 - (id) initWithDatabase:(Database *)database;
6962 - (void) reloadData;
6967 @implementation CYNavigationController
6969 - (NSArray *) navigationURLCollection {
6970 NSMutableArray *stack([NSMutableArray array]);
6972 for (CYViewController *controller in [self viewControllers]) {
6973 NSString *url = [[controller navigationURL] absoluteString];
6975 [stack addObject:url];
6981 - (void) reloadData {
6982 for (CYViewController *page in [self viewControllers]) {
6983 // Only reload controllers that have already loaded.
6984 // This prevents a page from accidentally loading too
6985 // early if it hasn't been shown on the screen yet.
6986 if ([page hasLoaded])
6991 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6992 delegate_ = delegate;
6995 - (id) initWithDatabase:(Database *)database {
6996 if ((self = [super init]) != nil) {
6997 database_ = database;
7004 /* Cydia:// Protocol {{{ */
7005 @interface CydiaURLProtocol : NSURLProtocol {
7010 @implementation CydiaURLProtocol
7012 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7013 NSURL *url([request URL]);
7017 NSString *scheme([[url scheme] lowercaseString]);
7018 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7020 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7026 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7030 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7031 id<NSURLProtocolClient> client([self client]);
7033 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7035 NSData *data(UIImagePNGRepresentation(icon));
7037 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7038 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7039 [client URLProtocol:self didLoadData:data];
7040 [client URLProtocolDidFinishLoading:self];
7044 - (void) startLoading {
7045 id<NSURLProtocolClient> client([self client]);
7046 NSURLRequest *request([self request]);
7048 NSURL *url([request URL]);
7049 NSString *href([url absoluteString]);
7050 NSString *scheme([[url scheme] lowercaseString]);
7054 if ([scheme isEqualToString:@"cydia"])
7055 path = [href substringFromIndex:8];
7056 else if ([scheme isEqualToString:@"about"])
7057 path = [href substringFromIndex:12];
7058 else _assert(false);
7060 NSRange slash([path rangeOfString:@"/"]);
7063 if (slash.location == NSNotFound) {
7067 command = [path substringToIndex:slash.location];
7068 path = [path substringFromIndex:(slash.location + 1)];
7071 Database *database([Database sharedInstance]);
7073 if ([command isEqualToString:@"package-icon"]) {
7076 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7077 Package *package([database packageWithName:path]);
7080 UIImage *icon([package icon]);
7081 [self _returnPNGWithImage:icon forRequest:request];
7082 } else if ([command isEqualToString:@"source-icon"]) {
7085 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7086 NSString *source(Simplify(path));
7087 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7089 icon = [UIImage applicationImageNamed:@"unknown.png"];
7090 [self _returnPNGWithImage:icon forRequest:request];
7091 } else if ([command isEqualToString:@"uikit-image"]) {
7094 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7095 UIImage *icon(_UIImageWithName(path));
7096 [self _returnPNGWithImage:icon forRequest:request];
7097 } else if ([command isEqualToString:@"section-icon"]) {
7100 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7101 NSString *section(Simplify(path));
7102 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7104 icon = [UIImage applicationImageNamed:@"unknown.png"];
7105 [self _returnPNGWithImage:icon forRequest:request];
7107 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7111 - (void) stopLoading {
7117 /* Section Controller {{{ */
7118 @interface SectionController : FilteredPackageListController {
7119 _H<NSString> section_;
7122 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7126 @implementation SectionController
7128 - (NSURL *) navigationURL {
7129 NSString *name = section_;
7133 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7136 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7139 title = UCLocalize("ALL_PACKAGES");
7140 else if (![name isEqual:@""])
7141 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7143 title = UCLocalize("NO_SECTION");
7145 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7152 /* Sections Controller {{{ */
7153 @interface SectionsController : CYViewController <
7154 UITableViewDataSource,
7157 _transient Database *database_;
7158 NSMutableArray *sections_;
7159 NSMutableArray *filtered_;
7164 - (id) initWithDatabase:(Database *)database;
7165 - (void) editButtonClicked;
7169 @implementation SectionsController
7172 [self releaseSubviews];
7173 [sections_ release];
7174 [filtered_ release];
7179 - (NSURL *) navigationURL {
7180 return [NSURL URLWithString:@"cydia://sections"];
7183 - (void) updateNavigationItem {
7184 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7185 if ([sections_ count] == 0) {
7186 [[self navigationItem] setRightBarButtonItem:nil];
7188 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7189 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7191 action:@selector(editButtonClicked)
7192 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7196 - (BOOL) isEditing {
7200 - (void) setEditing:(BOOL)editing {
7201 if ((editing_ = editing))
7204 [delegate_ updateData];
7206 [self updateNavigationItem];
7209 - (void) viewDidAppear:(BOOL)animated {
7210 [super viewDidAppear:animated];
7211 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7214 - (void) viewWillDisappear:(BOOL)animated {
7215 [super viewWillDisappear:animated];
7216 if (editing_) [self setEditing:NO];
7219 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7220 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7224 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7225 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7228 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7232 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7233 static NSString *reuseIdentifier = @"SectionCell";
7235 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7237 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7239 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7244 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7248 Section *section = [self sectionAtIndexPath:indexPath];
7250 SectionController *controller = [[[SectionController alloc]
7251 initWithDatabase:database_
7252 section:[section name]
7254 [controller setDelegate:delegate_];
7256 [[self navigationController] pushViewController:controller animated:YES];
7260 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7262 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7263 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7264 [list_ setRowHeight:45.0f];
7265 [list_ setDataSource:self];
7266 [list_ setDelegate:self];
7267 [[self view] addSubview:list_];
7270 - (void) viewDidLoad {
7271 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7274 - (void) releaseSubviews {
7279 - (id) initWithDatabase:(Database *)database {
7280 if ((self = [super init]) != nil) {
7281 database_ = database;
7283 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7284 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7288 - (void) reloadData {
7291 NSArray *packages = [database_ packages];
7293 [sections_ removeAllObjects];
7294 [filtered_ removeAllObjects];
7296 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7299 for (Package *package in packages) {
7300 NSString *name([package section]);
7301 NSString *key(name == nil ? @"" : name);
7305 _profile(SectionsView$reloadData$Section)
7306 section = [sections objectForKey:key];
7307 if (section == nil) {
7308 _profile(SectionsView$reloadData$Section$Allocate)
7309 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7310 [sections setObject:section forKey:key];
7315 [section addToCount];
7317 _profile(SectionsView$reloadData$Filter)
7318 if (![package valid] || ![package visible])
7326 [sections_ addObjectsFromArray:[sections allValues]];
7328 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7330 for (Section *section in sections_) {
7331 size_t count([section row]);
7335 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7336 [section setCount:count];
7337 [filtered_ addObject:section];
7340 [self updateNavigationItem];
7345 - (void) editButtonClicked {
7346 [self setEditing:(!editing_)];
7352 /* Changes Controller {{{ */
7353 @interface ChangesController : CYViewController <
7354 UITableViewDataSource,
7357 _transient Database *database_;
7359 CFMutableArrayRef packages_;
7360 NSMutableArray *sections_;
7363 BOOL hasSentFirstLoad_;
7366 - (id) initWithDatabase:(Database *)database;
7370 @implementation ChangesController
7373 [self releaseSubviews];
7374 CFRelease(packages_);
7375 [sections_ release];
7380 - (NSURL *) navigationURL {
7381 return [NSURL URLWithString:@"cydia://changes"];
7384 - (void) viewWillAppear:(BOOL)animated {
7385 // Loads after it appears, so don't load beforehand.
7387 [super viewWillAppear:animated];
7390 - (void) viewDidAppear:(BOOL)animated {
7391 [super viewDidAppear:animated];
7393 if (!hasSentFirstLoad_) {
7394 hasSentFirstLoad_ = YES;
7395 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7397 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7401 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7402 NSInteger count([sections_ count]);
7403 return count == 0 ? 1 : count;
7406 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7407 if ([sections_ count] == 0)
7409 return [[sections_ objectAtIndex:section] name];
7412 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7413 if ([sections_ count] == 0)
7415 return [[sections_ objectAtIndex:section] count];
7418 - (Package *) packageAtIndex:(NSUInteger)index {
7419 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7422 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7423 @synchronized (database_) {
7424 if ([database_ era] != era_)
7427 NSUInteger sectionIndex([path section]);
7428 if (sectionIndex >= [sections_ count])
7430 Section *section([sections_ objectAtIndex:sectionIndex]);
7431 NSInteger row([path row]);
7432 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7435 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7436 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7438 cell = [[[PackageCell alloc] init] autorelease];
7439 [cell setPackage:[self packageAtIndexPath:path]];
7443 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7444 Package *package([self packageAtIndexPath:path]);
7445 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7446 [view setDelegate:delegate_];
7447 [[self navigationController] pushViewController:view animated:YES];
7451 - (void) refreshButtonClicked {
7452 [delegate_ beginUpdate];
7453 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7456 - (void) upgradeButtonClicked {
7457 [delegate_ distUpgrade];
7461 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7463 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7464 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7465 [list_ setRowHeight:73];
7466 [list_ setDataSource:self];
7467 [list_ setDelegate:self];
7468 [[self view] addSubview:list_];
7471 - (void) viewDidLoad {
7472 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7475 - (void) releaseSubviews {
7480 - (id) initWithDatabase:(Database *)database {
7481 if ((self = [super init]) != nil) {
7482 database_ = database;
7484 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7485 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7489 // this mostly works because reloadData (below) is @synchronized (database_)
7490 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7491 - (void) _reloadPackages:(NSArray *)packages {
7492 CFRelease(packages_);
7493 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7496 _profile(ChangesController$_reloadPackages$Filter)
7497 for (Package *package in packages)
7498 if ([package upgradableAndEssential:YES] || [package visible])
7499 CFArrayAppendValue(packages_, package);
7502 _profile(ChangesController$_reloadPackages$radixSort)
7503 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7508 - (void) reloadData {
7509 @synchronized (database_) {
7510 era_ = [database_ era];
7511 NSArray *packages = [database_ packages];
7513 [sections_ removeAllObjects];
7516 UIProgressHUD *hud([delegate_ addProgressHUD]);
7517 [hud setText:UCLocalize("LOADING")];
7518 //NSLog(@"HUD:%@::%@", delegate_, hud);
7519 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7520 [delegate_ removeProgressHUD:hud];
7522 [self _reloadPackages:packages];
7525 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7526 Section *ignored = nil;
7527 Section *section = nil;
7531 bool unseens = false;
7533 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7535 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7536 Package *package = [self packageAtIndex:offset];
7538 BOOL uae = [package upgradableAndEssential:YES];
7542 time_t seen([package seen]);
7544 if (section == nil || last != seen) {
7548 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7551 _profile(ChangesController$reloadData$Allocate)
7552 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7553 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7554 [sections_ addObject:section];
7558 [section addToCount];
7559 } else if ([package ignored]) {
7560 if (ignored == nil) {
7561 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7563 [ignored addToCount];
7566 [upgradable addToCount];
7571 CFRelease(formatter);
7574 Section *last = [sections_ lastObject];
7575 size_t count = [last count];
7576 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7577 [sections_ removeLastObject];
7580 if ([ignored count] != 0)
7581 [sections_ insertObject:ignored atIndex:0];
7583 [sections_ insertObject:upgradable atIndex:0];
7588 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7589 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7590 style:UIBarButtonItemStylePlain
7592 action:@selector(upgradeButtonClicked)
7595 if (![delegate_ updating])
7596 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7597 initWithTitle:UCLocalize("REFRESH")
7598 style:UIBarButtonItemStylePlain
7600 action:@selector(refreshButtonClicked)
7608 /* Search Controller {{{ */
7609 @interface SearchController : FilteredPackageListController <
7612 _H<UISearchBar> search_;
7616 - (id) initWithDatabase:(Database *)database;
7617 - (void) setSearchTerm:(NSString *)term;
7618 - (void) reloadData;
7622 @implementation SearchController
7625 [search_ setDelegate:nil];
7629 - (NSURL *) navigationURL {
7630 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7631 return [NSURL URLWithString:@"cydia://search"];
7633 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7636 - (void) setSearchTerm:(NSString *)searchTerm {
7637 [search_ setText:searchTerm];
7641 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7642 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7643 [search_ resignFirstResponder];
7647 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7648 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7652 - (id) initWithDatabase:(Database *)database {
7653 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7654 search_ = [[[UISearchBar alloc] init] autorelease];
7655 [search_ setDelegate:self];
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 [textField setEnablesReturnKeyAutomatically:NO];
7676 [[self navigationItem] setTitleView:textField];
7680 - (void) reloadData {
7681 [self setObject:[search_ text]];
7686 - (void) didSelectPackage:(Package *)package {
7687 [search_ resignFirstResponder];
7688 [super didSelectPackage:package];
7693 /* Package Settings Controller {{{ */
7694 @interface PackageSettingsController : CYViewController <
7695 UITableViewDataSource,
7698 _transient Database *database_;
7701 UITableView *table_;
7702 UISwitch *subscribedSwitch_;
7703 UISwitch *ignoredSwitch_;
7704 UITableViewCell *subscribedCell_;
7705 UITableViewCell *ignoredCell_;
7708 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7712 @implementation PackageSettingsController
7715 [self releaseSubviews];
7722 - (NSURL *) navigationURL {
7723 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7726 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7727 if (package_ == nil)
7730 if ([package_ installed] == nil)
7736 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7737 if (package_ == nil)
7740 // both sections contain just one item right now.
7744 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7748 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7750 return UCLocalize("SHOW_ALL_CHANGES_EX");
7752 return UCLocalize("IGNORE_UPGRADES_EX");
7755 - (void) onSubscribed:(id)control {
7756 bool value([control isOn]);
7757 if (package_ == nil)
7759 if ([package_ setSubscribed:value])
7760 [delegate_ updateData];
7763 - (void) _updateIgnored {
7764 const char *package([name_ UTF8String]);
7765 bool on([ignoredSwitch_ isOn]);
7767 pid_t pid(ExecFork());
7769 FILE *dpkg(popen("dpkg --set-selections", "w"));
7770 fwrite(package, strlen(package), 1, dpkg);
7773 fwrite(" hold\n", 6, 1, dpkg);
7775 fwrite(" install\n", 9, 1, dpkg);
7785 int result(waitpid(pid, &status, 0));
7788 _assert(result == pid);
7794 - (void) onIgnored:(id)control {
7795 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7796 [invocation setTarget:self];
7797 [invocation setSelector:@selector(_updateIgnored)];
7799 [delegate_ reloadDataWithInvocation:invocation];
7802 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7803 if (package_ == nil)
7806 switch ([indexPath section]) {
7807 case 0: return subscribedCell_;
7808 case 1: return ignoredCell_;
7817 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7819 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7820 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7821 [table_ setDataSource:self];
7822 [table_ setDelegate:self];
7823 [[self view] addSubview:table_];
7825 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7826 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7827 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7829 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7830 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7831 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7833 subscribedCell_ = [[UITableViewCell alloc] init];
7834 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7835 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7836 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7838 ignoredCell_ = [[UITableViewCell alloc] init];
7839 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7840 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7841 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7844 - (void) viewDidLoad {
7845 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7848 - (void) releaseSubviews {
7849 [ignoredCell_ release];
7852 [subscribedCell_ release];
7853 subscribedCell_ = nil;
7858 [ignoredSwitch_ release];
7859 ignoredSwitch_ = nil;
7861 [subscribedSwitch_ release];
7862 subscribedSwitch_ = nil;
7865 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7866 if ((self = [super init]) != nil) {
7867 database_ = database;
7868 name_ = [package retain];
7872 - (void) reloadData {
7875 if (package_ != nil)
7876 [package_ autorelease];
7877 package_ = [database_ packageWithName:name_];
7879 if (package_ != nil) {
7880 package_ = [package_ retain];
7881 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7882 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7883 } // XXX: what now, G?
7885 [table_ reloadData];
7891 /* Installed Controller {{{ */
7892 @interface InstalledController : FilteredPackageListController {
7896 - (id) initWithDatabase:(Database *)database;
7898 - (void) updateRoleButton;
7899 - (void) queueStatusDidChange;
7903 @implementation InstalledController
7909 - (NSURL *) navigationURL {
7910 return [NSURL URLWithString:@"cydia://installed"];
7913 - (id) initWithDatabase:(Database *)database {
7914 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7915 [self updateRoleButton];
7916 [self queueStatusDidChange];
7921 - (void) queueButtonClicked {
7926 - (void) queueStatusDidChange {
7930 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7931 initWithTitle:UCLocalize("QUEUE")
7932 style:UIBarButtonItemStyleDone
7934 action:@selector(queueButtonClicked)
7937 [[self navigationItem] setLeftBarButtonItem:nil];
7943 - (void) updateRoleButton {
7944 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7945 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7946 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7947 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7949 action:@selector(roleButtonClicked)
7953 - (void) roleButtonClicked {
7954 [self setObject:[NSNumber numberWithBool:expert_]];
7958 [self updateRoleButton];
7964 /* Source Cell {{{ */
7965 @interface SourceCell : CYTableViewCell <
7973 - (void) setSource:(Source *)source;
7977 @implementation SourceCell
7979 - (void) clearSource {
7989 - (void) setSource:(Source *)source {
7993 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7995 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7996 icon_ = [icon_ retain];
7998 origin_ = [[source name] retain];
7999 label_ = [[source uri] retain];
8001 [content_ setNeedsDisplay];
8009 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8010 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8011 UIView *content([self contentView]);
8012 CGRect bounds([content bounds]);
8014 content_ = [[ContentView alloc] initWithFrame:bounds];
8015 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8016 [content_ setBackgroundColor:[UIColor whiteColor]];
8017 [content addSubview:content_];
8019 [content_ setDelegate:self];
8020 [content_ setOpaque:YES];
8024 - (NSString *) accessibilityLabel {
8028 - (void) drawContentRect:(CGRect)rect {
8029 bool highlighted(highlighted_);
8030 float width(rect.size.width);
8033 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8040 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8044 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8049 /* Source Controller {{{ */
8050 @interface SourceController : FilteredPackageListController {
8051 _transient Source *source_;
8055 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8059 @implementation SourceController
8061 - (NSURL *) navigationURL {
8062 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8065 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8066 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8068 key_ = [[source key] retain];
8072 - (void) reloadData {
8073 source_ = [database_ sourceWithKey:key_];
8075 key_ = [[source_ key] retain];
8076 [self setObject:source_];
8077 [[self navigationItem] setTitle:[source_ label]];
8084 /* Sources Controller {{{ */
8085 @interface SourcesController : CYViewController <
8086 UITableViewDataSource,
8089 _transient Database *database_;
8091 NSMutableArray *sources_;
8095 UIProgressHUD *hud_;
8098 //NSURLConnection *installer_;
8099 NSURLConnection *trivial_;
8100 NSURLConnection *trivial_bz2_;
8101 NSURLConnection *trivial_gz_;
8102 //NSURLConnection *automatic_;
8107 - (id) initWithDatabase:(Database *)database;
8108 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8112 @implementation SourcesController
8114 - (void) _releaseConnection:(NSURLConnection *)connection {
8115 if (connection != nil) {
8116 [connection cancel];
8117 //[connection setDelegate:nil];
8118 [connection release];
8123 [self releaseSubviews];
8129 //[self _releaseConnection:installer_];
8130 [self _releaseConnection:trivial_];
8131 [self _releaseConnection:trivial_gz_];
8132 [self _releaseConnection:trivial_bz2_];
8133 //[self _releaseConnection:automatic_];
8139 - (NSURL *) navigationURL {
8140 return [NSURL URLWithString:@"cydia://sources"];
8143 - (void) viewDidAppear:(BOOL)animated {
8144 [super viewDidAppear:animated];
8145 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8148 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8149 return offset_ == 0 ? 1 : 2;
8152 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8153 switch (section + (offset_ == 0 ? 1 : 0)) {
8154 case 0: return UCLocalize("ENTERED_BY_USER");
8155 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8161 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8162 int count = [sources_ count];
8164 case 0: return (offset_ == 0 ? count : offset_);
8165 case 1: return count - offset_;
8171 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8173 switch (indexPath.section) {
8174 case 0: idx = indexPath.row; break;
8175 case 1: idx = indexPath.row + offset_; break;
8179 return [sources_ objectAtIndex:idx];
8182 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8183 static NSString *cellIdentifier = @"SourceCell";
8185 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8186 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8187 [cell setSource:[self sourceAtIndexPath:indexPath]];
8188 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8193 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8194 Source *source = [self sourceAtIndexPath:indexPath];
8196 SourceController *controller = [[[SourceController alloc]
8197 initWithDatabase:database_
8201 [controller setDelegate:delegate_];
8203 [[self navigationController] pushViewController:controller animated:YES];
8206 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8207 Source *source = [self sourceAtIndexPath:indexPath];
8208 return [source record] != nil;
8211 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8212 Source *source = [self sourceAtIndexPath:indexPath];
8213 [Sources_ removeObjectForKey:[source key]];
8214 [delegate_ syncData];
8218 [delegate_ addTrivialSource:href_];
8219 [delegate_ syncData];
8222 - (NSString *) getWarning {
8223 NSString *href(href_);
8224 NSRange colon([href rangeOfString:@"://"]);
8225 if (colon.location != NSNotFound)
8226 href = [href substringFromIndex:(colon.location + 3)];
8227 href = [href stringByAddingPercentEscapes];
8228 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8229 href = [href stringByCachingURLWithCurrentCDN];
8231 NSURL *url([NSURL URLWithString:href]);
8233 NSStringEncoding encoding;
8234 NSError *error(nil);
8236 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8237 return [warning length] == 0 ? nil : warning;
8241 - (void) _endConnection:(NSURLConnection *)connection {
8242 // XXX: the memory management in this method is horribly awkward
8244 NSURLConnection **field = NULL;
8245 if (connection == trivial_)
8247 else if (connection == trivial_bz2_)
8248 field = &trivial_bz2_;
8249 else if (connection == trivial_gz_)
8250 field = &trivial_gz_;
8251 _assert(field != NULL);
8252 [connection release];
8257 trivial_bz2_ == nil &&
8263 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8266 UIAlertView *alert = [[[UIAlertView alloc]
8267 initWithTitle:UCLocalize("SOURCE_WARNING")
8270 cancelButtonTitle:UCLocalize("CANCEL")
8272 UCLocalize("ADD_ANYWAY"),
8276 [alert setContext:@"warning"];
8277 [alert setNumberOfRows:1];
8281 } else if (error_ != nil) {
8282 UIAlertView *alert = [[[UIAlertView alloc]
8283 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8284 message:[error_ localizedDescription]
8286 cancelButtonTitle:UCLocalize("OK")
8287 otherButtonTitles:nil
8290 [alert setContext:@"urlerror"];
8293 UIAlertView *alert = [[[UIAlertView alloc]
8294 initWithTitle:UCLocalize("NOT_REPOSITORY")
8295 message:UCLocalize("NOT_REPOSITORY_EX")
8297 cancelButtonTitle:UCLocalize("OK")
8298 otherButtonTitles:nil
8301 [alert setContext:@"trivial"];
8305 [delegate_ releaseNetworkActivityIndicator];
8307 [delegate_ removeProgressHUD:hud_];
8316 if (error_ != nil) {
8323 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8324 switch ([response statusCode]) {
8330 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8331 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8333 error_ = [error retain];
8334 [self _endConnection:connection];
8337 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8338 [self _endConnection:connection];
8341 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8342 NSMutableURLRequest *request = [NSMutableURLRequest
8343 requestWithURL:[NSURL URLWithString:href]
8344 cachePolicy:NSURLRequestUseProtocolCachePolicy
8345 timeoutInterval:120.0
8348 [request setHTTPMethod:method];
8350 if (Machine_ != NULL)
8351 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8352 if (UniqueID_ != nil)
8353 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8355 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8357 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8360 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8361 NSString *context([alert context]);
8363 if ([context isEqualToString:@"source"]) {
8366 NSString *href = [[alert textField] text];
8368 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8370 if (![href hasSuffix:@"/"])
8371 href_ = [href stringByAppendingString:@"/"];
8374 href_ = [href_ retain];
8376 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8377 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8378 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8379 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8383 // XXX: this is stupid
8384 hud_ = [[delegate_ addProgressHUD] retain];
8385 [hud_ setText:UCLocalize("VERIFYING_URL")];
8386 [delegate_ retainNetworkActivityIndicator];
8395 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8396 } else if ([context isEqualToString:@"trivial"])
8397 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8398 else if ([context isEqualToString:@"urlerror"])
8399 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8400 else if ([context isEqualToString:@"warning"]) {
8415 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8420 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8422 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8423 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8424 [list_ setRowHeight:56];
8425 [list_ setDataSource:self];
8426 [list_ setDelegate:self];
8427 [[self view] addSubview:list_];
8430 - (void) viewDidLoad {
8431 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8432 [self updateButtonsForEditingStatus:NO animated:NO];
8435 - (void) releaseSubviews {
8440 - (id) initWithDatabase:(Database *)database {
8441 if ((self = [super init]) != nil) {
8442 database_ = database;
8443 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8447 - (void) reloadData {
8451 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8454 [sources_ removeAllObjects];
8455 [sources_ addObjectsFromArray:[database_ sources]];
8457 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8460 int count([sources_ count]);
8462 for (int i = 0; i != count; i++) {
8463 if ([[sources_ objectAtIndex:i] record] == nil)
8468 [list_ setEditing:NO];
8469 [self updateButtonsForEditingStatus:NO animated:NO];
8473 - (void) showAddSourcePrompt {
8474 UIAlertView *alert = [[[UIAlertView alloc]
8475 initWithTitle:UCLocalize("ENTER_APT_URL")
8478 cancelButtonTitle:UCLocalize("CANCEL")
8480 UCLocalize("ADD_SOURCE"),
8484 [alert setContext:@"source"];
8485 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8487 [alert setNumberOfRows:1];
8488 [alert addTextFieldWithValue:@"http://" label:@""];
8490 UITextInputTraits *traits = [[alert textField] textInputTraits];
8491 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8492 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8493 [traits setKeyboardType:UIKeyboardTypeURL];
8494 // XXX: UIReturnKeyDone
8495 [traits setReturnKeyType:UIReturnKeyNext];
8500 - (void) addButtonClicked {
8501 [self showAddSourcePrompt];
8504 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8505 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8506 initWithTitle:UCLocalize("ADD")
8507 style:UIBarButtonItemStylePlain
8509 action:@selector(addButtonClicked)
8510 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8512 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8513 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8514 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8516 action:@selector(editButtonClicked)
8517 ] autorelease] animated:animated];
8519 if (IsWildcat_ && !editing)
8520 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8521 initWithTitle:UCLocalize("SETTINGS")
8522 style:UIBarButtonItemStylePlain
8524 action:@selector(settingsButtonClicked)
8528 - (void) settingsButtonClicked {
8529 [delegate_ showSettings];
8532 - (void) editButtonClicked {
8533 [list_ setEditing:![list_ isEditing] animated:YES];
8535 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8541 /* Settings Controller {{{ */
8542 @interface SettingsController : CYViewController <
8543 UITableViewDataSource,
8546 _transient Database *database_;
8547 // XXX: ok, "roledelegate_"?...
8548 _transient id roledelegate_;
8549 UITableView *table_;
8550 UISegmentedControl *segment_;
8554 - (void) showDoneButton;
8555 - (void) resizeSegmentedControl;
8559 @implementation SettingsController
8562 [self releaseSubviews];
8568 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8570 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8571 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8572 [table_ setDelegate:self];
8573 [table_ setDataSource:self];
8574 [[self view] addSubview:table_];
8576 NSArray *items = [NSArray arrayWithObjects:
8578 UCLocalize("HACKER"),
8579 UCLocalize("DEVELOPER"),
8581 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8582 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8583 [container_ addSubview:segment_];
8586 - (void) viewDidLoad {
8587 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8590 if ([Role_ isEqualToString:@"User"]) index = 0;
8591 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8592 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8594 [segment_ setSelectedSegmentIndex:index];
8595 [self showDoneButton];
8598 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8599 [self resizeSegmentedControl];
8602 - (void) releaseSubviews {
8609 [container_ release];
8613 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8614 if ((self = [super init]) != nil) {
8615 database_ = database;
8616 roledelegate_ = delegate;
8620 - (void) resizeSegmentedControl {
8621 CGFloat width = [[self view] frame].size.width;
8622 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8625 - (void) viewWillAppear:(BOOL)animated {
8626 [super viewWillAppear:animated];
8628 [self resizeSegmentedControl];
8631 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8632 [self resizeSegmentedControl];
8635 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8636 [self resizeSegmentedControl];
8640 NSString *role(nil);
8642 switch ([segment_ selectedSegmentIndex]) {
8643 case 0: role = @"User"; break;
8644 case 1: role = @"Hacker"; break;
8645 case 2: role = @"Developer"; break;
8650 if (![role isEqualToString:Role_]) {
8651 bool rolling(Role_ == nil);
8654 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8658 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8662 [roledelegate_ loadData];
8664 [roledelegate_ updateData];
8668 - (void) segmentChanged:(UISegmentedControl *)control {
8669 [self showDoneButton];
8672 - (void) saveAndClose {
8675 [[self navigationItem] setRightBarButtonItem:nil];
8676 [[self navigationController] dismissModalViewControllerAnimated:YES];
8679 - (void) doneButtonClicked {
8680 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8681 [spinner startAnimating];
8682 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8683 [[self navigationItem] setRightBarButtonItem:spinItem];
8685 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8688 - (void) showDoneButton {
8689 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8690 initWithTitle:UCLocalize("DONE")
8691 style:UIBarButtonItemStyleDone
8693 action:@selector(doneButtonClicked)
8694 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8697 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8698 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8702 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8706 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8707 return nil; // This method is required by the protocol.
8710 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8712 return UCLocalize("ROLE_EX");
8714 return [NSString stringWithFormat:
8715 @"%@: %@\n%@: %@\n%@: %@",
8716 UCLocalize("USER"), UCLocalize("USER_EX"),
8717 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8718 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8723 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8724 return section == 3 ? 44.0f : 0;
8727 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8728 return section == 3 ? container_ : nil;
8731 - (void) reloadData {
8733 [table_ reloadData];
8738 /* Stash Controller {{{ */
8739 @interface StashController : CYViewController {
8740 UIActivityIndicatorView *spinner_;
8747 @implementation StashController
8750 [self releaseSubviews];
8756 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8757 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8759 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8760 CGRect spinrect = [spinner_ frame];
8761 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8762 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8763 [spinner_ setFrame:spinrect];
8764 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8765 [[self view] addSubview:spinner_];
8766 [spinner_ startAnimating];
8769 captrect.size.width = [[self view] frame].size.width;
8770 captrect.size.height = 40.0f;
8771 captrect.origin.x = 0;
8772 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8773 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8774 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8775 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8776 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8777 [caption_ setTextColor:[UIColor whiteColor]];
8778 [caption_ setBackgroundColor:[UIColor clearColor]];
8779 [caption_ setShadowColor:[UIColor blackColor]];
8780 [caption_ setTextAlignment:UITextAlignmentCenter];
8781 [[self view] addSubview:caption_];
8784 statusrect.size.width = [[self view] frame].size.width;
8785 statusrect.size.height = 30.0f;
8786 statusrect.origin.x = 0;
8787 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8788 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8789 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8790 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8791 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8792 [status_ setTextColor:[UIColor whiteColor]];
8793 [status_ setBackgroundColor:[UIColor clearColor]];
8794 [status_ setShadowColor:[UIColor blackColor]];
8795 [status_ setTextAlignment:UITextAlignmentCenter];
8796 [[self view] addSubview:status_];
8799 - (void) releaseSubviews {
8813 @interface Cydia : UIApplication <
8814 ConfirmationControllerDelegate,
8817 UINavigationControllerDelegate,
8818 UITabBarControllerDelegate
8820 // XXX: evaluate all fields for _transient
8823 CYTabBarController *tabbar_;
8824 CYEmulatedLoadingController *emulated_;
8826 NSMutableArray *essential_;
8827 NSMutableArray *broken_;
8829 Database *database_;
8836 StashController *stash_;
8845 @implementation Cydia
8847 - (void) beginUpdate {
8848 [tabbar_ beginUpdate];
8852 return [tabbar_ updating];
8856 if ([broken_ count] != 0) {
8857 int count = [broken_ count];
8859 UIAlertView *alert = [[[UIAlertView alloc]
8860 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8861 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8863 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8865 UCLocalize("TEMPORARY_IGNORE"),
8869 [alert setContext:@"fixhalf"];
8870 [alert setNumberOfRows:2];
8872 } else if (!Ignored_ && [essential_ count] != 0) {
8873 int count = [essential_ count];
8875 UIAlertView *alert = [[[UIAlertView alloc]
8876 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8877 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8879 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8881 UCLocalize("UPGRADE_ESSENTIAL"),
8882 UCLocalize("COMPLETE_UPGRADE"),
8886 [alert setContext:@"upgrade"];
8891 - (void) _saveConfig {
8897 NSString *error(nil);
8899 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8901 NSError *error(nil);
8902 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8903 NSLog(@"failure to save metadata data: %@", error);
8908 NSLog(@"failure to serialize metadata: %@", error);
8913 // Navigation controller for the queuing badge.
8914 - (CYNavigationController *) queueNavigationController {
8915 NSArray *controllers = [tabbar_ viewControllers];
8916 return [controllers objectAtIndex:3];
8919 - (void) _updateData {
8922 [tabbar_ reloadData];
8924 CYNavigationController *navigation = [self queueNavigationController];
8926 id queuedelegate = nil;
8927 if ([[navigation viewControllers] count] > 0)
8928 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8930 [queuedelegate queueStatusDidChange];
8931 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8934 - (void) _refreshIfPossible:(NSDate *)update {
8935 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8937 bool recently = false;
8938 if (update != nil) {
8939 NSTimeInterval interval([update timeIntervalSinceNow]);
8940 if (interval <= 0 && interval > -(15*60))
8944 // Don't automatic refresh if:
8945 // - We already refreshed recently.
8946 // - We already auto-refreshed this launch.
8947 // - Auto-refresh is disabled.
8948 if (recently || loaded_ || ManualRefresh) {
8949 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8951 // If we are cancelling, we need to make sure it knows it's already loaded.
8955 // We are going to load, so remember that.
8959 SCNetworkReachabilityFlags flags; {
8960 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8961 SCNetworkReachabilityGetFlags(reachability, &flags);
8962 CFRelease(reachability);
8965 // XXX: this elaborate mess is what Apple is using to determine this? :(
8966 // XXX: do we care if the user has to intervene? maybe that's ok?
8968 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8969 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8970 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8971 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8972 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8973 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8977 // If we can reach the server, auto-refresh!
8979 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8984 - (void) refreshIfPossible {
8985 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8988 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8989 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8990 [hud setText:UCLocalize("RELOADING_DATA")];
8992 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8995 [self removeProgressHUD:hud];
8999 [essential_ removeAllObjects];
9000 [broken_ removeAllObjects];
9002 NSArray *packages([database_ packages]);
9003 for (Package *package in packages) {
9005 [broken_ addObject:package];
9006 if ([package upgradableAndEssential:NO]) {
9007 if ([package essential])
9008 [essential_ addObject:package];
9013 NSLog(@"changes:#%u", changes);
9015 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9018 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9019 [changesItem setBadgeValue:badge];
9020 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9021 [self setApplicationIconBadgeNumber:changes];
9024 [changesItem setBadgeValue:nil];
9025 [changesItem setAnimatedBadge:NO];
9026 [self setApplicationIconBadgeNumber:0];
9031 [self refreshIfPossible];
9034 - (void) updateData {
9043 @synchronized (self) {
9044 [self _reloadDataWithInvocation:nil];
9048 - (void) disemulate {
9049 if (emulated_ == nil)
9052 [window_ addSubview:[tabbar_ view]];
9053 [[emulated_ view] removeFromSuperview];
9054 [emulated_ release];
9056 [window_ setUserInteractionEnabled:YES];
9059 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9060 UINavigationController *navigation([[[CYNavigationController alloc] initWithRootViewController:controller] autorelease]);
9062 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9064 UIViewController *parent;
9065 if (emulated_ == nil)
9074 [parent presentModalViewController:navigation animated:YES];
9077 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9078 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9080 if (navigation != nil)
9081 [navigation pushViewController:progress animated:YES];
9083 [self presentModalViewController:progress force:YES];
9085 [progress invoke:invocation withTitle:title];
9089 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9090 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9093 - (void) repairWithInvocation:(NSInvocation *)invocation {
9095 [self invokeNewProgress:invocation forController:nil withTitle:UCLocalize("REPAIRING")];
9099 - (void) repairWithSelector:(SEL)selector {
9100 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9106 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9107 _assert(file != NULL);
9109 for (NSString *key in [Sources_ allKeys]) {
9110 NSDictionary *source([Sources_ objectForKey:key]);
9112 fprintf(file, "%s %s %s\n",
9113 [[source objectForKey:@"Type"] UTF8String],
9114 [[source objectForKey:@"URI"] UTF8String],
9115 [[source objectForKey:@"Distribution"] UTF8String]
9121 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:UCLocalize("UPDATING_SOURCES")];
9126 - (void) addTrivialSource:(NSString *)href {
9127 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9130 @"./", @"Distribution",
9131 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9136 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9137 @synchronized (self) {
9138 [self _reloadDataWithInvocation:invocation];
9142 - (void) reloadData {
9143 [self reloadDataWithInvocation:nil];
9147 pkgProblemResolver *resolver = [database_ resolver];
9149 resolver->InstallProtect();
9150 if (!resolver->Resolve(true))
9155 // XXX: this is a really crappy way of doing this.
9156 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9157 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9158 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9159 if ([tabbar_ updating])
9160 [tabbar_ cancelUpdate];
9162 if (![database_ prepare])
9165 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9166 [page setDelegate:self];
9167 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
9168 [confirm_ setDelegate:self];
9171 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9172 [tabbar_ presentModalViewController:confirm_ animated:YES];
9178 @synchronized (self) {
9183 - (void) clearPackage:(Package *)package {
9184 @synchronized (self) {
9191 - (void) installPackages:(NSArray *)packages {
9192 @synchronized (self) {
9193 for (Package *package in packages)
9200 - (void) installPackage:(Package *)package {
9201 @synchronized (self) {
9208 - (void) removePackage:(Package *)package {
9209 @synchronized (self) {
9216 - (void) distUpgrade {
9217 @synchronized (self) {
9218 if (![database_ upgrade])
9224 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9227 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:UCLocalize("RUNNING")];
9232 - (void) showSettings {
9233 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9234 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9236 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9237 [tabbar_ presentModalViewController:nav animated:YES];
9240 - (void) retainNetworkActivityIndicator {
9241 if (activity_++ == 0)
9242 [self setNetworkActivityIndicatorVisible:YES];
9245 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9249 - (void) releaseNetworkActivityIndicator {
9250 if (--activity_ == 0)
9251 [self setNetworkActivityIndicatorVisible:NO];
9254 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9259 - (void) cancelAndClear:(bool)clear {
9260 @synchronized (self) {
9272 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9273 NSString *context([alert context]);
9275 if ([context isEqualToString:@"conffile"]) {
9276 FILE *input = [database_ input];
9277 if (button == [alert cancelButtonIndex])
9278 fprintf(input, "N\n");
9279 else if (button == [alert firstOtherButtonIndex])
9280 fprintf(input, "Y\n");
9283 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9284 } else if ([context isEqualToString:@"fixhalf"]) {
9285 if (button == [alert cancelButtonIndex]) {
9286 @synchronized (self) {
9287 for (Package *broken in broken_) {
9290 NSString *id = [broken id];
9291 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9292 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9293 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9294 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9300 } else if (button == [alert firstOtherButtonIndex]) {
9301 [broken_ removeAllObjects];
9305 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9306 } else if ([context isEqualToString:@"upgrade"]) {
9307 if (button == [alert firstOtherButtonIndex]) {
9308 @synchronized (self) {
9309 for (Package *essential in essential_)
9310 [essential install];
9315 } else if (button == [alert firstOtherButtonIndex] + 1) {
9317 } else if (button == [alert cancelButtonIndex]) {
9321 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9325 - (void) system:(NSString *)command { _pooled
9327 system([command UTF8String]);
9331 - (void) applicationWillSuspend {
9333 [super applicationWillSuspend];
9336 - (BOOL) isSafeToSuspend {
9337 // Use external process status API internally.
9338 // This is probably a really bad idea.
9339 // XXX: what is the point of this? does this solve anything at all?
9340 uint64_t status = 0;
9342 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9343 notify_get_state(notify_token, &status);
9344 notify_cancel(notify_token);
9347 return locked_ == 0 && status == 0;
9350 - (void) applicationSuspend:(__GSEvent *)event {
9351 if ([self isSafeToSuspend])
9352 [super applicationSuspend:event];
9355 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9356 if ([self isSafeToSuspend])
9357 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9360 - (void) _setSuspended:(BOOL)value {
9361 if ([self isSafeToSuspend])
9362 [super _setSuspended:value];
9365 - (UIProgressHUD *) addProgressHUD {
9366 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9367 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9369 [window_ setUserInteractionEnabled:NO];
9372 UIViewController *target = tabbar_;
9373 while ([target modalViewController] != nil) target = [target modalViewController];
9374 [[target view] addSubview:hud];
9380 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9382 [hud removeFromSuperview];
9383 [window_ setUserInteractionEnabled:YES];
9387 - (CYViewController *) pageForPackage:(NSString *)name {
9388 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9391 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9392 NSString *scheme([[url scheme] lowercaseString]);
9393 if ([[url absoluteString] length] <= [scheme length] + 3)
9395 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9396 NSArray *components([path pathComponents]);
9398 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9399 return [self pageForPackage:[components objectAtIndex:1]];
9401 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9404 NSString *base([components objectAtIndex:0]);
9406 CYViewController *controller = nil;
9408 if ([base isEqualToString:@"url"]) {
9409 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9410 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9411 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9412 } else if (!external && [components count] == 1) {
9413 if ([base isEqualToString:@"manage"]) {
9414 controller = [[[ManageController alloc] init] autorelease];
9417 if ([base isEqualToString:@"sources"]) {
9418 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9421 if ([base isEqualToString:@"home"]) {
9422 controller = [[[HomeController alloc] init] autorelease];
9425 if ([base isEqualToString:@"sections"]) {
9426 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9429 if ([base isEqualToString:@"search"]) {
9430 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9433 if ([base isEqualToString:@"changes"]) {
9434 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9437 if ([base isEqualToString:@"installed"]) {
9438 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9440 } else if ([components count] == 2) {
9441 NSString *argument = [components objectAtIndex:1];
9443 if ([base isEqualToString:@"package"]) {
9444 controller = [self pageForPackage:argument];
9447 if (!external && [base isEqualToString:@"search"]) {
9448 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9449 [(SearchController *)controller setSearchTerm:argument];
9452 if (!external && [base isEqualToString:@"sections"]) {
9453 if ([argument isEqualToString:@"all"])
9455 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9458 if (!external && [base isEqualToString:@"sources"]) {
9459 if ([argument isEqualToString:@"add"]) {
9460 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9461 [(SourcesController *)controller showAddSourcePrompt];
9463 Source *source = [database_ sourceWithKey:argument];
9464 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9468 if (!external && [base isEqualToString:@"launch"]) {
9469 [self launchApplicationWithIdentifier:argument suspended:NO];
9472 } else if (!external && [components count] == 3) {
9473 NSString *arg1 = [components objectAtIndex:1];
9474 NSString *arg2 = [components objectAtIndex:2];
9476 if ([base isEqualToString:@"package"]) {
9477 if ([arg2 isEqualToString:@"settings"]) {
9478 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9479 } else if ([arg2 isEqualToString:@"files"]) {
9480 if (Package *package = [database_ packageWithName:arg1]) {
9481 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9482 [(FileTable *)controller setPackage:package];
9488 [controller setDelegate:self];
9492 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9493 CYViewController *page([self pageForURL:url forExternal:external]);
9496 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9497 [nav setViewControllers:[NSArray arrayWithObject:page]];
9498 [tabbar_ setUnselectedViewController:nav];
9504 - (void) applicationOpenURL:(NSURL *)url {
9505 [super applicationOpenURL:url];
9507 if (!loaded_) starturl_ = [url retain];
9508 else [self openCydiaURL:url forExternal:YES];
9511 - (void) applicationWillResignActive:(UIApplication *)application {
9512 // Stop refreshing if you get a phone call or lock the device.
9513 if ([tabbar_ updating])
9514 [tabbar_ cancelUpdate];
9516 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9517 [super applicationWillResignActive:application];
9520 - (void) applicationWillTerminate:(UIApplication *)application {
9522 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9523 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9524 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9529 - (void) setConfigurationData:(NSString *)data {
9530 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9532 if (!conffile_r(data)) {
9533 lprintf("E:invalid conffile\n");
9537 NSString *ofile = conffile_r[1];
9538 //NSString *nfile = conffile_r[2];
9540 UIAlertView *alert = [[[UIAlertView alloc]
9541 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9542 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9544 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9546 UCLocalize("ACCEPT_NEW_COPY"),
9547 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9551 [alert setContext:@"conffile"];
9552 [alert setNumberOfRows:2];
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);
9918 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];
9956 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9957 alloc_ = alloc->method_imp;
9958 alloc->method_imp = (IMP) &Alloc_;*/
9960 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9961 dealloc_ = dealloc->method_imp;
9962 dealloc->method_imp = (IMP) &Dealloc_;*/
9964 /* System Information {{{ */
9968 size = sizeof(maxproc);
9969 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9970 perror("sysctlbyname(\"kern.maxproc\", ?)");
9971 else if (maxproc < 64) {
9973 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9974 perror("sysctlbyname(\"kern.maxproc\", #)");
9977 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9978 char *osversion = new char[size];
9979 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9980 perror("sysctlbyname(\"kern.osversion\", ?)");
9982 System_ = [NSString stringWithUTF8String:osversion];
9984 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9985 char *machine = new char[size];
9986 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9987 perror("sysctlbyname(\"hw.machine\", ?)");
9991 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9992 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9993 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9994 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9998 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9999 NSData *data((NSData *) ecid);
10000 size_t length([data length]);
10001 uint8_t bytes[length];
10002 [data getBytes:bytes];
10003 char string[length * 2 + 1];
10004 for (size_t i(0); i != length; ++i)
10005 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10006 ChipID_ = [NSString stringWithUTF8String:string];
10010 IOObjectRelease(service);
10014 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10016 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10017 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10018 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10020 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10021 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10022 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10024 if (mcc != NULL && mnc != NULL)
10025 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10032 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10033 Build_ = [system objectForKey:@"ProductBuildVersion"];
10034 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10035 Product_ = [info objectForKey:@"SafariProductVersion"];
10036 Safari_ = [info objectForKey:@"CFBundleVersion"];
10039 /* Load Database {{{ */
10041 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10043 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10045 if (Metadata_ == NULL)
10046 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10048 Settings_ = [Metadata_ objectForKey:@"Settings"];
10050 Packages_ = [Metadata_ objectForKey:@"Packages"];
10051 Sections_ = [Metadata_ objectForKey:@"Sections"];
10052 Sources_ = [Metadata_ objectForKey:@"Sources"];
10054 Token_ = [Metadata_ objectForKey:@"Token"];
10057 if (Settings_ != nil)
10058 Role_ = [Settings_ objectForKey:@"Role"];
10060 if (Sections_ == nil) {
10061 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10062 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10065 if (Sources_ == nil) {
10066 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10067 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10072 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10075 if (Packages_ != nil) {
10077 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10081 [Metadata_ removeObjectForKey:@"Packages"];
10087 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10089 #define MobileSubstrate_(name) \
10090 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10091 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10092 if (handle == NULL) \
10093 NSLog(@"%s", dlerror()); \
10096 MobileSubstrate_(Activator)
10097 MobileSubstrate_(libstatusbar)
10098 MobileSubstrate_(SimulatedKeyEvents)
10099 MobileSubstrate_(WinterBoard)
10101 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10102 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10104 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10106 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10107 unlink("/tmp/.cydia.fw");
10109 } else if (access("/User", F_OK) != 0 || version < 4) {
10112 system("/usr/libexec/cydia/firmware.sh");
10116 _assert([[NSFileManager defaultManager]
10117 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10118 withIntermediateDirectories:YES
10123 if (access("/tmp/cydia.chk", F_OK) == 0) {
10124 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10125 _assert(errno == ENOENT);
10126 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10127 _assert(errno == ENOENT);
10130 /* APT Initialization {{{ */
10131 _assert(pkgInitConfig(*_config));
10132 _assert(pkgInitSystem(*_config, _system));
10135 _config->Set("APT::Acquire::Translation", lang);
10137 // XXX: this timeout might be important :(
10138 //_config->Set("Acquire::http::Timeout", 15);
10140 _config->Set("Acquire::http::MaxParallel", 3);
10142 /* Color Choices {{{ */
10143 space_ = CGColorSpaceCreateDeviceRGB();
10145 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10146 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10147 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10148 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10149 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10150 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10151 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10152 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10153 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10155 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10156 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10158 /* UIKit Configuration {{{ */
10159 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10160 if ($GSFontSetUseLegacyFontMetrics != NULL)
10161 $GSFontSetUseLegacyFontMetrics(YES);
10163 // XXX: I have a feeling this was important
10164 //UIKeyboardDisableAutomaticAppearance();
10167 Colon_ = UCLocalize("COLON_DELIMITED");
10168 Elision_ = UCLocalize("ELISION");
10169 Error_ = UCLocalize("ERROR");
10170 Warning_ = UCLocalize("WARNING");
10173 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10175 CGColorSpaceRelease(space_);
10176 CFRelease(Locale_);