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 NSString *authority_;
1644 CYString defaultIcon_;
1646 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();
1691 if (record_ != nil) {
1701 if (authority_ != nil) {
1702 [authority_ release];
1708 // XXX: this is a very inefficient way to call these deconstructors
1713 + (NSArray *) _attributeKeys {
1714 return [NSArray arrayWithObjects:
1729 - (NSArray *) attributeKeys {
1730 return [[self class] _attributeKeys];
1733 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1734 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1737 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1740 trusted_ = index->IsTrusted();
1742 uri_.set(pool, index->GetURI());
1743 distribution_.set(pool, index->GetDist());
1744 type_.set(pool, index->GetType());
1746 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1747 if (dindex != NULL) {
1749 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1752 pkgTagFile tags(&fd);
1754 pkgTagSection section;
1761 {"default-icon", &defaultIcon_},
1762 {"depiction", &depiction_},
1763 {"description", &description_},
1765 {"origin", &origin_},
1766 {"support", &support_},
1767 {"version", &version_},
1770 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1771 const char *start, *end;
1773 if (section.Find(names[i].name_, start, end)) {
1774 CYString &value(*names[i].value_);
1775 value.set(pool, start, end - start);
1781 record_ = [Sources_ objectForKey:[self key]];
1783 record_ = [record_ retain];
1785 NSURL *url([NSURL URLWithString:uri_]);
1789 host_ = [[host_ lowercaseString] retain];
1794 authority_ = [url path];
1796 if (authority_ != nil)
1797 authority_ = [authority_ retain];
1800 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1801 if ((self = [super init]) != nil) {
1802 [self setMetaIndex:index inPool:pool];
1806 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1807 NSDictionary *lhr = [self record];
1808 NSDictionary *rhr = [source record];
1811 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1813 NSString *lhs = [self name];
1814 NSString *rhs = [source name];
1816 if ([lhs length] != 0 && [rhs length] != 0) {
1817 unichar lhc = [lhs characterAtIndex:0];
1818 unichar rhc = [rhs characterAtIndex:0];
1820 if (isalpha(lhc) && !isalpha(rhc))
1821 return NSOrderedAscending;
1822 else if (!isalpha(lhc) && isalpha(rhc))
1823 return NSOrderedDescending;
1826 return [lhs compare:rhs options:LaxCompareOptions_];
1829 - (NSString *) depictionForPackage:(NSString *)package {
1830 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1833 - (NSString *) supportForPackage:(NSString *)package {
1834 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1837 - (NSDictionary *) record {
1845 - (NSString *) uri {
1849 - (NSString *) distribution {
1850 return distribution_;
1853 - (NSString *) type {
1857 - (NSString *) key {
1858 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1861 - (NSString *) host {
1865 - (NSString *) name {
1866 return origin_.empty() ? authority_ : origin_;
1869 - (NSString *) description {
1870 return description_;
1873 - (NSString *) label {
1874 return label_.empty() ? authority_ : label_;
1877 - (NSString *) origin {
1881 - (NSString *) version {
1885 - (NSString *) defaultIcon {
1886 return defaultIcon_;
1891 /* CydiaOperation Class {{{ */
1892 @interface CydiaOperation : NSObject {
1893 NSString *operator_;
1897 - (NSString *) operator;
1898 - (NSString *) value;
1902 @implementation CydiaOperation
1905 [operator_ release];
1910 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1911 if ((self = [super init]) != nil) {
1912 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1913 value_ = [[NSString alloc] initWithUTF8String:value];
1917 + (NSArray *) _attributeKeys {
1918 return [NSArray arrayWithObjects:
1924 - (NSArray *) attributeKeys {
1925 return [[self class] _attributeKeys];
1928 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1929 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1932 - (NSString *) operator {
1936 - (NSString *) value {
1942 /* CydiaClause Class {{{ */
1943 @interface CydiaClause : NSObject {
1945 CydiaOperation *version_;
1948 - (NSString *) package;
1949 - (CydiaOperation *) version;
1953 @implementation CydiaClause
1961 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1962 if ((self = [super init]) != nil) {
1963 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1965 if (const char *version = dep.TargetVer())
1966 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1968 version_ = [[NSNull null] retain];
1972 + (NSArray *) _attributeKeys {
1973 return [NSArray arrayWithObjects:
1979 - (NSArray *) attributeKeys {
1980 return [[self class] _attributeKeys];
1983 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1984 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1987 - (NSString *) package {
1991 - (CydiaOperation *) version {
1997 /* CydiaRelation Class {{{ */
1998 @interface CydiaRelation : NSObject {
1999 NSString *relationship_;
2000 NSMutableArray *clauses_;
2003 - (NSString *) relationship;
2004 - (NSArray *) clauses;
2008 @implementation CydiaRelation
2011 [relationship_ release];
2016 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2017 if ((self = [super init]) != nil) {
2018 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
2019 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
2021 pkgCache::DepIterator start;
2022 pkgCache::DepIterator end;
2023 dep.GlobOr(start, end); // ++dep
2026 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2028 // yes, seriously. (wtf?)
2036 + (NSArray *) _attributeKeys {
2037 return [NSArray arrayWithObjects:
2043 - (NSArray *) attributeKeys {
2044 return [[self class] _attributeKeys];
2047 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2048 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2051 - (NSString *) relationship {
2052 return relationship_;
2055 - (NSArray *) clauses {
2059 - (void) addClause:(CydiaClause *)clause {
2060 [clauses_ addObject:clause];
2065 /* Package Class {{{ */
2066 struct ParsedPackage {
2071 CYString depiction_;
2081 @interface Package : NSObject {
2084 uint32_t essential_ : 1;
2085 uint32_t obsolete_ : 1;
2086 uint32_t ignored_ : 1;
2090 _transient Database *database_;
2092 pkgCache::VerIterator version_;
2093 pkgCache::PkgIterator iterator_;
2094 pkgCache::VerFileIterator file_;
2100 CYString installed_;
2102 const char *section_;
2103 _transient NSString *section$_;
2107 PackageValue *metadata_;
2108 ParsedPackage *parsed_;
2110 NSMutableArray *tags_;
2113 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2114 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2116 - (pkgCache::PkgIterator) iterator;
2119 - (NSString *) section;
2120 - (NSString *) simpleSection;
2122 - (NSString *) longSection;
2123 - (NSString *) shortSection;
2127 - (Address *) maintainer;
2129 - (NSString *) longDescription;
2130 - (NSString *) shortDescription;
2133 - (PackageValue *) metadata;
2136 - (bool) subscribed;
2137 - (bool) setSubscribed:(bool)subscribed;
2141 - (NSString *) latest;
2142 - (NSString *) installed;
2143 - (BOOL) uninstalled;
2146 - (BOOL) upgradableAndEssential:(BOOL)essential;
2149 - (BOOL) unfiltered;
2153 - (BOOL) halfConfigured;
2154 - (BOOL) halfInstalled;
2156 - (NSString *) mode;
2159 - (NSString *) name;
2161 - (NSString *) homepage;
2162 - (NSString *) depiction;
2163 - (Address *) author;
2165 - (NSString *) support;
2167 - (NSArray *) files;
2168 - (NSArray *) warnings;
2169 - (NSArray *) applications;
2171 - (Source *) source;
2173 - (BOOL) matches:(NSString *)text;
2175 - (bool) hasSupportingRole;
2176 - (BOOL) hasTag:(NSString *)tag;
2177 - (NSString *) primaryPurpose;
2178 - (NSArray *) purposes;
2179 - (bool) isCommercial;
2181 - (void) setIndex:(size_t)index;
2183 - (CYString &) cyname;
2185 - (uint32_t) compareBySection:(NSArray *)sections;
2190 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2191 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2192 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2193 - (bool) isVisibleInSection:(NSString *)section;
2194 - (bool) isVisibleInSource:(Source *)source;
2198 uint32_t PackageChangesRadix(Package *self, void *) {
2203 uint32_t timestamp : 30;
2204 uint32_t ignored : 1;
2205 uint32_t upgradable : 1;
2209 bool upgradable([self upgradableAndEssential:YES]);
2210 value.bits.upgradable = upgradable ? 1 : 0;
2213 value.bits.timestamp = 0;
2214 value.bits.ignored = [self ignored] ? 0 : 1;
2215 value.bits.upgradable = 1;
2217 value.bits.timestamp = [self seen] >> 2;
2218 value.bits.ignored = 0;
2219 value.bits.upgradable = 0;
2222 return _not(uint32_t) - value.key;
2225 uint32_t PackagePrefixRadix(Package *self, void *context) {
2226 size_t offset(reinterpret_cast<size_t>(context));
2227 CYString &name([self cyname]);
2229 size_t size(name.size());
2232 char *text(name.data());
2235 if (!isdigit(text[0]))
2239 while (size != digits && isdigit(text[digits]))
2247 if (offset == 0 && zeros != 0) {
2248 memset(data, '0', zeros);
2249 memcpy(data + zeros, text, 4 - zeros);
2251 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2252 if (size <= offset - zeros)
2255 text += offset - zeros;
2256 size -= offset - zeros;
2259 memcpy(data, text, 4);
2261 memcpy(data, text, size);
2262 memset(data + size, 0, 4 - size);
2265 for (size_t i(0); i != 4; ++i)
2266 if (isalpha(data[i]))
2274 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2276 /* XXX: ntohl may be more honest */
2277 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2280 CYString &(*PackageName)(Package *self, SEL sel);
2282 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2283 _profile(PackageNameCompare)
2284 CYString &lhi(PackageName(lhs, @selector(cyname)));
2285 CYString &rhi(PackageName(rhs, @selector(cyname)));
2286 CFStringRef lhn(lhi), rhn(rhi);
2289 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2290 else if (rhn == NULL)
2291 return NSOrderedDescending;
2293 _profile(PackageNameCompare$NumbersLast)
2294 if (!lhi.empty() && !rhi.empty()) {
2295 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2296 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2297 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2298 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2299 return lha ? NSOrderedAscending : NSOrderedDescending;
2303 CFIndex length = CFStringGetLength(lhn);
2305 _profile(PackageNameCompare$Compare)
2306 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2311 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2312 return PackageNameCompare(*lhs, *rhs, context);
2315 struct PackageNameOrdering :
2316 std::binary_function<Package *, Package *, bool>
2318 _finline bool operator ()(Package *lhs, Package *rhs) const {
2319 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2323 @implementation Package
2325 - (NSString *) description {
2326 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2330 if (parsed_ != NULL)
2339 + (NSString *) webScriptNameForSelector:(SEL)selector {
2341 else if (selector == @selector(clear))
2343 else if (selector == @selector(getField:))
2345 else if (selector == @selector(hasTag:))
2347 else if (selector == @selector(install))
2349 else if (selector == @selector(remove))
2355 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2356 return [self webScriptNameForSelector:selector] == nil;
2359 + (NSArray *) _attributeKeys {
2360 return [NSArray arrayWithObjects:
2378 @"shortDescription",
2389 - (NSArray *) attributeKeys {
2390 return [[self class] _attributeKeys];
2393 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2394 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2397 - (NSArray *) relations {
2398 @synchronized (database_) {
2399 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2400 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2401 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2405 - (NSString *) getField:(NSString *)name {
2406 @synchronized (database_) {
2407 if ([database_ era] != era_ || file_.end())
2410 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2412 const char *start, *end;
2413 if (!parser.Find([name UTF8String], start, end))
2414 return (NSString *) [NSNull null];
2416 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2420 if (parsed_ != NULL)
2422 @synchronized (database_) {
2423 if ([database_ era] != era_ || file_.end())
2426 ParsedPackage *parsed(new ParsedPackage);
2429 _profile(Package$parse)
2430 pkgRecords::Parser *parser;
2432 _profile(Package$parse$Lookup)
2433 parser = &[database_ records]->Lookup(file_);
2438 _profile(Package$parse$Find)
2443 {"icon", &parsed->icon_},
2444 {"depiction", &parsed->depiction_},
2445 {"homepage", &parsed->homepage_},
2446 {"website", &website},
2447 {"bugs", &parsed->bugs_},
2448 {"support", &parsed->support_},
2449 {"sponsor", &parsed->sponsor_},
2450 {"author", &parsed->author_},
2453 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2454 const char *start, *end;
2456 if (parser->Find(names[i].name_, start, end)) {
2457 CYString &value(*names[i].value_);
2458 _profile(Package$parse$Value)
2459 value.set(pool_, start, end - start);
2465 _profile(Package$parse$Tagline)
2466 const char *start, *end;
2467 if (parser->ShortDesc(start, end)) {
2468 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2471 while (stop != start && stop[-1] == '\r')
2473 parsed->tagline_.set(pool_, start, stop - start);
2477 _profile(Package$parse$Retain)
2478 if (parsed->homepage_.empty())
2479 parsed->homepage_ = website;
2480 if (parsed->homepage_ == parsed->depiction_)
2481 parsed->homepage_.clear();
2486 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2487 if ((self = [super init]) != nil) {
2488 _profile(Package$initWithVersion)
2491 database_ = database;
2492 era_ = [database era];
2496 pkgCache::PkgIterator iterator(version.ParentPkg());
2497 iterator_ = iterator;
2499 _profile(Package$initWithVersion$Version)
2500 if (!version_.end())
2501 file_ = version_.FileList();
2503 pkgCache &cache([database_ cache]);
2504 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2508 _profile(Package$initWithVersion$Cache)
2509 name_.set(NULL, iterator.Display());
2511 latest_.set(NULL, StripVersion_(version_.VerStr()));
2513 pkgCache::VerIterator current(iterator.CurrentVer());
2515 installed_.set(NULL, StripVersion_(current.VerStr()));
2518 _profile(Package$initWithVersion$Tags)
2519 pkgCache::TagIterator tag(iterator.TagList());
2521 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2523 const char *name(tag.Name());
2524 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2526 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2527 if (strcmp(name + 6, "enduser") == 0)
2529 else if (strcmp(name + 6, "hacker") == 0)
2531 else if (strcmp(name + 6, "developer") == 0)
2533 else if (strcmp(name + 6, "cydia") == 0)
2539 if (strncmp(name, "cydia::", 7) == 0) {
2540 if (strcmp(name + 7, "essential") == 0)
2542 else if (strcmp(name + 7, "obsolete") == 0)
2547 } while (!tag.end());
2551 _profile(Package$initWithVersion$Metadata)
2552 const char *mixed(iterator.Name());
2553 size_t size(strlen(mixed));
2554 char lower[size + 1];
2556 for (size_t i(0); i != size; ++i)
2557 lower[i] = mixed[i] | 0x20;
2560 PackageValue *metadata(PackageFind(lower, size));
2561 metadata_ = metadata;
2563 id_.set(NULL, metadata->name_, size);
2565 const char *latest(version_.VerStr());
2566 size_t length(strlen(latest));
2568 uint16_t vhash(hashlittle(latest, length));
2570 size_t capped(std::min<size_t>(8, length));
2571 latest = latest + length - capped;
2573 if (metadata->first_ == 0)
2574 metadata->first_ = now_;
2576 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2577 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2578 metadata->vhash_ = vhash;
2579 metadata->last_ = now_;
2580 } else if (metadata->last_ == 0)
2581 metadata->last_ = metadata->first_;
2584 _profile(Package$initWithVersion$Section)
2585 section_ = iterator.Section();
2588 _profile(Package$initWithVersion$Flags)
2589 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2590 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2595 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2596 pkgCache::VerIterator version;
2598 _profile(Package$packageWithIterator$GetCandidateVer)
2599 version = [database policy]->GetCandidateVer(iterator);
2607 _profile(Package$packageWithIterator$Allocate)
2608 package = [Package allocWithZone:zone];
2611 _profile(Package$packageWithIterator$Initialize)
2613 initWithVersion:version
2620 _profile(Package$packageWithIterator$Autorelease)
2621 package = [package autorelease];
2627 - (pkgCache::PkgIterator) iterator {
2631 - (NSString *) section {
2632 if (section$_ == nil) {
2633 if (section_ == NULL)
2636 _profile(Package$section$mappedSectionForPointer)
2637 section$_ = [database_ mappedSectionForPointer:section_];
2642 - (NSString *) simpleSection {
2643 if (NSString *section = [self section])
2644 return Simplify(section);
2649 - (NSString *) longSection {
2650 return LocalizeSection([self section]);
2653 - (NSString *) shortSection {
2654 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2657 - (NSString *) uri {
2660 pkgIndexFile *index;
2661 pkgCache::PkgFileIterator file(file_.File());
2662 if (![database_ list].FindIndex(file, index))
2664 return [NSString stringWithUTF8String:iterator_->Path];
2665 //return [NSString stringWithUTF8String:file.Site()];
2666 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2670 - (Address *) maintainer {
2671 @synchronized (database_) {
2672 if ([database_ era] != era_ || file_.end())
2675 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2676 const std::string &maintainer(parser->Maintainer());
2677 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2681 @synchronized (database_) {
2682 if ([database_ era] != era_ || version_.end())
2685 return version_->InstalledSize;
2688 - (NSString *) longDescription {
2689 @synchronized (database_) {
2690 if ([database_ era] != era_ || file_.end())
2693 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2694 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2696 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2697 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2698 if ([lines count] < 2)
2701 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2702 for (size_t i(1), e([lines count]); i != e; ++i) {
2703 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2704 [trimmed addObject:trim];
2707 return [trimmed componentsJoinedByString:@"\n"];
2710 - (NSString *) shortDescription {
2711 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2715 _profile(Package$index)
2716 CFStringRef name((CFStringRef) [self name]);
2717 if (CFStringGetLength(name) == 0)
2719 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2720 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2722 return toupper(character);
2726 - (PackageValue *) metadata {
2731 PackageValue *metadata([self metadata]);
2732 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2735 - (bool) subscribed {
2736 return [self metadata]->subscribed_;
2739 - (bool) setSubscribed:(bool)subscribed {
2740 PackageValue *metadata([self metadata]);
2741 if (metadata->subscribed_ == subscribed)
2743 metadata->subscribed_ = subscribed;
2751 - (NSString *) latest {
2755 - (NSString *) installed {
2759 - (BOOL) uninstalled {
2760 return installed_.empty();
2764 return !version_.end();
2767 - (BOOL) upgradableAndEssential:(BOOL)essential {
2768 _profile(Package$upgradableAndEssential)
2769 pkgCache::VerIterator current(iterator_.CurrentVer());
2771 return essential && essential_;
2773 return !version_.end() && version_ != current;
2777 - (BOOL) essential {
2782 return [database_ cache][iterator_].InstBroken();
2785 - (BOOL) unfiltered {
2786 _profile(Package$unfiltered$obsolete)
2787 if (_unlikely(obsolete_))
2791 _profile(Package$unfiltered$hasSupportingRole)
2792 if (_unlikely(![self hasSupportingRole]))
2800 if (![self unfiltered])
2805 _profile(Package$visible$section)
2806 section = [self section];
2809 _profile(Package$visible$isSectionVisible)
2810 if (!isSectionVisible(section))
2818 unsigned char current(iterator_->CurrentState);
2819 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2822 - (BOOL) halfConfigured {
2823 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2826 - (BOOL) halfInstalled {
2827 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2831 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2832 return state.Mode != pkgDepCache::ModeKeep;
2835 - (NSString *) mode {
2836 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2838 switch (state.Mode) {
2839 case pkgDepCache::ModeDelete:
2840 if ((state.iFlags & pkgDepCache::Purge) != 0)
2844 case pkgDepCache::ModeKeep:
2845 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2846 return @"REINSTALL";
2847 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2851 case pkgDepCache::ModeInstall:
2852 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2853 return @"REINSTALL";
2854 else*/ switch (state.Status) {
2856 return @"DOWNGRADE";
2862 return @"NEW_INSTALL";
2873 - (NSString *) name {
2874 return name_.empty() ? id_ : name_;
2877 - (UIImage *) icon {
2878 NSString *section = [self simpleSection];
2881 if (parsed_ != NULL)
2882 if (NSString *href = parsed_->icon_)
2883 if ([href hasPrefix:@"file:///"])
2884 // XXX: correct escaping
2885 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2886 if (icon == nil) if (section != nil)
2887 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2888 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2889 if ([dicon hasPrefix:@"file:///"])
2890 // XXX: correct escaping
2891 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2893 icon = [UIImage applicationImageNamed:@"unknown.png"];
2897 - (NSString *) homepage {
2898 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2901 - (NSString *) depiction {
2902 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2905 - (Address *) sponsor {
2906 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2909 - (Address *) author {
2910 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2913 - (NSString *) support {
2914 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2917 - (NSArray *) files {
2918 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2919 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2922 fin.open([path UTF8String]);
2927 while (std::getline(fin, line))
2928 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2933 - (NSArray *) warnings {
2934 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2935 const char *name(iterator_.Name());
2937 size_t length(strlen(name));
2938 if (length < 2) invalid:
2939 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2940 else for (size_t i(0); i != length; ++i)
2942 /* XXX: technically this is not allowed */
2943 (name[i] < 'A' || name[i] > 'Z') &&
2944 (name[i] < 'a' || name[i] > 'z') &&
2945 (name[i] < '0' || name[i] > '9') &&
2946 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2949 if (strcmp(name, "cydia") != 0) {
2952 bool _private = false;
2955 bool repository = [[self section] isEqualToString:@"Repositories"];
2957 if (NSArray *files = [self files])
2958 for (NSString *file in files)
2959 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2961 else if (!user && [file isEqualToString:@"/User"])
2963 else if (!_private && [file isEqualToString:@"/private"])
2965 else if (!stash && [file isEqualToString:@"/var/stash"])
2968 /* XXX: this is not sensitive enough. only some folders are valid. */
2969 if (cydia && !repository)
2970 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2972 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2974 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2976 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2979 return [warnings count] == 0 ? nil : warnings;
2982 - (NSArray *) applications {
2983 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2985 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2987 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2988 if (NSArray *files = [self files])
2989 for (NSString *file in files)
2990 if (application_r(file)) {
2991 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2992 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2993 if ([id isEqualToString:me])
2996 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2998 display = application_r[1];
3000 NSString *bundle([file stringByDeletingLastPathComponent]);
3001 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3002 if (icon == nil || [icon length] == 0)
3004 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3006 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3007 [applications addObject:application];
3009 [application addObject:id];
3010 [application addObject:display];
3011 [application addObject:url];
3014 return [applications count] == 0 ? nil : applications;
3017 - (Source *) source {
3018 if (source_ == nil) {
3019 @synchronized (database_) {
3020 if ([database_ era] != era_ || file_.end())
3021 source_ = (Source *) [NSNull null];
3023 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
3027 return source_ == (Source *) [NSNull null] ? nil : source_;
3030 - (BOOL) matches:(NSString *)text {
3036 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
3037 if (range.location != NSNotFound)
3040 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
3041 if (range.location != NSNotFound)
3046 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
3047 if (range.location != NSNotFound)
3053 - (bool) hasSupportingRole {
3058 if ([Role_ isEqualToString:@"User"])
3062 if ([Role_ isEqualToString:@"Hacker"])
3066 if ([Role_ isEqualToString:@"Developer"])
3071 - (BOOL) hasTag:(NSString *)tag {
3072 return tags_ == nil ? NO : [tags_ containsObject:tag];
3075 - (NSString *) primaryPurpose {
3076 for (NSString *tag in tags_)
3077 if ([tag hasPrefix:@"purpose::"])
3078 return [tag substringFromIndex:9];
3082 - (NSArray *) purposes {
3083 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3084 for (NSString *tag in tags_)
3085 if ([tag hasPrefix:@"purpose::"])
3086 [purposes addObject:[tag substringFromIndex:9]];
3087 return [purposes count] == 0 ? nil : purposes;
3090 - (bool) isCommercial {
3091 return [self hasTag:@"cydia::commercial"];
3094 - (void) setIndex:(size_t)index {
3095 if (metadata_->index_ != index)
3096 metadata_->index_ = index;
3099 - (CYString &) cyname {
3100 return name_.empty() ? id_ : name_;
3103 - (uint32_t) compareBySection:(NSArray *)sections {
3104 NSString *section([self section]);
3105 for (size_t i(0), e([sections count]); i != e; ++i) {
3106 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3110 return _not(uint32_t);
3114 @synchronized (database_) {
3115 pkgProblemResolver *resolver = [database_ resolver];
3116 resolver->Clear(iterator_);
3118 pkgCacheFile &cache([database_ cache]);
3119 cache->SetReInstall(iterator_, false);
3120 cache->MarkKeep(iterator_, false);
3124 @synchronized (database_) {
3125 pkgProblemResolver *resolver = [database_ resolver];
3126 resolver->Clear(iterator_);
3127 resolver->Protect(iterator_);
3129 pkgCacheFile &cache([database_ cache]);
3130 cache->SetReInstall(iterator_, false);
3131 cache->MarkInstall(iterator_, false);
3133 pkgDepCache::StateCache &state((*cache)[iterator_]);
3134 if (!state.Install())
3135 cache->SetReInstall(iterator_, true);
3139 @synchronized (database_) {
3140 pkgProblemResolver *resolver = [database_ resolver];
3141 resolver->Clear(iterator_);
3142 resolver->Remove(iterator_);
3143 resolver->Protect(iterator_);
3145 pkgCacheFile &cache([database_ cache]);
3146 cache->SetReInstall(iterator_, false);
3147 cache->MarkDelete(iterator_, true);
3150 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3151 _profile(Package$isUnfilteredAndSearchedForBy)
3154 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3155 value &= [self unfiltered];
3158 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3159 value &= [self matches:search];
3166 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3167 if ([search length] == 0)
3170 _profile(Package$isUnfilteredAndSelectedForBy)
3173 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3174 value &= [self unfiltered];
3177 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3178 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3185 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3186 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3189 - (bool) isVisibleInSection:(NSString *)name {
3190 NSString *section([self section]);
3194 section == nil && [name length] == 0 ||
3195 [name isEqualToString:section]
3196 ) && [self visible];
3199 - (bool) isVisibleInSource:(Source *)source {
3200 return [self source] == source && [self visible];
3205 /* Section Class {{{ */
3206 @interface Section : NSObject {
3211 NSString *localized_;
3214 - (NSComparisonResult) compareByLocalized:(Section *)section;
3215 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3216 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3217 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3218 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3219 - (NSString *) name;
3226 - (void) addToCount;
3228 - (void) setCount:(size_t)count;
3229 - (NSString *) localized;
3233 @implementation Section
3237 if (localized_ != nil)
3238 [localized_ release];
3242 - (NSComparisonResult) compareByLocalized:(Section *)section {
3243 NSString *lhs(localized_);
3244 NSString *rhs([section localized]);
3246 /*if ([lhs length] != 0 && [rhs length] != 0) {
3247 unichar lhc = [lhs characterAtIndex:0];
3248 unichar rhc = [rhs characterAtIndex:0];
3250 if (isalpha(lhc) && !isalpha(rhc))
3251 return NSOrderedAscending;
3252 else if (!isalpha(lhc) && isalpha(rhc))
3253 return NSOrderedDescending;
3256 return [lhs compare:rhs options:LaxCompareOptions_];
3259 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3260 if ((self = [self initWithName:name localize:NO]) != nil) {
3261 if (localized != nil)
3262 localized_ = [localized retain];
3266 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3267 return [self initWithName:name row:0 localize:localize];
3270 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3271 if ((self = [super init]) != nil) {
3272 name_ = [name retain];
3276 localized_ = [LocalizeSection(name_) retain];
3280 /* XXX: localize the index thingees */
3281 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3282 if ((self = [super init]) != nil) {
3283 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3289 - (NSString *) name {
3309 - (void) addToCount {
3313 - (void) setCount:(size_t)count {
3317 - (NSString *) localized {
3324 static NSString *Colon_;
3325 static NSString *Elision_;
3326 static NSString *Error_;
3327 static NSString *Warning_;
3329 /* Database Implementation {{{ */
3330 @implementation Database
3332 + (Database *) sharedInstance {
3333 static Database *instance;
3334 if (instance == nil)
3335 instance = [[Database alloc] init];
3343 - (void) releasePackages {
3344 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3345 CFArrayRemoveAllValues(packages_);
3349 // XXX: actually implement this thing
3351 [sourceList_ release];
3352 [self releasePackages];
3353 apr_pool_destroy(pool_);
3354 NSRecycleZone(zone_);
3358 - (void) _readCydia:(NSNumber *)fd { _pooled
3359 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3360 std::istream is(&ib);
3363 static Pcre finish_r("^finish:([^:]*)$");
3365 while (std::getline(is, line)) {
3366 const char *data(line.c_str());
3367 size_t size = line.size();
3368 lprintf("C:%s\n", data);
3370 if (finish_r(data, size)) {
3371 NSString *finish = finish_r[1];
3372 int index = [Finishes_ indexOfObject:finish];
3373 if (index != INT_MAX && index > Finish_)
3381 - (void) _readStatus:(NSNumber *)fd { _pooled
3382 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3383 std::istream is(&ib);
3386 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3387 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3389 while (std::getline(is, line)) {
3390 const char *data(line.c_str());
3391 size_t size(line.size());
3392 lprintf("S:%s\n", data);
3394 if (conffile_r(data, size)) {
3395 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3396 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3397 } else if (strncmp(data, "status: ", 8) == 0) {
3398 // status: <package>: {unpacked,half-configured,installed}
3399 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:@"STATUS"]);
3400 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3401 } else if (strncmp(data, "processing: ", 12) == 0) {
3402 // processing: configure: config-test
3403 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:@"STATUS"]);
3404 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3405 } else if (pmstatus_r(data, size)) {
3406 std::string type([pmstatus_r[1] UTF8String]);
3408 NSString *package = pmstatus_r[2];
3409 if ([package isEqualToString:@"dpkg-exec"])
3412 float percent([pmstatus_r[3] floatValue]);
3413 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3415 NSString *string = pmstatus_r[4];
3417 if (type == "pmerror") {
3418 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"ERROR" forPackage:package]);
3419 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3420 } else if (type == "pmstatus") {
3421 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"STATUS" forPackage:package]);
3422 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3423 } else if (type == "pmconffile")
3424 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3426 lprintf("E:unknown pmstatus\n");
3428 lprintf("E:unknown status\n");
3434 - (void) _readOutput:(NSNumber *)fd { _pooled
3435 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3436 std::istream is(&ib);
3439 while (std::getline(is, line)) {
3440 lprintf("O:%s\n", line.c_str());
3442 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:@"INFORMATION"]);
3443 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3453 - (Package *) packageWithName:(NSString *)name {
3454 @synchronized (self) {
3455 if (static_cast<pkgDepCache *>(cache_) == NULL)
3457 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3458 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3462 if ((self = [super init]) != nil) {
3469 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3470 apr_pool_create(&pool_, NULL);
3472 size_t capacity(MetaFile_->active_);
3478 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3479 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3483 _assert(pipe(fds) != -1);
3486 _config->Set("APT::Keep-Fds::", cydiafd_);
3487 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3490 detachNewThreadSelector:@selector(_readCydia:)
3492 withObject:[NSNumber numberWithInt:fds[0]]
3495 _assert(pipe(fds) != -1);
3499 detachNewThreadSelector:@selector(_readStatus:)
3501 withObject:[NSNumber numberWithInt:fds[0]]
3504 _assert(pipe(fds) != -1);
3505 _assert(dup2(fds[0], 0) != -1);
3506 _assert(close(fds[0]) != -1);
3508 input_ = fdopen(fds[1], "a");
3510 _assert(pipe(fds) != -1);
3511 _assert(dup2(fds[1], 1) != -1);
3512 _assert(close(fds[1]) != -1);
3515 detachNewThreadSelector:@selector(_readOutput:)
3517 withObject:[NSNumber numberWithInt:fds[0]]
3522 - (pkgCacheFile &) cache {
3526 - (pkgDepCache::Policy *) policy {
3530 - (pkgRecords *) records {
3534 - (pkgProblemResolver *) resolver {
3538 - (pkgAcquire &) fetcher {
3542 - (pkgSourceList &) list {
3546 - (NSArray *) packages {
3547 return (NSArray *) packages_;
3550 - (NSArray *) sources {
3554 - (Source *) sourceWithKey:(NSString *)key {
3555 for (Source *source in [self sources]) {
3556 if ([[source key] isEqualToString:key])
3561 - (bool) popErrorWithTitle:(NSString *)title {
3564 while (!_error->empty()) {
3566 bool warning(!_error->PopMessage(error));
3571 size_t size(error.size());
3572 if (size == 0 || error[size - 1] != '\n')
3574 error.resize(size - 1);
3577 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3579 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3585 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3586 return [self popErrorWithTitle:title] || !success;
3589 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3590 @synchronized (self) {
3593 [self releasePackages];
3596 [sourceList_ removeAllObjects];
3616 apr_pool_clear(pool_);
3618 NSRecycleZone(zone_);
3619 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3621 int chk(creat("/tmp/cydia.chk", 0644));
3625 if (invocation != nil)
3626 [invocation invoke];
3628 NSString *title(UCLocalize("DATABASE"));
3631 OpProgress progress;
3632 while (!cache_.Open(progress, true)) { pop:
3634 bool warning(!_error->PopMessage(error));
3635 lprintf("cache_.Open():[%s]\n", error.c_str());
3637 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3638 [delegate_ repairWithSelector:@selector(configure)];
3639 else if (error == "The package lists or status file could not be parsed or opened.")
3640 [delegate_ repairWithSelector:@selector(update)];
3641 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3642 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3643 // else if (error == "Malformed Status line")
3644 // else if (error == "The list of sources could not be read.")
3646 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3656 unlink("/tmp/cydia.chk");
3658 now_ = [[NSDate date] timeIntervalSince1970];
3660 policy_ = new pkgDepCache::Policy();
3661 records_ = new pkgRecords(cache_);
3662 resolver_ = new pkgProblemResolver(cache_);
3663 fetcher_ = new pkgAcquire(&status_);
3666 list_ = new pkgSourceList();
3667 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3670 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3671 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:@"ERROR"] forTask:title];
3675 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3678 if (cache_->BrokenCount() != 0) {
3679 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3682 if (cache_->BrokenCount() != 0) {
3683 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:@"ERROR"] forTask:title];
3687 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3691 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3692 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3693 [sourceList_ addObject:object];
3695 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3696 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3697 // XXX: this could be more intelligent
3698 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3699 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3701 sourceMap_[cached->ID] = object;
3706 /*std::vector<Package *> packages;
3707 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3708 [packages_ release];
3713 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3714 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3715 //packages.push_back(package);
3716 CFArrayAppendValue(packages_, [package retain]);
3720 /*if (packages.empty())
3721 packages_ = [[NSArray alloc] init];
3723 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3726 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3727 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3728 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3736 /*if (!packages.empty())
3737 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3738 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3740 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3742 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3744 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3748 size_t count(CFArrayGetCount(packages_));
3749 MetaFile_->active_ = count;
3751 for (size_t index(0); index != count; ++index)
3752 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3756 } } CYPoolEnd() _trace(); }
3759 @synchronized (self) {
3761 resolver_ = new pkgProblemResolver(cache_);
3763 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3764 if (!cache_[iterator].Keep())
3765 cache_->MarkKeep(iterator, false);
3766 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3767 cache_->SetReInstall(iterator, false);
3770 - (void) configure {
3771 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3773 system([dpkg UTF8String]);
3778 // XXX: I don't remember this condition
3783 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3785 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3787 if ([self popErrorWithTitle:title])
3791 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3794 public pkgArchiveCleaner
3797 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3802 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3809 fetcher_->Shutdown();
3811 pkgRecords records(cache_);
3813 lock_ = new FileFd();
3814 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3816 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3818 if ([self popErrorWithTitle:title])
3822 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3825 manager_ = (_system->CreatePM(cache_));
3826 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3833 bool substrate(RestartSubstrate_);
3834 RestartSubstrate_ = false;
3836 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3838 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3840 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3842 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3843 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3846 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3848 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3850 [self popErrorWithTitle:title];
3854 bool failed = false;
3855 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3856 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3858 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3864 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3872 RestartSubstrate_ = true;
3875 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3877 if (_error->PendingError()) {
3882 if (result == pkgPackageManager::Failed) {
3887 if (result != pkgPackageManager::Completed) {
3892 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3894 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3896 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3897 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3900 if (![before isEqualToArray:after])
3905 NSString *title(UCLocalize("UPGRADE"));
3906 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3912 [self updateWithStatus:status_];
3915 - (void) updateWithStatus:(Status &)status {
3916 NSString *title(UCLocalize("REFRESHING_DATA"));
3919 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3923 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3924 if ([self popErrorWithTitle:title])
3927 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3929 bool success(ListUpdate(status, list, PulseInterval_));
3930 if (status.WasCancelled())
3933 [self popErrorWithTitle:title forOperation:success];
3935 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3937 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3941 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3942 delegate_ = delegate;
3945 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3946 progress_ = delegate;
3947 status_.setDelegate(delegate);
3950 - (NSObject<ProgressDelegate> *) progressDelegate {
3954 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3955 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3956 return i == sourceMap_.end() ? nil : i->second;
3959 - (NSString *) mappedSectionForPointer:(const char *)section {
3960 _H<NSString> *mapped;
3962 _profile(Database$mappedSectionForPointer$Cache)
3963 mapped = §ions_[section];
3966 if (*mapped == NULL) {
3967 size_t length(strlen(section));
3968 char spaced[length + 1];
3970 _profile(Database$mappedSectionForPointer$Replace)
3971 for (size_t index(0); index != length; ++index)
3972 spaced[index] = section[index] == '_' ? ' ' : section[index];
3973 spaced[length] = '\0';
3978 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3979 string = [NSString stringWithUTF8String:spaced];
3982 _profile(Database$mappedSectionForPointer$Map)
3983 string = [SectionMap_ objectForKey:string] ?: string;
3993 /* Web Scripting {{{ */
3994 @interface CydiaObject : NSObject {
3996 _transient id delegate_;
3999 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4003 @implementation CydiaObject
4006 [indirect_ release];
4010 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4011 if ((self = [super init]) != nil) {
4012 indirect_ = [indirect retain];
4016 - (void) setDelegate:(id)delegate {
4017 delegate_ = delegate;
4020 + (NSArray *) _attributeKeys {
4021 return [NSArray arrayWithObjects:
4036 - (NSArray *) attributeKeys {
4037 return [[self class] _attributeKeys];
4040 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4041 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4044 - (NSString *) version {
4048 - (NSString *) device {
4049 return [[UIDevice currentDevice] uniqueIdentifier];
4052 - (NSString *) firmware {
4053 return [[UIDevice currentDevice] systemVersion];
4056 - (NSString *) hostname {
4057 return [[UIDevice currentDevice] name];
4060 - (NSString *) idiom {
4061 return (id) Idiom_ ?: [NSNull null];
4064 - (NSString *) plmn {
4065 return (id) PLMN_ ?: [NSNull null];
4068 - (NSString *) ecid {
4069 return (id) ChipID_ ?: [NSNull null];
4072 - (NSString *) serial {
4073 return SerialNumber_;
4076 - (NSString *) role {
4077 return (id) Role_ ?: [NSNull null];
4080 - (NSString *) model {
4081 return [NSString stringWithUTF8String:Machine_];
4084 - (NSString *) token {
4085 return (id) Token_ ?: [NSNull null];
4088 + (NSString *) webScriptNameForSelector:(SEL)selector {
4090 else if (selector == @selector(addTrivialSource:))
4091 return @"addTrivialSource";
4092 else if (selector == @selector(close))
4094 else if (selector == @selector(du:))
4096 else if (selector == @selector(stringWithFormat:arguments:))
4098 else if (selector == @selector(getAllSources))
4099 return @"getAllSourcs";
4100 else if (selector == @selector(getKernelNumber:))
4101 return @"getKernelNumber";
4102 else if (selector == @selector(getKernelString:))
4103 return @"getKernelString";
4104 else if (selector == @selector(getInstalledPackages))
4105 return @"getInstalledPackages";
4106 else if (selector == @selector(getPackageById:))
4107 return @"getPackageById";
4108 else if (selector == @selector(installPackages:))
4109 return @"installPackages";
4110 else if (selector == @selector(localizedStringForKey:value:table:))
4112 else if (selector == @selector(refreshSources))
4113 return @"refreshSources";
4114 else if (selector == @selector(removeButton))
4115 return @"removeButton";
4116 else if (selector == @selector(substitutePackageNames:))
4117 return @"substitutePackageNames";
4118 else if (selector == @selector(scrollToBottom:))
4119 return @"scrollToBottom";
4120 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4121 return @"setButtonImage";
4122 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4123 return @"setButtonTitle";
4124 else if (selector == @selector(setHidesBackButton:))
4125 return @"setHidesBackButton";
4126 else if (selector == @selector(setHidesNavigationBar:))
4127 return @"setHidesNavigationBar";
4128 else if (selector == @selector(setNavigationBarStyle:))
4129 return @"setNavigationBarStyle";
4130 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4131 return @"setNavigationBarTintColor";
4132 else if (selector == @selector(setPopupHook:))
4133 return @"setPopupHook";
4134 else if (selector == @selector(setToken:))
4136 else if (selector == @selector(setViewportWidth:))
4137 return @"setViewportWidth";
4138 else if (selector == @selector(statfs:))
4140 else if (selector == @selector(supports:))
4146 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4147 return [self webScriptNameForSelector:selector] == nil;
4150 - (BOOL) supports:(NSString *)feature {
4151 return [feature isEqualToString:@"window.open"];
4154 - (NSNumber *) getKernelNumber:(NSString *)name {
4155 const char *string([name UTF8String]);
4158 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4159 return (id) [NSNull null];
4161 if (size != sizeof(int))
4162 return (id) [NSNull null];
4165 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4166 return (id) [NSNull null];
4168 return [NSNumber numberWithInt:value];
4171 - (NSString *) getKernelString:(NSString *)name {
4172 const char *string([name UTF8String]);
4175 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4176 return (id) [NSNull null];
4178 char value[size + 1];
4179 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4180 return (id) [NSNull null];
4182 // XXX: just in case you request something ludicrous
4185 return [NSString stringWithCString:value];
4188 - (void) addTrivialSource:(NSString *)href {
4189 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4192 - (void) refreshSources {
4193 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4196 - (NSArray *) getAllSources {
4197 return [[Database sharedInstance] sources];
4200 - (NSArray *) getInstalledPackages {
4201 Database *database([Database sharedInstance]);
4202 @synchronized (database) {
4203 NSArray *packages([database packages]);
4204 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4205 for (Package *package in packages)
4206 if (![package uninstalled])
4207 [installed addObject:package];
4211 - (Package *) getPackageById:(NSString *)id {
4212 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4216 return (Package *) [NSNull null];
4219 - (NSArray *) statfs:(NSString *)path {
4222 if (path == nil || statfs([path UTF8String], &stat) == -1)
4225 return [NSArray arrayWithObjects:
4226 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4227 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4228 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4232 - (NSNumber *) du:(NSString *)path {
4233 NSNumber *value(nil);
4236 _assert(pipe(fds) != -1);
4238 pid_t pid(ExecFork());
4240 _assert(dup2(fds[1], 1) != -1);
4241 _assert(close(fds[0]) != -1);
4242 _assert(close(fds[1]) != -1);
4243 /* XXX: this should probably not use du */
4244 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4249 _assert(close(fds[1]) != -1);
4251 if (FILE *du = fdopen(fds[0], "r")) {
4253 while (fgets(line, sizeof(line), du) != NULL) {
4254 size_t length(strlen(line));
4255 while (length != 0 && line[length - 1] == '\n')
4256 line[--length] = '\0';
4257 if (char *tab = strchr(line, '\t')) {
4259 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4264 } else _assert(close(fds[0]));
4268 if (waitpid(pid, &status, 0) == -1)
4271 else _assert(false);
4277 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4280 - (void) installPackages:(NSArray *)packages {
4281 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4284 - (NSString *) substitutePackageNames:(NSString *)message {
4285 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4286 for (size_t i(0), e([words count]); i != e; ++i) {
4287 NSString *word([words objectAtIndex:i]);
4288 if (Package *package = [[Database sharedInstance] packageWithName:word])
4289 [words replaceObjectAtIndex:i withObject:[package name]];
4292 return [words componentsJoinedByString:@" "];
4295 - (void) removeButton {
4296 [indirect_ removeButton];
4299 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4300 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4303 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4304 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4307 - (void) setHidesBackButton:(NSString *)value {
4308 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4311 - (void) setHidesNavigationBar:(NSString *)value {
4312 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4315 - (void) setNavigationBarStyle:(NSString *)value {
4316 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4319 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4320 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4321 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4322 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4325 - (void) _setToken:(NSString *)token {
4329 [Metadata_ removeObjectForKey:@"Token"];
4331 [Metadata_ setObject:Token_ forKey:@"Token"];
4336 - (void) setToken:(NSString *)token {
4337 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4340 - (void) setPopupHook:(id)function {
4341 [indirect_ setPopupHook:function];
4344 - (void) scrollToBottom:(NSNumber *)animated {
4345 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4348 - (void) setViewportWidth:(float)width {
4349 [indirect_ setViewportWidthOnMainThread:width];
4352 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4353 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4354 unsigned count([arguments count]);
4356 for (unsigned i(0); i != count; ++i)
4357 values[i] = [arguments objectAtIndex:i];
4358 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4361 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4362 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4364 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4366 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4372 /* @ Loading... Indicator {{{ */
4373 @interface CYLoadingIndicator : UIView {
4374 _H<UIActivityIndicatorView> spinner_;
4376 _H<UIView> container_;
4379 @property (readonly, nonatomic) UILabel *label;
4380 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4384 @implementation CYLoadingIndicator
4386 - (id) initWithFrame:(CGRect)frame {
4387 if ((self = [super initWithFrame:frame]) != nil) {
4388 container_ = [[[UIView alloc] init] autorelease];
4389 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4391 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4392 [spinner_ startAnimating];
4393 [container_ addSubview:spinner_];
4395 label_ = [[[UILabel alloc] init] autorelease];
4396 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4397 [label_ setBackgroundColor:[UIColor clearColor]];
4398 [label_ setTextColor:[UIColor blackColor]];
4399 [label_ setShadowColor:[UIColor whiteColor]];
4400 [label_ setShadowOffset:CGSizeMake(0, 1)];
4401 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4402 [container_ addSubview:label_];
4404 CGSize viewsize = frame.size;
4405 CGSize spinnersize = [spinner_ bounds].size;
4406 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4407 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4409 CGRect containrect = {
4410 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4411 CGSizeMake(bothwidth, spinnersize.height)
4414 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4422 [container_ setFrame:containrect];
4423 [spinner_ setFrame:spinrect];
4424 [label_ setFrame:textrect];
4425 [self addSubview:container_];
4429 - (UILabel *) label {
4433 - (UIActivityIndicatorView *) activityIndicatorView {
4439 /* Emulated Loading Controller {{{ */
4440 @interface CYEmulatedLoadingController : CYViewController {
4441 _transient Database *database_;
4442 _H<CYLoadingIndicator> indicator_;
4443 _H<UITabBar> tabbar_;
4444 _H<UINavigationBar> navbar_;
4449 @implementation CYEmulatedLoadingController
4451 - (id) initWithDatabase:(Database *)database {
4452 if ((self = [super init]) != nil) {
4453 database_ = database;
4457 // XXX: factor this out somewhere
4458 - (UIColor *) groupTableViewBackgroundColor {
4459 UIDevice *device([UIDevice currentDevice]);
4460 bool iPad([device respondsToSelector:@selector(userInterfaceIdiom)] && [device userInterfaceIdiom] == UIUserInterfaceIdiomPad);
4461 return iPad ? [UIColor colorWithRed:0.821 green:0.834 blue:0.860 alpha:1] : [UIColor groupTableViewBackgroundColor];
4465 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4466 [[self view] setBackgroundColor:[self groupTableViewBackgroundColor]];
4468 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4469 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4470 [[self view] addSubview:indicator_];
4472 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4473 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4474 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4475 [[self view] addSubview:tabbar_];
4477 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4478 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4479 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4480 [[self view] addSubview:navbar_];
4483 - (void) releaseSubviews {
4492 /* Cydia Browser Controller {{{ */
4493 @interface CYBrowserController : BrowserController {
4494 CydiaObject *cydia_;
4499 @implementation CYBrowserController
4506 - (NSURL *) navigationURL {
4507 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4510 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4513 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4514 [super webView:view didClearWindowObject:window forFrame:frame];
4516 WebDataSource *source([frame dataSource]);
4517 NSURLResponse *response([source response]);
4519 NSURL *url([response URL]);
4520 NSString *scheme([url scheme]);
4521 NSString *host([url host]);
4523 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4524 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4525 NSDictionary *headers([http allHeaderFields]);
4526 [self setHeaders:headers forHost:host];
4530 [host isEqualToString:@"cydia.saurik.com"] ||
4531 [host hasSuffix:@".cydia.saurik.com"] ||
4532 [scheme isEqualToString:@"file"]
4534 [window setValue:cydia_ forKey:@"cydia"];
4537 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4538 if (System_ != NULL)
4539 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4540 if (Machine_ != NULL)
4541 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4543 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4545 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4548 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4549 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4550 [self _setMoreHeaders:copy];
4554 - (void) setDelegate:(id)delegate {
4555 [super setDelegate:delegate];
4556 [cydia_ setDelegate:delegate];
4560 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4561 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4563 WebView *webview([[webview_ _documentView] webView]);
4565 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4568 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4570 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4571 if (Product_ != nil)
4572 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4574 [webview setApplicationNameForUserAgent:application];
4582 @interface NSObject (CydiaScript)
4583 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4586 @implementation NSObject (CydiaScript)
4588 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4594 @implementation NSArray (CydiaScript)
4596 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4597 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4598 for (size_t i(0), e([self count]); i != e; ++i)
4599 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4605 @implementation NSDictionary (CydiaScript)
4607 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4608 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4610 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4617 /* Confirmation Controller {{{ */
4618 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4619 if (!iterator.end())
4620 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4621 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4623 pkgCache::PkgIterator package(dep.TargetPkg());
4626 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4633 @protocol ConfirmationControllerDelegate
4634 - (void) cancelAndClear:(bool)clear;
4635 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4639 @interface ConfirmationController : CYBrowserController {
4640 _transient Database *database_;
4642 UIAlertView *essential_;
4644 NSDictionary *changes_;
4645 NSMutableArray *issues_;
4646 NSDictionary *sizes_;
4651 - (id) initWithDatabase:(Database *)database;
4655 @implementation ConfirmationController
4662 if (essential_ != nil)
4663 [essential_ release];
4670 RestartSubstrate_ = true;
4671 [delegate_ confirmWithNavigationController:[self navigationController]];
4674 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4675 NSString *context([alert context]);
4677 if ([context isEqualToString:@"remove"]) {
4678 if (button == [alert cancelButtonIndex])
4679 [self dismissModalViewControllerAnimated:YES];
4680 else if (button == [alert firstOtherButtonIndex]) {
4684 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4685 } else if ([context isEqualToString:@"unable"]) {
4686 [self dismissModalViewControllerAnimated:YES];
4687 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4689 [super alertView:alert clickedButtonAtIndex:button];
4693 - (void) _doContinue {
4694 [self dismissModalViewControllerAnimated:YES];
4695 [delegate_ cancelAndClear:NO];
4698 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4699 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4703 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4704 [super webView:view didClearWindowObject:window forFrame:frame];
4706 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4707 changes_, @"changes",
4711 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4714 - (id) initWithDatabase:(Database *)database {
4715 if ((self = [super init]) != nil) {
4716 database_ = database;
4718 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4719 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4720 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4721 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4722 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4726 pkgCacheFile &cache([database_ cache]);
4727 NSArray *packages([database_ packages]);
4728 pkgDepCache::Policy *policy([database_ policy]);
4730 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4732 for (Package *package in packages) {
4733 pkgCache::PkgIterator iterator([package iterator]);
4734 NSString *name([package id]);
4736 if ([package broken]) {
4737 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4739 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4741 reasons, @"reasons",
4744 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4748 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4749 pkgCache::DepIterator start;
4750 pkgCache::DepIterator end;
4751 dep.GlobOr(start, end); // ++dep
4753 if (!cache->IsImportantDep(end))
4755 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4758 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4760 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4761 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4762 clauses, @"clauses",
4766 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4768 pkgCache::PkgIterator target(start.TargetPkg());
4769 if (target->ProvidesList != 0)
4770 reason = @"missing";
4772 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4774 reason = @"installed";
4775 installed = [NSString stringWithUTF8String:ver.VerStr()];
4776 } else if (!cache[target].CandidateVerIter(cache).end())
4777 reason = @"uninstalled";
4778 else if (target->ProvidesList == 0)
4779 reason = @"uninstallable";
4781 reason = @"virtual";
4784 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4785 [NSString stringWithUTF8String:start.CompType()], @"operator",
4786 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4789 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4790 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4791 version, @"version",
4793 installed, @"installed",
4796 // yes, seriously. (wtf?)
4804 pkgDepCache::StateCache &state(cache[iterator]);
4806 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4808 if (state.NewInstall())
4809 [installs addObject:name];
4810 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4811 [reinstalls addObject:name];
4812 else if (state.Upgrade())
4813 [upgrades addObject:name];
4814 else if (state.Downgrade())
4815 [downgrades addObject:name];
4816 else if (!state.Delete())
4818 else if (special_r(name))
4819 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4820 [NSNull null], @"package",
4821 [NSArray arrayWithObjects:
4822 [NSDictionary dictionaryWithObjectsAndKeys:
4823 @"Conflicts", @"relationship",
4824 [NSArray arrayWithObjects:
4825 [NSDictionary dictionaryWithObjectsAndKeys:
4827 [NSNull null], @"version",
4828 @"installed", @"reason",
4835 if ([package essential])
4837 [removes addObject:name];
4840 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4841 substrate_ |= DepSubstrate(iterator.CurrentVer());
4846 else if (Advanced_) {
4847 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4849 essential_ = [[UIAlertView alloc]
4850 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4851 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4853 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4855 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4859 [essential_ setContext:@"remove"];
4861 essential_ = [[UIAlertView alloc]
4862 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4863 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4865 cancelButtonTitle:UCLocalize("OKAY")
4866 otherButtonTitles:nil
4869 [essential_ setContext:@"unable"];
4872 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4873 installs, @"installs",
4874 reinstalls, @"reinstalls",
4875 upgrades, @"upgrades",
4876 downgrades, @"downgrades",
4877 removes, @"removes",
4880 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4881 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4882 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4885 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4887 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4888 initWithTitle:UCLocalize("CANCEL")
4889 style:UIBarButtonItemStylePlain
4891 action:@selector(cancelButtonClicked)
4897 - (void) applyRightButton {
4898 if ([issues_ count] == 0 && ![self isLoading])
4899 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4900 initWithTitle:UCLocalize("CONFIRM")
4901 style:UIBarButtonItemStyleDone
4903 action:@selector(confirmButtonClicked)
4906 [[self navigationItem] setRightBarButtonItem:nil];
4910 - (void) cancelButtonClicked {
4911 [self dismissModalViewControllerAnimated:YES];
4912 [delegate_ cancelAndClear:YES];
4916 - (void) confirmButtonClicked {
4917 if (essential_ != nil)
4927 /* Progress Data {{{ */
4928 @interface CydiaProgressData : NSObject {
4929 _transient id delegate_;
4938 _H<NSMutableArray> events_;
4939 _H<NSString> title_;
4941 _H<NSString> status_;
4942 _H<NSString> finish_;
4947 @implementation CydiaProgressData
4949 + (NSArray *) _attributeKeys {
4950 return [NSArray arrayWithObjects:
4962 - (NSArray *) attributeKeys {
4963 return [[self class] _attributeKeys];
4966 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4967 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4971 if ((self = [super init]) != nil) {
4972 events_ = [NSMutableArray arrayWithCapacity:32];
4976 - (void) setDelegate:(id)delegate {
4977 delegate_ = delegate;
4980 - (void) setPercent:(float)value {
4984 - (NSNumber *) percent {
4985 return [NSNumber numberWithFloat:percent_];
4988 - (void) setCurrent:(float)value {
4992 - (NSNumber *) current {
4993 return [NSNumber numberWithFloat:current_];
4996 - (void) setTotal:(float)value {
5000 - (NSNumber *) total {
5001 return [NSNumber numberWithFloat:total_];
5004 - (void) setSpeed:(float)value {
5008 - (NSNumber *) speed {
5009 return [NSNumber numberWithFloat:speed_];
5012 - (NSArray *) events {
5016 - (void) removeAllEvents {
5017 [events_ removeAllObjects];
5020 - (void) addEvent:(CydiaProgressEvent *)event {
5021 [events_ addObject:event];
5024 - (void) setTitle:(NSString *)text {
5028 - (NSString *) title {
5032 - (void) setFinish:(NSString *)text {
5036 - (NSString *) finish {
5037 return (id) finish_ ?: [NSNull null];
5040 - (void) setRunning:(bool)running {
5044 - (NSNumber *) running {
5045 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5050 /* Progress Controller {{{ */
5051 @interface ProgressController : CYBrowserController <
5054 _transient Database *database_;
5055 _H<CydiaProgressData> progress_;
5059 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5061 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5063 - (void) setTitle:(NSString *)title;
5064 - (void) setCancellable:(bool)cancellable;
5068 @implementation ProgressController
5071 [database_ setProgressDelegate:nil];
5072 [progress_ setDelegate:nil];
5076 - (void) updateCancel {
5077 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5078 initWithTitle:UCLocalize("CANCEL")
5079 style:UIBarButtonItemStylePlain
5081 action:@selector(cancel)
5082 ] autorelease] : nil)];
5085 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5086 if ((self = [super init]) != nil) {
5087 database_ = database;
5088 delegate_ = delegate;
5090 [database_ setProgressDelegate:self];
5092 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5093 [progress_ setDelegate:self];
5095 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5097 [scroller_ setBackgroundColor:[UIColor blackColor]];
5099 [[self navigationItem] setHidesBackButton:YES];
5101 [self updateCancel];
5105 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5106 [super webView:view didClearWindowObject:window forFrame:frame];
5107 [window setValue:progress_ forKey:@"cydiaProgress"];
5110 - (void) updateProgress {
5111 [self dispatchEvent:@"CydiaProgressUpdate"];
5114 - (void) viewWillAppear:(BOOL)animated {
5115 if (![self hasLoaded])
5116 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5118 [super viewWillAppear:animated];
5122 UpdateExternalStatus(0);
5129 [delegate_ terminateWithSuccess];
5130 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5131 [delegate_ suspendWithAnimation:YES];
5133 [delegate_ suspend];*/
5145 system("/usr/bin/sbreload");
5151 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5152 SBReboot(SBSSpringBoardServerPort());
5154 reboot2(RB_AUTOBOOT);
5161 - (void) setTitle:(NSString *)title {
5162 [progress_ setTitle:title];
5163 [self updateProgress];
5166 - (UIBarButtonItem *) rightButton {
5167 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5168 initWithTitle:UCLocalize("CLOSE")
5169 style:UIBarButtonItemStylePlain
5171 action:@selector(close)
5175 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5176 UpdateExternalStatus(1);
5178 [progress_ setRunning:true];
5179 [self setTitle:title];
5180 // implicit updateProgress
5182 SHA1SumValue notifyconf; {
5184 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5187 MMap mmap(file, MMap::ReadOnly);
5189 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5190 notifyconf = sha1.Result();
5194 SHA1SumValue springlist; {
5196 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5199 MMap mmap(file, MMap::ReadOnly);
5201 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5202 springlist = sha1.Result();
5206 if (invocation != nil) {
5207 [invocation yieldToSelector:@selector(invoke)];
5208 [self setTitle:@"COMPLETE"];
5213 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5216 MMap mmap(file, MMap::ReadOnly);
5218 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5219 if (!(notifyconf == sha1.Result()))
5226 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5229 MMap mmap(file, MMap::ReadOnly);
5231 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5232 if (!(springlist == sha1.Result()))
5238 if (RestartSubstrate_)
5242 RestartSubstrate_ = false;
5245 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5246 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5247 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5248 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5249 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5253 system("su -c /usr/bin/uicache mobile");
5256 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5258 [progress_ setRunning:false];
5259 [self updateProgress];
5261 [self applyRightButton];
5264 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5265 [progress_ addEvent:event];
5266 [self updateProgress];
5269 - (bool) isProgressCancelled {
5270 return cancel_ == 2;
5275 [self updateCancel];
5278 - (void) setCancellable:(bool)cancellable {
5279 unsigned cancel(cancel_);
5283 else if (cancel_ == 0)
5286 if (cancel != cancel_)
5287 [self updateCancel];
5290 - (void) setProgressCancellable:(NSNumber *)cancellable {
5291 [self setCancellable:[cancellable boolValue]];
5294 - (void) setProgressPercent:(NSNumber *)percent {
5295 [progress_ setPercent:[percent floatValue]];
5296 [self updateProgress];
5299 - (void) setProgressStatus:(NSDictionary *)status {
5300 if (status == nil) {
5301 [progress_ setCurrent:0];
5302 [progress_ setTotal:0];
5303 [progress_ setSpeed:0];
5305 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5307 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5308 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5309 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5312 [self updateProgress];
5318 /* Cell Content View {{{ */
5319 @protocol ContentDelegate
5320 - (void) drawContentRect:(CGRect)rect;
5323 @interface ContentView : UIView {
5324 _transient id<ContentDelegate> delegate_;
5329 @implementation ContentView
5331 - (id) initWithFrame:(CGRect)frame {
5332 if ((self = [super initWithFrame:frame]) != nil) {
5333 [self setNeedsDisplayOnBoundsChange:YES];
5337 - (void) setDelegate:(id<ContentDelegate>)delegate {
5338 delegate_ = delegate;
5341 - (void) drawRect:(CGRect)rect {
5342 [super drawRect:rect];
5343 [delegate_ drawContentRect:rect];
5348 /* Cydia TableView Cell {{{ */
5349 @interface CYTableViewCell : UITableViewCell {
5350 ContentView *content_;
5356 @implementation CYTableViewCell
5363 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5364 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5366 if (view == content_) {
5367 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5368 highlighted_ = highlighted;
5371 [super _updateHighlightColorsForView:view highlighted:highlighted];
5374 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5375 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5376 highlighted_ = selected;
5378 [super setSelected:selected animated:animated];
5379 [content_ setNeedsDisplay];
5385 /* Package Cell {{{ */
5386 @interface PackageCell : CYTableViewCell <
5391 NSString *description_;
5399 - (PackageCell *) init;
5400 - (void) setPackage:(Package *)package;
5402 - (void) drawContentRect:(CGRect)rect;
5406 @implementation PackageCell
5408 - (void) clearPackage {
5419 if (description_ != nil) {
5420 [description_ release];
5424 if (source_ != nil) {
5429 if (badge_ != nil) {
5434 if (placard_ != nil) {
5444 [self clearPackage];
5448 - (PackageCell *) init {
5449 CGRect frame(CGRectMake(0, 0, 320, 74));
5450 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5451 UIView *content([self contentView]);
5452 CGRect bounds([content bounds]);
5454 content_ = [[ContentView alloc] initWithFrame:bounds];
5455 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5456 [content addSubview:content_];
5458 [content_ setDelegate:self];
5459 [content_ setOpaque:YES];
5463 - (NSString *) accessibilityLabel {
5464 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5467 - (void) setPackage:(Package *)package {
5468 [self clearPackage];
5471 Source *source = [package source];
5473 icon_ = [[package icon] retain];
5474 name_ = [[package name] retain];
5477 description_ = [package longDescription];
5478 if (description_ == nil)
5479 description_ = [package shortDescription];
5480 if (description_ != nil)
5481 description_ = [description_ retain];
5483 commercial_ = [package isCommercial];
5485 package_ = [package retain];
5487 NSString *label = nil;
5488 bool trusted = false;
5490 if (source != nil) {
5491 label = [source label];
5492 trusted = [source trusted];
5493 } else if ([[package id] isEqualToString:@"firmware"])
5494 label = UCLocalize("APPLE");
5496 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5498 NSString *from(label);
5500 NSString *section = [package simpleSection];
5501 if (section != nil && ![section isEqualToString:label]) {
5502 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5503 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5506 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5507 source_ = [from retain];
5509 if (NSString *purpose = [package primaryPurpose])
5510 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5511 badge_ = [badge_ retain];
5516 if (NSString *mode = [package_ mode]) {
5517 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5518 color = RemovingColor_;
5519 //placard = @"removing";
5521 color = InstallingColor_;
5522 //placard = @"installing";
5525 // XXX: the removing/installing placards are not @2x
5528 color = [UIColor whiteColor];
5530 if ([package installed] != nil)
5531 placard = @"installed";
5536 [content_ setBackgroundColor:color];
5539 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5540 placard_ = [placard_ retain];
5542 [self setNeedsDisplay];
5543 [content_ setNeedsDisplay];
5546 - (void) drawContentRect:(CGRect)rect {
5547 bool highlighted(highlighted_);
5548 float width([self bounds].size.width);
5551 CGContextRef context(UIGraphicsGetCurrentContext());
5552 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5553 CGContextFillRect(context, rect);
5558 rect.size = [icon_ size];
5560 rect.size.width /= 2;
5561 rect.size.height /= 2;
5563 rect.origin.x = 25 - rect.size.width / 2;
5564 rect.origin.y = 25 - rect.size.height / 2;
5566 [icon_ drawInRect:rect];
5569 if (badge_ != nil) {
5571 rect.size = [badge_ size];
5573 rect.size.width /= 2;
5574 rect.size.height /= 2;
5576 rect.origin.x = 36 - rect.size.width / 2;
5577 rect.origin.y = 36 - rect.size.height / 2;
5579 [badge_ drawInRect:rect];
5586 UISetColor(commercial_ ? Purple_ : Black_);
5587 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5588 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5591 UISetColor(commercial_ ? Purplish_ : Gray_);
5592 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5594 if (placard_ != nil)
5595 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5600 /* Section Cell {{{ */
5601 @interface SectionCell : CYTableViewCell <
5613 - (void) setSection:(Section *)section editing:(BOOL)editing;
5617 @implementation SectionCell
5619 - (void) clearSection {
5620 if (basic_ != nil) {
5625 if (section_ != nil) {
5635 if (count_ != nil) {
5642 [self clearSection];
5648 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5649 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5650 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5651 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5652 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5654 UIView *content([self contentView]);
5655 CGRect bounds([content bounds]);
5657 content_ = [[ContentView alloc] initWithFrame:bounds];
5658 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5659 [content addSubview:content_];
5660 [content_ setBackgroundColor:[UIColor whiteColor]];
5662 [content_ setDelegate:self];
5666 - (void) onSwitch:(id)sender {
5667 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5668 if (metadata == nil) {
5669 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5670 [Sections_ setObject:metadata forKey:basic_];
5673 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5677 - (void) setSection:(Section *)section editing:(BOOL)editing {
5678 if (editing != editing_) {
5680 [switch_ removeFromSuperview];
5682 [self addSubview:switch_];
5686 [self clearSection];
5688 if (section == nil) {
5689 name_ = [UCLocalize("ALL_PACKAGES") retain];
5692 basic_ = [section name];
5694 basic_ = [basic_ retain];
5696 section_ = [section localized];
5697 if (section_ != nil)
5698 section_ = [section_ retain];
5700 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5701 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5704 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5707 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5708 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5710 [content_ setNeedsDisplay];
5713 - (void) setFrame:(CGRect)frame {
5714 [super setFrame:frame];
5716 CGRect rect([switch_ frame]);
5717 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5720 - (NSString *) accessibilityLabel {
5724 - (void) drawContentRect:(CGRect)rect {
5725 bool highlighted(highlighted_ && !editing_);
5727 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5732 float width(rect.size.width);
5738 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5740 CGSize size = [count_ sizeWithFont:Font14_];
5744 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5750 /* File Table {{{ */
5751 @interface FileTable : CYViewController <
5752 UITableViewDataSource,
5755 _transient Database *database_;
5758 NSMutableArray *files_;
5762 - (id) initWithDatabase:(Database *)database;
5763 - (void) setPackage:(Package *)package;
5767 @implementation FileTable
5770 [self releaseSubviews];
5779 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5780 return files_ == nil ? 0 : [files_ count];
5783 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5787 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5788 static NSString *reuseIdentifier = @"Cell";
5790 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5792 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5793 [cell setFont:[UIFont systemFontOfSize:16]];
5795 [cell setText:[files_ objectAtIndex:indexPath.row]];
5796 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5801 - (NSURL *) navigationURL {
5802 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5806 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5808 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5809 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5810 [list_ setRowHeight:24.0f];
5811 [list_ setDataSource:self];
5812 [list_ setDelegate:self];
5813 [[self view] addSubview:list_];
5816 - (void) viewDidLoad {
5817 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5820 - (void) releaseSubviews {
5825 - (id) initWithDatabase:(Database *)database {
5826 if ((self = [super init]) != nil) {
5827 database_ = database;
5829 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5833 - (void) setPackage:(Package *)package {
5834 if (package_ != nil) {
5835 [package_ autorelease];
5844 [files_ removeAllObjects];
5846 if (package != nil) {
5847 package_ = [package retain];
5848 name_ = [[package id] retain];
5850 if (NSArray *files = [package files])
5851 [files_ addObjectsFromArray:files];
5853 if ([files_ count] != 0) {
5854 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5855 [files_ removeObjectAtIndex:0];
5856 [files_ sortUsingSelector:@selector(compareByPath:)];
5858 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5859 [stack addObject:@"/"];
5861 for (int i(0), e([files_ count]); i != e; ++i) {
5862 NSString *file = [files_ objectAtIndex:i];
5863 while (![file hasPrefix:[stack lastObject]])
5864 [stack removeLastObject];
5865 NSString *directory = [stack lastObject];
5866 [stack addObject:[file stringByAppendingString:@"/"]];
5867 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5868 ([stack count] - 2) * 3, "",
5869 [file substringFromIndex:[directory length]]
5878 - (void) reloadData {
5881 [self setPackage:[database_ packageWithName:name_]];
5886 /* Package Controller {{{ */
5887 @interface CYPackageController : CYBrowserController <
5888 UIActionSheetDelegate
5890 _transient Database *database_;
5891 _H<Package> package_;
5894 _H<NSMutableArray> buttons_;
5895 _H<UIBarButtonItem> button_;
5898 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5902 @implementation CYPackageController
5904 - (NSURL *) navigationURL {
5905 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5908 - (bool) _allowNavigationAction {
5909 // XXX: damn it... I really want this.
5913 /* XXX: this is not safe at all... localization of /fail/ */
5914 - (void) _clickButtonWithName:(NSString *)name {
5915 if ([name isEqualToString:UCLocalize("CLEAR")])
5916 [delegate_ clearPackage:package_];
5917 else if ([name isEqualToString:UCLocalize("INSTALL")])
5918 [delegate_ installPackage:package_];
5919 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5920 [delegate_ installPackage:package_];
5921 else if ([name isEqualToString:UCLocalize("REMOVE")])
5922 [delegate_ removePackage:package_];
5923 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5924 [delegate_ installPackage:package_];
5925 else _assert(false);
5928 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5929 NSString *context([sheet context]);
5931 if ([context isEqualToString:@"modify"]) {
5932 if (button != [sheet cancelButtonIndex]) {
5933 NSString *buttonName = [buttons_ objectAtIndex:button];
5934 [self _clickButtonWithName:buttonName];
5937 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5941 - (bool) _allowJavaScriptPanel {
5946 - (void) _customButtonClicked {
5947 int count([buttons_ count]);
5952 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5954 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5955 [buttons addObjectsFromArray:buttons_];
5957 UIActionSheet *sheet = [[[UIActionSheet alloc]
5960 cancelButtonTitle:nil
5961 destructiveButtonTitle:nil
5962 otherButtonTitles:nil
5965 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5967 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5968 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5970 [sheet setContext:@"modify"];
5972 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5976 // We don't want to allow non-commercial packages to do custom things to the install button,
5977 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5978 - (void) customButtonClicked {
5980 [super customButtonClicked];
5982 [self _customButtonClicked];
5985 - (void) reloadButtonClicked {
5986 // Don't reload a commerical package by tapping the loading button,
5987 // but if it's not an Install button, we should forward it on.
5988 if (![package_ uninstalled])
5989 [self _customButtonClicked];
5992 - (void) applyLoadingTitle {
5993 // Don't show "Loading" as the title. Ever.
5996 - (UIBarButtonItem *) rightButton {
6001 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
6002 if ((self = [super init]) != nil) {
6003 database_ = database;
6004 buttons_ = [NSMutableArray arrayWithCapacity:4];
6005 name_ = [NSString stringWithString:name];
6006 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
6010 - (void) reloadData {
6011 package_ = [database_ packageWithName:name_];
6013 [buttons_ removeAllObjects];
6015 if (package_ != nil) {
6016 [(Package *) package_ parse];
6018 commercial_ = [package_ isCommercial];
6020 if ([package_ mode] != nil)
6021 [buttons_ addObject:UCLocalize("CLEAR")];
6022 if ([package_ source] == nil);
6023 else if ([package_ upgradableAndEssential:NO])
6024 [buttons_ addObject:UCLocalize("UPGRADE")];
6025 else if ([package_ uninstalled])
6026 [buttons_ addObject:UCLocalize("INSTALL")];
6028 [buttons_ addObject:UCLocalize("REINSTALL")];
6029 if (![package_ uninstalled])
6030 [buttons_ addObject:UCLocalize("REMOVE")];
6034 switch ([buttons_ count]) {
6035 case 0: title = nil; break;
6036 case 1: title = [buttons_ objectAtIndex:0]; break;
6037 default: title = UCLocalize("MODIFY"); break;
6040 button_ = [[[UIBarButtonItem alloc]
6042 style:UIBarButtonItemStylePlain
6044 action:@selector(customButtonClicked)
6050 - (bool) isLoading {
6051 return commercial_ ? [super isLoading] : false;
6057 /* Package List Controller {{{ */
6058 @interface PackageListController : CYViewController <
6059 UITableViewDataSource,
6062 _transient Database *database_;
6064 NSMutableArray *packages_;
6065 NSMutableArray *sections_;
6067 NSMutableArray *index_;
6068 NSMutableDictionary *indices_;
6072 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6073 - (void) setDelegate:(id)delegate;
6074 - (void) resetCursor;
6078 @implementation PackageListController
6081 [packages_ release];
6082 [sections_ release];
6091 - (void) deselectWithAnimation:(BOOL)animated {
6092 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6095 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6096 CGRect base = [[self view] bounds];
6097 base.size.height -= bounds.size.height;
6098 base.origin = [list_ frame].origin;
6100 [UIView beginAnimations:nil context:NULL];
6101 [UIView setAnimationBeginsFromCurrentState:YES];
6102 [UIView setAnimationCurve:curve];
6103 [UIView setAnimationDuration:duration];
6104 [list_ setFrame:base];
6105 [UIView commitAnimations];
6108 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6109 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6112 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6113 [self resizeForKeyboardBounds:bounds duration:0];
6116 - (void) keyboardWillShow:(NSNotification *)notification {
6119 NSTimeInterval duration;
6120 UIViewAnimationCurve curve;
6121 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6122 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6123 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6124 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6126 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);
6127 UIViewController *base = self;
6128 while ([base parentViewController] != nil)
6129 base = [base parentViewController];
6130 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6131 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6133 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6136 - (void) keyboardWillHide:(NSNotification *)notification {
6137 NSTimeInterval duration;
6138 UIViewAnimationCurve curve;
6139 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6140 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6142 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6145 - (void) viewWillAppear:(BOOL)animated {
6146 [super viewWillAppear:animated];
6148 [self resizeForKeyboardBounds:CGRectZero];
6149 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6150 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6153 - (void) viewWillDisappear:(BOOL)animated {
6154 [super viewWillDisappear:animated];
6156 [self resizeForKeyboardBounds:CGRectZero];
6157 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6158 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6161 - (void) viewDidAppear:(BOOL)animated {
6162 [super viewDidAppear:animated];
6163 [self deselectWithAnimation:animated];
6166 - (void) didSelectPackage:(Package *)package {
6167 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6168 [view setDelegate:delegate_];
6169 [[self navigationController] pushViewController:view animated:YES];
6172 #if TryIndexedCollation
6173 + (BOOL) hasIndexedCollation {
6174 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6178 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6179 NSInteger count([sections_ count]);
6180 return count == 0 ? 1 : count;
6183 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6184 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6186 return [[sections_ objectAtIndex:section] name];
6189 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6190 if ([sections_ count] == 0)
6192 return [[sections_ objectAtIndex:section] count];
6195 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6196 @synchronized (database_) {
6197 if ([database_ era] != era_)
6200 Section *section([sections_ objectAtIndex:[path section]]);
6201 NSInteger row([path row]);
6202 Package *package([packages_ objectAtIndex:([section row] + row)]);
6203 return [[package retain] autorelease];
6206 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6207 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6209 cell = [[[PackageCell alloc] init] autorelease];
6210 [cell setPackage:[self packageAtIndexPath:path]];
6214 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6215 Package *package([self packageAtIndexPath:path]);
6216 package = [database_ packageWithName:[package id]];
6217 [self didSelectPackage:package];
6220 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6221 // XXX: is 20 the most optimal number here?
6222 return [packages_ count] > 20 ? index_ : nil;
6225 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6226 #if TryIndexedCollation
6227 if ([[self class] hasIndexedCollation]) {
6228 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6235 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6236 if ((self = [super init]) != nil) {
6237 database_ = database;
6238 title_ = [title copy];
6239 [[self navigationItem] setTitle:title_];
6241 #if TryIndexedCollation
6242 if ([[self class] hasIndexedCollation])
6243 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6246 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6248 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6250 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6251 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6253 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6254 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6255 [list_ setRowHeight:73];
6256 [[self view] addSubview:list_];
6258 [list_ setDataSource:self];
6259 [list_ setDelegate:self];
6263 - (void) setDelegate:(id)delegate {
6264 delegate_ = delegate;
6267 - (bool) hasPackage:(Package *)package {
6271 - (void) reloadData {
6274 era_ = [database_ era];
6275 NSArray *packages = [database_ packages];
6277 [packages_ removeAllObjects];
6278 [sections_ removeAllObjects];
6280 _profile(PackageTable$reloadData$Filter)
6281 for (Package *package in packages)
6282 if ([self hasPackage:package])
6283 [packages_ addObject:package];
6286 [indices_ removeAllObjects];
6288 Section *section = nil;
6290 #if TryIndexedCollation
6291 if ([[self class] hasIndexedCollation]) {
6292 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6293 NSArray *titles = [collation sectionIndexTitles];
6296 _profile(PackageTable$reloadData$Section)
6297 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6301 _profile(PackageTable$reloadData$Section$Package)
6302 package = [packages_ objectAtIndex:offset];
6303 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6306 while (secidx < index) {
6309 _profile(PackageTable$reloadData$Section$Allocate)
6310 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6313 _profile(PackageTable$reloadData$Section$Add)
6314 [sections_ addObject:section];
6318 [section addToCount];
6324 [index_ removeAllObjects];
6326 _profile(PackageTable$reloadData$Section)
6327 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6331 _profile(PackageTable$reloadData$Section$Package)
6332 package = [packages_ objectAtIndex:offset];
6333 index = [package index];
6336 if (section == nil || [section index] != index) {
6337 _profile(PackageTable$reloadData$Section$Allocate)
6338 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6341 [index_ addObject:[section name]];
6342 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6344 _profile(PackageTable$reloadData$Section$Add)
6345 [sections_ addObject:section];
6349 [section addToCount];
6354 _profile(PackageTable$reloadData$List)
6359 - (void) resetCursor {
6360 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6365 /* Filtered Package List Controller {{{ */
6366 @interface FilteredPackageListController : PackageListController {
6372 - (void) setObject:(id)object;
6373 - (void) setObject:(id)object forFilter:(SEL)filter;
6375 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6379 @implementation FilteredPackageListController
6387 - (void) setFilter:(SEL)filter {
6390 /* XXX: this is an unsafe optimization of doomy hell */
6391 Method method(class_getInstanceMethod([Package class], filter));
6392 _assert(method != NULL);
6393 imp_ = method_getImplementation(method);
6394 _assert(imp_ != NULL);
6397 - (void) setObject:(id)object {
6403 object_ = [object retain];
6406 - (void) setObject:(id)object forFilter:(SEL)filter {
6407 [self setFilter:filter];
6408 [self setObject:object];
6411 - (bool) hasPackage:(Package *)package {
6412 _profile(FilteredPackageTable$hasPackage)
6413 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6417 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6418 if ((self = [super initWithDatabase:database title:title]) != nil) {
6419 [self setFilter:filter];
6420 [self setObject:object];
6427 /* Home Controller {{{ */
6428 @interface HomeController : CYBrowserController {
6433 @implementation HomeController
6436 if ((self = [super init]) != nil) {
6437 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6441 - (NSURL *) navigationURL {
6442 return [NSURL URLWithString:@"cydia://home"];
6445 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6446 [super _setMoreHeaders:request];
6449 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6450 if (UniqueID_ != nil)
6451 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6453 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6456 - (void) aboutButtonClicked {
6457 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6459 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6460 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6461 [alert setCancelButtonIndex:0];
6464 @"Copyright (C) 2008-2011\n"
6465 "Jay Freeman (saurik)\n"
6466 "saurik@saurik.com\n"
6467 "http://www.saurik.com/"
6473 - (void) viewDidLoad {
6474 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6475 initWithTitle:UCLocalize("ABOUT")
6476 style:UIBarButtonItemStylePlain
6478 action:@selector(aboutButtonClicked)
6484 /* Manage Controller {{{ */
6485 @interface ManageController : CYBrowserController {
6488 - (void) queueStatusDidChange;
6492 @implementation ManageController
6495 if ((self = [super init]) != nil) {
6496 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6500 - (NSURL *) navigationURL {
6501 return [NSURL URLWithString:@"cydia://manage"];
6504 - (void) viewDidLoad {
6505 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6506 initWithTitle:UCLocalize("SETTINGS")
6507 style:UIBarButtonItemStylePlain
6509 action:@selector(settingsButtonClicked)
6512 [self queueStatusDidChange];
6515 - (void) settingsButtonClicked {
6516 [delegate_ showSettings];
6520 - (void) queueButtonClicked {
6524 - (void) applyLoadingTitle {
6525 // Disable "Loading" title.
6528 - (void) applyRightButton {
6529 // Disable right button.
6533 - (void) queueStatusDidChange {
6535 if (!IsWildcat_ && Queuing_) {
6536 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6537 initWithTitle:UCLocalize("QUEUE")
6538 style:UIBarButtonItemStyleDone
6540 action:@selector(queueButtonClicked)
6543 [[self navigationItem] setRightBarButtonItem:nil];
6548 - (bool) isLoading {
6549 // Never show as loading.
6556 /* Refresh Bar {{{ */
6557 @interface RefreshBar : UINavigationBar {
6558 UIProgressIndicator *indicator_;
6559 UITextLabel *prompt_;
6560 UIProgressBar *progress_;
6561 UINavigationButton *cancel_;
6566 @implementation RefreshBar
6569 [indicator_ release];
6571 [progress_ release];
6576 - (void) positionViews {
6577 CGRect frame = [cancel_ frame];
6578 frame.size = [cancel_ sizeThatFits:frame.size];
6579 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6580 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6581 [cancel_ setFrame:frame];
6583 CGSize prgsize = {75, 100};
6585 [self frame].size.width - prgsize.width - 10,
6586 ([self frame].size.height - prgsize.height) / 2
6588 [progress_ setFrame:prgrect];
6590 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6591 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6592 CGRect indrect = {{indoffset, indoffset}, indsize};
6593 [indicator_ setFrame:indrect];
6595 CGSize prmsize = {215, indsize.height + 4};
6597 indoffset * 2 + indsize.width,
6598 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6600 [prompt_ setFrame:prmrect];
6603 - (void) setFrame:(CGRect)frame {
6604 [super setFrame:frame];
6605 [self positionViews];
6608 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6609 if ((self = [super initWithFrame:frame]) != nil) {
6610 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6612 [self setBarStyle:UIBarStyleBlack];
6614 UIBarStyle barstyle([self _barStyle:NO]);
6615 bool ugly(barstyle == UIBarStyleDefault);
6617 UIProgressIndicatorStyle style = ugly ?
6618 UIProgressIndicatorStyleMediumBrown :
6619 UIProgressIndicatorStyleMediumWhite;
6621 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6622 [indicator_ setStyle:style];
6623 [indicator_ startAnimation];
6624 [self addSubview:indicator_];
6626 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6627 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6628 [prompt_ setBackgroundColor:[UIColor clearColor]];
6629 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6630 [self addSubview:prompt_];
6632 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6633 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6634 [progress_ setStyle:0];
6635 [self addSubview:progress_];
6637 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6638 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6639 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6640 [cancel_ setBarStyle:barstyle];
6642 [self positionViews];
6646 - (void) setCancellable:(bool)cancellable {
6648 [self addSubview:cancel_];
6650 [cancel_ removeFromSuperview];
6654 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6655 [progress_ setProgress:0];
6659 [self setCancellable:NO];
6662 - (void) setPrompt:(NSString *)prompt {
6663 [prompt_ setText:prompt];
6666 - (void) setProgress:(float)progress {
6667 [progress_ setProgress:progress];
6673 @class CYNavigationController;
6675 /* Cydia Tab Bar Controller {{{ */
6676 @interface CYTabBarController : UITabBarController <
6677 UITabBarControllerDelegate,
6680 _transient Database *database_;
6681 RefreshBar *refreshbar_;
6685 // XXX: ok, "updatedelegate_"?...
6686 _transient NSObject<CydiaDelegate> *updatedelegate_;
6689 UIViewController *remembered_;
6690 _transient UIViewController *transient_;
6693 - (NSArray *) navigationURLCollection;
6694 - (void) dropBar:(BOOL)animated;
6695 - (void) beginUpdate;
6696 - (void) raiseBar:(BOOL)animated;
6701 @implementation CYTabBarController
6703 - (void) setUnselectedViewController:(UIViewController *)transient {
6704 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6705 if (transient != nil) {
6706 if (transient_ == nil)
6707 remembered_ = [[controllers objectAtIndex:0] retain];
6708 transient_ = transient;
6709 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6710 [controllers replaceObjectAtIndex:0 withObject:transient_];
6711 [self setSelectedIndex:0];
6712 [self setViewControllers:controllers];
6713 [self concealTabBarSelection];
6714 } else if (remembered_ != nil) {
6715 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6716 transient_ = transient;
6717 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6718 [remembered_ release];
6720 [self setViewControllers:controllers];
6721 [self revealTabBarSelection];
6725 - (UIViewController *) unselectedViewController {
6729 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6730 if ([self unselectedViewController])
6731 [self setUnselectedViewController:nil];
6734 - (NSArray *) navigationURLCollection {
6735 NSMutableArray *items([NSMutableArray array]);
6737 // XXX: Should this deal with transient view controllers?
6738 for (id navigation in [self viewControllers]) {
6739 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6741 [items addObject:stack];
6747 - (void) reloadData {
6748 for (CYViewController *controller in [self viewControllers])
6749 [controller reloadData];
6751 [(CYNavigationController *)[self unselectedViewController] reloadData];
6755 [refreshbar_ release];
6756 [[NSNotificationCenter defaultCenter] removeObserver:self];
6761 - (id) initWithDatabase:(Database *)database {
6762 if ((self = [super init]) != nil) {
6763 database_ = database;
6764 [self setDelegate:self];
6766 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6767 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6769 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6773 - (void) setUpdate:(NSDate *)date {
6777 - (void) beginUpdate {
6778 [refreshbar_ start];
6781 [updatedelegate_ retainNetworkActivityIndicator];
6785 detachNewThreadSelector:@selector(performUpdate)
6791 - (void) performUpdate { _pooled
6793 status.setDelegate(self);
6794 [database_ updateWithStatus:status];
6797 performSelectorOnMainThread:@selector(completeUpdate)
6803 - (void) stopUpdateWithSelector:(SEL)selector {
6805 [updatedelegate_ releaseNetworkActivityIndicator];
6807 [self raiseBar:YES];
6810 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6813 - (void) completeUpdate {
6816 [self stopUpdateWithSelector:@selector(reloadData)];
6819 - (void) cancelUpdate {
6820 [self stopUpdateWithSelector:@selector(updateData)];
6823 - (void) cancelPressed {
6824 [self cancelUpdate];
6831 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6832 [refreshbar_ setPrompt:[event compoundMessage]];
6835 - (bool) isProgressCancelled {
6839 - (void) setProgressCancellable:(NSNumber *)cancellable {
6840 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6843 - (void) setProgressPercent:(NSNumber *)percent {
6844 [refreshbar_ setProgress:[percent floatValue]];
6847 - (void) setProgressStatus:(NSDictionary *)status {
6849 [self setProgressPercent:[status objectForKey:@"Percent"]];
6852 - (void) setUpdateDelegate:(id)delegate {
6853 updatedelegate_ = delegate;
6856 - (CGFloat) statusBarHeight {
6857 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6858 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6860 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6864 - (UIView *) transitionView {
6865 if ([self respondsToSelector:@selector(_transitionView)])
6866 return [self _transitionView];
6868 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6871 - (void) dropBar:(BOOL)animated {
6876 UIView *transition([self transitionView]);
6877 [[self view] addSubview:refreshbar_];
6879 CGRect barframe([refreshbar_ frame]);
6881 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6882 barframe.origin.y = [self statusBarHeight];
6884 barframe.origin.y = 0;
6886 [refreshbar_ setFrame:barframe];
6889 [UIView beginAnimations:nil context:NULL];
6891 CGRect viewframe = [transition frame];
6892 viewframe.origin.y += barframe.size.height;
6893 viewframe.size.height -= barframe.size.height;
6894 [transition setFrame:viewframe];
6897 [UIView commitAnimations];
6899 // Ensure bar has the proper width for our view, it might have changed
6900 barframe.size.width = viewframe.size.width;
6901 [refreshbar_ setFrame:barframe];
6903 // XXX: fix Apple's layout bug
6904 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6907 - (void) raiseBar:(BOOL)animated {
6912 UIView *transition([self transitionView]);
6913 [refreshbar_ removeFromSuperview];
6915 CGRect barframe([refreshbar_ frame]);
6918 [UIView beginAnimations:nil context:NULL];
6920 CGRect viewframe = [transition frame];
6921 viewframe.origin.y -= barframe.size.height;
6922 viewframe.size.height += barframe.size.height;
6923 [transition setFrame:viewframe];
6926 [UIView commitAnimations];
6928 // XXX: fix Apple's layout bug
6929 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6933 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6934 // XXX: fix Apple's layout bug
6935 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6939 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6940 bool dropped(dropped_);
6945 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6950 // XXX: fix Apple's layout bug
6951 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6954 - (void) statusBarFrameChanged:(NSNotification *)notification {
6963 /* Cydia Navigation Controller {{{ */
6964 @interface CYNavigationController : UINavigationController {
6965 _transient Database *database_;
6966 _transient id<UINavigationControllerDelegate> delegate_;
6969 - (NSArray *) navigationURLCollection;
6970 - (id) initWithDatabase:(Database *)database;
6971 - (void) reloadData;
6976 @implementation CYNavigationController
6978 - (NSArray *) navigationURLCollection {
6979 NSMutableArray *stack([NSMutableArray array]);
6981 for (CYViewController *controller in [self viewControllers]) {
6982 NSString *url = [[controller navigationURL] absoluteString];
6984 [stack addObject:url];
6990 - (void) reloadData {
6991 for (CYViewController *page in [self viewControllers]) {
6992 // Only reload controllers that have already loaded.
6993 // This prevents a page from accidentally loading too
6994 // early if it hasn't been shown on the screen yet.
6995 if ([page hasLoaded])
7000 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
7001 delegate_ = delegate;
7004 - (id) initWithDatabase:(Database *)database {
7005 if ((self = [super init]) != nil) {
7006 database_ = database;
7013 /* Cydia:// Protocol {{{ */
7014 @interface CydiaURLProtocol : NSURLProtocol {
7019 @implementation CydiaURLProtocol
7021 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7022 NSURL *url([request URL]);
7026 NSString *scheme([[url scheme] lowercaseString]);
7027 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7029 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7035 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7039 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7040 id<NSURLProtocolClient> client([self client]);
7042 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7044 NSData *data(UIImagePNGRepresentation(icon));
7046 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7047 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7048 [client URLProtocol:self didLoadData:data];
7049 [client URLProtocolDidFinishLoading:self];
7053 - (void) startLoading {
7054 id<NSURLProtocolClient> client([self client]);
7055 NSURLRequest *request([self request]);
7057 NSURL *url([request URL]);
7058 NSString *href([url absoluteString]);
7059 NSString *scheme([[url scheme] lowercaseString]);
7063 if ([scheme isEqualToString:@"cydia"])
7064 path = [href substringFromIndex:8];
7065 else if ([scheme isEqualToString:@"about"])
7066 path = [href substringFromIndex:12];
7067 else _assert(false);
7069 NSRange slash([path rangeOfString:@"/"]);
7072 if (slash.location == NSNotFound) {
7076 command = [path substringToIndex:slash.location];
7077 path = [path substringFromIndex:(slash.location + 1)];
7080 Database *database([Database sharedInstance]);
7082 if ([command isEqualToString:@"package-icon"]) {
7085 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7086 Package *package([database packageWithName:path]);
7089 UIImage *icon([package icon]);
7090 [self _returnPNGWithImage:icon forRequest:request];
7091 } else if ([command isEqualToString:@"source-icon"]) {
7094 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7095 NSString *source(Simplify(path));
7096 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7098 icon = [UIImage applicationImageNamed:@"unknown.png"];
7099 [self _returnPNGWithImage:icon forRequest:request];
7100 } else if ([command isEqualToString:@"uikit-image"]) {
7103 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7104 UIImage *icon(_UIImageWithName(path));
7105 [self _returnPNGWithImage:icon forRequest:request];
7106 } else if ([command isEqualToString:@"section-icon"]) {
7109 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7110 NSString *section(Simplify(path));
7111 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7113 icon = [UIImage applicationImageNamed:@"unknown.png"];
7114 [self _returnPNGWithImage:icon forRequest:request];
7116 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7120 - (void) stopLoading {
7126 /* Section Controller {{{ */
7127 @interface SectionController : FilteredPackageListController {
7128 _H<NSString> section_;
7131 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7135 @implementation SectionController
7137 - (NSURL *) navigationURL {
7138 NSString *name = section_;
7142 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7145 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7148 title = UCLocalize("ALL_PACKAGES");
7149 else if (![name isEqual:@""])
7150 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7152 title = UCLocalize("NO_SECTION");
7154 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7161 /* Sections Controller {{{ */
7162 @interface SectionsController : CYViewController <
7163 UITableViewDataSource,
7166 _transient Database *database_;
7167 NSMutableArray *sections_;
7168 NSMutableArray *filtered_;
7173 - (id) initWithDatabase:(Database *)database;
7174 - (void) editButtonClicked;
7178 @implementation SectionsController
7181 [self releaseSubviews];
7182 [sections_ release];
7183 [filtered_ release];
7188 - (NSURL *) navigationURL {
7189 return [NSURL URLWithString:@"cydia://sections"];
7192 - (void) updateNavigationItem {
7193 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7194 if ([sections_ count] == 0) {
7195 [[self navigationItem] setRightBarButtonItem:nil];
7197 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7198 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7200 action:@selector(editButtonClicked)
7201 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7205 - (BOOL) isEditing {
7209 - (void) setEditing:(BOOL)editing {
7210 if ((editing_ = editing))
7213 [delegate_ updateData];
7215 [self updateNavigationItem];
7218 - (void) viewDidAppear:(BOOL)animated {
7219 [super viewDidAppear:animated];
7220 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7223 - (void) viewWillDisappear:(BOOL)animated {
7224 [super viewWillDisappear:animated];
7225 if (editing_) [self setEditing:NO];
7228 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7229 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7233 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7234 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7237 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7241 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7242 static NSString *reuseIdentifier = @"SectionCell";
7244 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7246 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7248 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7253 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7257 Section *section = [self sectionAtIndexPath:indexPath];
7259 SectionController *controller = [[[SectionController alloc]
7260 initWithDatabase:database_
7261 section:[section name]
7263 [controller setDelegate:delegate_];
7265 [[self navigationController] pushViewController:controller animated:YES];
7269 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7271 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7272 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7273 [list_ setRowHeight:45.0f];
7274 [list_ setDataSource:self];
7275 [list_ setDelegate:self];
7276 [[self view] addSubview:list_];
7279 - (void) viewDidLoad {
7280 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7283 - (void) releaseSubviews {
7288 - (id) initWithDatabase:(Database *)database {
7289 if ((self = [super init]) != nil) {
7290 database_ = database;
7292 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7293 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7297 - (void) reloadData {
7300 NSArray *packages = [database_ packages];
7302 [sections_ removeAllObjects];
7303 [filtered_ removeAllObjects];
7305 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7308 for (Package *package in packages) {
7309 NSString *name([package section]);
7310 NSString *key(name == nil ? @"" : name);
7314 _profile(SectionsView$reloadData$Section)
7315 section = [sections objectForKey:key];
7316 if (section == nil) {
7317 _profile(SectionsView$reloadData$Section$Allocate)
7318 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7319 [sections setObject:section forKey:key];
7324 [section addToCount];
7326 _profile(SectionsView$reloadData$Filter)
7327 if (![package valid] || ![package visible])
7335 [sections_ addObjectsFromArray:[sections allValues]];
7337 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7339 for (Section *section in sections_) {
7340 size_t count([section row]);
7344 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7345 [section setCount:count];
7346 [filtered_ addObject:section];
7349 [self updateNavigationItem];
7354 - (void) editButtonClicked {
7355 [self setEditing:(!editing_)];
7361 /* Changes Controller {{{ */
7362 @interface ChangesController : CYViewController <
7363 UITableViewDataSource,
7366 _transient Database *database_;
7368 CFMutableArrayRef packages_;
7369 NSMutableArray *sections_;
7372 BOOL hasSentFirstLoad_;
7375 - (id) initWithDatabase:(Database *)database;
7379 @implementation ChangesController
7382 [self releaseSubviews];
7383 CFRelease(packages_);
7384 [sections_ release];
7389 - (NSURL *) navigationURL {
7390 return [NSURL URLWithString:@"cydia://changes"];
7393 - (void) viewWillAppear:(BOOL)animated {
7394 // Loads after it appears, so don't load beforehand.
7396 [super viewWillAppear:animated];
7399 - (void) viewDidAppear:(BOOL)animated {
7400 [super viewDidAppear:animated];
7402 if (!hasSentFirstLoad_) {
7403 hasSentFirstLoad_ = YES;
7404 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7406 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7410 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7411 NSInteger count([sections_ count]);
7412 return count == 0 ? 1 : count;
7415 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7416 if ([sections_ count] == 0)
7418 return [[sections_ objectAtIndex:section] name];
7421 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7422 if ([sections_ count] == 0)
7424 return [[sections_ objectAtIndex:section] count];
7427 - (Package *) packageAtIndex:(NSUInteger)index {
7428 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7431 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7432 @synchronized (database_) {
7433 if ([database_ era] != era_)
7436 NSUInteger sectionIndex([path section]);
7437 if (sectionIndex >= [sections_ count])
7439 Section *section([sections_ objectAtIndex:sectionIndex]);
7440 NSInteger row([path row]);
7441 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7444 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7445 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7447 cell = [[[PackageCell alloc] init] autorelease];
7448 [cell setPackage:[self packageAtIndexPath:path]];
7452 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7453 Package *package([self packageAtIndexPath:path]);
7454 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7455 [view setDelegate:delegate_];
7456 [[self navigationController] pushViewController:view animated:YES];
7460 - (void) refreshButtonClicked {
7461 [delegate_ beginUpdate];
7462 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7465 - (void) upgradeButtonClicked {
7466 [delegate_ distUpgrade];
7470 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7472 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7473 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7474 [list_ setRowHeight:73];
7475 [list_ setDataSource:self];
7476 [list_ setDelegate:self];
7477 [[self view] addSubview:list_];
7480 - (void) viewDidLoad {
7481 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7484 - (void) releaseSubviews {
7489 - (id) initWithDatabase:(Database *)database {
7490 if ((self = [super init]) != nil) {
7491 database_ = database;
7493 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7494 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7498 // this mostly works because reloadData (below) is @synchronized (database_)
7499 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7500 - (void) _reloadPackages:(NSArray *)packages {
7501 CFRelease(packages_);
7502 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7505 _profile(ChangesController$_reloadPackages$Filter)
7506 for (Package *package in packages)
7507 if ([package upgradableAndEssential:YES] || [package visible])
7508 CFArrayAppendValue(packages_, package);
7511 _profile(ChangesController$_reloadPackages$radixSort)
7512 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7517 - (void) reloadData {
7518 @synchronized (database_) {
7519 era_ = [database_ era];
7520 NSArray *packages = [database_ packages];
7522 [sections_ removeAllObjects];
7525 UIProgressHUD *hud([delegate_ addProgressHUD]);
7526 [hud setText:UCLocalize("LOADING")];
7527 //NSLog(@"HUD:%@::%@", delegate_, hud);
7528 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7529 [delegate_ removeProgressHUD:hud];
7531 [self _reloadPackages:packages];
7534 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7535 Section *ignored = nil;
7536 Section *section = nil;
7540 bool unseens = false;
7542 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7544 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7545 Package *package = [self packageAtIndex:offset];
7547 BOOL uae = [package upgradableAndEssential:YES];
7551 time_t seen([package seen]);
7553 if (section == nil || last != seen) {
7557 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7560 _profile(ChangesController$reloadData$Allocate)
7561 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7562 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7563 [sections_ addObject:section];
7567 [section addToCount];
7568 } else if ([package ignored]) {
7569 if (ignored == nil) {
7570 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7572 [ignored addToCount];
7575 [upgradable addToCount];
7580 CFRelease(formatter);
7583 Section *last = [sections_ lastObject];
7584 size_t count = [last count];
7585 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7586 [sections_ removeLastObject];
7589 if ([ignored count] != 0)
7590 [sections_ insertObject:ignored atIndex:0];
7592 [sections_ insertObject:upgradable atIndex:0];
7597 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7598 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7599 style:UIBarButtonItemStylePlain
7601 action:@selector(upgradeButtonClicked)
7604 if (![delegate_ updating])
7605 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7606 initWithTitle:UCLocalize("REFRESH")
7607 style:UIBarButtonItemStylePlain
7609 action:@selector(refreshButtonClicked)
7617 /* Search Controller {{{ */
7618 @interface SearchController : FilteredPackageListController <
7621 UISearchBar *search_;
7625 - (id) initWithDatabase:(Database *)database;
7626 - (void) setSearchTerm:(NSString *)term;
7627 - (void) reloadData;
7631 @implementation SearchController
7638 - (NSURL *) navigationURL {
7639 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7640 return [NSURL URLWithString:@"cydia://search"];
7642 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7645 - (void) setSearchTerm:(NSString *)searchTerm {
7646 [search_ setText:searchTerm];
7650 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7651 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7652 [search_ resignFirstResponder];
7656 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7657 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7661 - (id) initWithDatabase:(Database *)database {
7662 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7663 search_ = [[UISearchBar alloc] init];
7667 - (void) viewDidAppear:(BOOL)animated {
7668 [super viewDidAppear:animated];
7670 if (!searchloaded_) {
7671 searchloaded_ = YES;
7672 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7673 [search_ layoutSubviews];
7674 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7676 UITextField *textField;
7677 if ([search_ respondsToSelector:@selector(searchField)])
7678 textField = [search_ searchField];
7680 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7682 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7683 [search_ setDelegate:self];
7684 [textField setEnablesReturnKeyAutomatically:NO];
7685 [[self navigationItem] setTitleView:textField];
7689 - (void) reloadData {
7690 [self setObject:[search_ text]];
7695 - (void) didSelectPackage:(Package *)package {
7696 [search_ resignFirstResponder];
7697 [super didSelectPackage:package];
7702 /* Package Settings Controller {{{ */
7703 @interface PackageSettingsController : CYViewController <
7704 UITableViewDataSource,
7707 _transient Database *database_;
7710 UITableView *table_;
7711 UISwitch *subscribedSwitch_;
7712 UISwitch *ignoredSwitch_;
7713 UITableViewCell *subscribedCell_;
7714 UITableViewCell *ignoredCell_;
7717 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7721 @implementation PackageSettingsController
7724 [self releaseSubviews];
7731 - (NSURL *) navigationURL {
7732 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7735 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7736 if (package_ == nil)
7739 if ([package_ installed] == nil)
7745 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7746 if (package_ == nil)
7749 // both sections contain just one item right now.
7753 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7757 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7759 return UCLocalize("SHOW_ALL_CHANGES_EX");
7761 return UCLocalize("IGNORE_UPGRADES_EX");
7764 - (void) onSubscribed:(id)control {
7765 bool value([control isOn]);
7766 if (package_ == nil)
7768 if ([package_ setSubscribed:value])
7769 [delegate_ updateData];
7772 - (void) _updateIgnored {
7773 const char *package([name_ UTF8String]);
7774 bool on([ignoredSwitch_ isOn]);
7776 pid_t pid(ExecFork());
7778 FILE *dpkg(popen("dpkg --set-selections", "w"));
7779 fwrite(package, strlen(package), 1, dpkg);
7782 fwrite(" hold\n", 6, 1, dpkg);
7784 fwrite(" install\n", 9, 1, dpkg);
7794 int result(waitpid(pid, &status, 0));
7797 _assert(result == pid);
7803 - (void) onIgnored:(id)control {
7804 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7805 [invocation setTarget:self];
7806 [invocation setSelector:@selector(_updateIgnored)];
7808 [delegate_ reloadDataWithInvocation:invocation];
7811 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7812 if (package_ == nil)
7815 switch ([indexPath section]) {
7816 case 0: return subscribedCell_;
7817 case 1: return ignoredCell_;
7826 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7828 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7829 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7830 [table_ setDataSource:self];
7831 [table_ setDelegate:self];
7832 [[self view] addSubview:table_];
7834 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7835 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7836 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7838 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7839 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7840 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7842 subscribedCell_ = [[UITableViewCell alloc] init];
7843 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7844 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7845 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7847 ignoredCell_ = [[UITableViewCell alloc] init];
7848 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7849 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7850 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7853 - (void) viewDidLoad {
7854 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7857 - (void) releaseSubviews {
7858 [ignoredCell_ release];
7861 [subscribedCell_ release];
7862 subscribedCell_ = nil;
7867 [ignoredSwitch_ release];
7868 ignoredSwitch_ = nil;
7870 [subscribedSwitch_ release];
7871 subscribedSwitch_ = nil;
7874 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7875 if ((self = [super init]) != nil) {
7876 database_ = database;
7877 name_ = [package retain];
7881 - (void) reloadData {
7884 if (package_ != nil)
7885 [package_ autorelease];
7886 package_ = [database_ packageWithName:name_];
7888 if (package_ != nil) {
7889 package_ = [package_ retain];
7890 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7891 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7892 } // XXX: what now, G?
7894 [table_ reloadData];
7900 /* Installed Controller {{{ */
7901 @interface InstalledController : FilteredPackageListController {
7905 - (id) initWithDatabase:(Database *)database;
7907 - (void) updateRoleButton;
7908 - (void) queueStatusDidChange;
7912 @implementation InstalledController
7918 - (NSURL *) navigationURL {
7919 return [NSURL URLWithString:@"cydia://installed"];
7922 - (id) initWithDatabase:(Database *)database {
7923 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7924 [self updateRoleButton];
7925 [self queueStatusDidChange];
7930 - (void) queueButtonClicked {
7935 - (void) queueStatusDidChange {
7939 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7940 initWithTitle:UCLocalize("QUEUE")
7941 style:UIBarButtonItemStyleDone
7943 action:@selector(queueButtonClicked)
7946 [[self navigationItem] setLeftBarButtonItem:nil];
7952 - (void) updateRoleButton {
7953 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7954 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7955 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7956 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7958 action:@selector(roleButtonClicked)
7962 - (void) roleButtonClicked {
7963 [self setObject:[NSNumber numberWithBool:expert_]];
7967 [self updateRoleButton];
7973 /* Source Cell {{{ */
7974 @interface SourceCell : CYTableViewCell <
7982 - (void) setSource:(Source *)source;
7986 @implementation SourceCell
7988 - (void) clearSource {
7998 - (void) setSource:(Source *)source {
8002 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
8004 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8005 icon_ = [icon_ retain];
8007 origin_ = [[source name] retain];
8008 label_ = [[source uri] retain];
8010 [content_ setNeedsDisplay];
8018 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8019 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8020 UIView *content([self contentView]);
8021 CGRect bounds([content bounds]);
8023 content_ = [[ContentView alloc] initWithFrame:bounds];
8024 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8025 [content_ setBackgroundColor:[UIColor whiteColor]];
8026 [content addSubview:content_];
8028 [content_ setDelegate:self];
8029 [content_ setOpaque:YES];
8033 - (NSString *) accessibilityLabel {
8037 - (void) drawContentRect:(CGRect)rect {
8038 bool highlighted(highlighted_);
8039 float width(rect.size.width);
8042 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8049 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8053 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8058 /* Source Controller {{{ */
8059 @interface SourceController : FilteredPackageListController {
8060 _transient Source *source_;
8064 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8068 @implementation SourceController
8070 - (NSURL *) navigationURL {
8071 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8074 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8075 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8077 key_ = [[source key] retain];
8081 - (void) reloadData {
8082 source_ = [database_ sourceWithKey:key_];
8084 key_ = [[source_ key] retain];
8085 [self setObject:source_];
8086 [[self navigationItem] setTitle:[source_ label]];
8093 /* Sources Controller {{{ */
8094 @interface SourcesController : CYViewController <
8095 UITableViewDataSource,
8098 _transient Database *database_;
8100 NSMutableArray *sources_;
8104 UIProgressHUD *hud_;
8107 //NSURLConnection *installer_;
8108 NSURLConnection *trivial_;
8109 NSURLConnection *trivial_bz2_;
8110 NSURLConnection *trivial_gz_;
8111 //NSURLConnection *automatic_;
8116 - (id) initWithDatabase:(Database *)database;
8117 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8121 @implementation SourcesController
8123 - (void) _releaseConnection:(NSURLConnection *)connection {
8124 if (connection != nil) {
8125 [connection cancel];
8126 //[connection setDelegate:nil];
8127 [connection release];
8132 [self releaseSubviews];
8138 //[self _releaseConnection:installer_];
8139 [self _releaseConnection:trivial_];
8140 [self _releaseConnection:trivial_gz_];
8141 [self _releaseConnection:trivial_bz2_];
8142 //[self _releaseConnection:automatic_];
8148 - (NSURL *) navigationURL {
8149 return [NSURL URLWithString:@"cydia://sources"];
8152 - (void) viewDidAppear:(BOOL)animated {
8153 [super viewDidAppear:animated];
8154 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8157 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8158 return offset_ == 0 ? 1 : 2;
8161 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8162 switch (section + (offset_ == 0 ? 1 : 0)) {
8163 case 0: return UCLocalize("ENTERED_BY_USER");
8164 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8170 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8171 int count = [sources_ count];
8173 case 0: return (offset_ == 0 ? count : offset_);
8174 case 1: return count - offset_;
8180 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8182 switch (indexPath.section) {
8183 case 0: idx = indexPath.row; break;
8184 case 1: idx = indexPath.row + offset_; break;
8188 return [sources_ objectAtIndex:idx];
8191 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8192 static NSString *cellIdentifier = @"SourceCell";
8194 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8195 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8196 [cell setSource:[self sourceAtIndexPath:indexPath]];
8197 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8202 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8203 Source *source = [self sourceAtIndexPath:indexPath];
8205 SourceController *controller = [[[SourceController alloc]
8206 initWithDatabase:database_
8210 [controller setDelegate:delegate_];
8212 [[self navigationController] pushViewController:controller animated:YES];
8215 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8216 Source *source = [self sourceAtIndexPath:indexPath];
8217 return [source record] != nil;
8220 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8221 Source *source = [self sourceAtIndexPath:indexPath];
8222 [Sources_ removeObjectForKey:[source key]];
8223 [delegate_ syncData];
8227 [delegate_ addTrivialSource:href_];
8228 [delegate_ syncData];
8231 - (NSString *) getWarning {
8232 NSString *href(href_);
8233 NSRange colon([href rangeOfString:@"://"]);
8234 if (colon.location != NSNotFound)
8235 href = [href substringFromIndex:(colon.location + 3)];
8236 href = [href stringByAddingPercentEscapes];
8237 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8238 href = [href stringByCachingURLWithCurrentCDN];
8240 NSURL *url([NSURL URLWithString:href]);
8242 NSStringEncoding encoding;
8243 NSError *error(nil);
8245 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8246 return [warning length] == 0 ? nil : warning;
8250 - (void) _endConnection:(NSURLConnection *)connection {
8251 // XXX: the memory management in this method is horribly awkward
8253 NSURLConnection **field = NULL;
8254 if (connection == trivial_)
8256 else if (connection == trivial_bz2_)
8257 field = &trivial_bz2_;
8258 else if (connection == trivial_gz_)
8259 field = &trivial_gz_;
8260 _assert(field != NULL);
8261 [connection release];
8266 trivial_bz2_ == nil &&
8272 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8275 UIAlertView *alert = [[[UIAlertView alloc]
8276 initWithTitle:UCLocalize("SOURCE_WARNING")
8279 cancelButtonTitle:UCLocalize("CANCEL")
8281 UCLocalize("ADD_ANYWAY"),
8285 [alert setContext:@"warning"];
8286 [alert setNumberOfRows:1];
8290 } else if (error_ != nil) {
8291 UIAlertView *alert = [[[UIAlertView alloc]
8292 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8293 message:[error_ localizedDescription]
8295 cancelButtonTitle:UCLocalize("OK")
8296 otherButtonTitles:nil
8299 [alert setContext:@"urlerror"];
8302 UIAlertView *alert = [[[UIAlertView alloc]
8303 initWithTitle:UCLocalize("NOT_REPOSITORY")
8304 message:UCLocalize("NOT_REPOSITORY_EX")
8306 cancelButtonTitle:UCLocalize("OK")
8307 otherButtonTitles:nil
8310 [alert setContext:@"trivial"];
8314 [delegate_ releaseNetworkActivityIndicator];
8316 [delegate_ removeProgressHUD:hud_];
8325 if (error_ != nil) {
8332 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8333 switch ([response statusCode]) {
8339 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8340 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8342 error_ = [error retain];
8343 [self _endConnection:connection];
8346 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8347 [self _endConnection:connection];
8350 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8351 NSMutableURLRequest *request = [NSMutableURLRequest
8352 requestWithURL:[NSURL URLWithString:href]
8353 cachePolicy:NSURLRequestUseProtocolCachePolicy
8354 timeoutInterval:120.0
8357 [request setHTTPMethod:method];
8359 if (Machine_ != NULL)
8360 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8361 if (UniqueID_ != nil)
8362 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8364 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8366 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8369 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8370 NSString *context([alert context]);
8372 if ([context isEqualToString:@"source"]) {
8375 NSString *href = [[alert textField] text];
8377 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8379 if (![href hasSuffix:@"/"])
8380 href_ = [href stringByAppendingString:@"/"];
8383 href_ = [href_ retain];
8385 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8386 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8387 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8388 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8392 // XXX: this is stupid
8393 hud_ = [[delegate_ addProgressHUD] retain];
8394 [hud_ setText:UCLocalize("VERIFYING_URL")];
8395 [delegate_ retainNetworkActivityIndicator];
8404 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8405 } else if ([context isEqualToString:@"trivial"])
8406 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8407 else if ([context isEqualToString:@"urlerror"])
8408 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8409 else if ([context isEqualToString:@"warning"]) {
8424 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8429 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8431 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8432 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8433 [list_ setRowHeight:56];
8434 [list_ setDataSource:self];
8435 [list_ setDelegate:self];
8436 [[self view] addSubview:list_];
8439 - (void) viewDidLoad {
8440 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8441 [self updateButtonsForEditingStatus:NO animated:NO];
8444 - (void) releaseSubviews {
8449 - (id) initWithDatabase:(Database *)database {
8450 if ((self = [super init]) != nil) {
8451 database_ = database;
8452 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8456 - (void) reloadData {
8460 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8463 [sources_ removeAllObjects];
8464 [sources_ addObjectsFromArray:[database_ sources]];
8466 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8469 int count([sources_ count]);
8471 for (int i = 0; i != count; i++) {
8472 if ([[sources_ objectAtIndex:i] record] == nil)
8477 [list_ setEditing:NO];
8478 [self updateButtonsForEditingStatus:NO animated:NO];
8482 - (void) showAddSourcePrompt {
8483 UIAlertView *alert = [[[UIAlertView alloc]
8484 initWithTitle:UCLocalize("ENTER_APT_URL")
8487 cancelButtonTitle:UCLocalize("CANCEL")
8489 UCLocalize("ADD_SOURCE"),
8493 [alert setContext:@"source"];
8494 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8496 [alert setNumberOfRows:1];
8497 [alert addTextFieldWithValue:@"http://" label:@""];
8499 UITextInputTraits *traits = [[alert textField] textInputTraits];
8500 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8501 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8502 [traits setKeyboardType:UIKeyboardTypeURL];
8503 // XXX: UIReturnKeyDone
8504 [traits setReturnKeyType:UIReturnKeyNext];
8509 - (void) addButtonClicked {
8510 [self showAddSourcePrompt];
8513 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8514 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8515 initWithTitle:UCLocalize("ADD")
8516 style:UIBarButtonItemStylePlain
8518 action:@selector(addButtonClicked)
8519 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8521 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8522 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8523 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8525 action:@selector(editButtonClicked)
8526 ] autorelease] animated:animated];
8528 if (IsWildcat_ && !editing)
8529 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8530 initWithTitle:UCLocalize("SETTINGS")
8531 style:UIBarButtonItemStylePlain
8533 action:@selector(settingsButtonClicked)
8537 - (void) settingsButtonClicked {
8538 [delegate_ showSettings];
8541 - (void) editButtonClicked {
8542 [list_ setEditing:![list_ isEditing] animated:YES];
8544 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8550 /* Settings Controller {{{ */
8551 @interface SettingsController : CYViewController <
8552 UITableViewDataSource,
8555 _transient Database *database_;
8556 // XXX: ok, "roledelegate_"?...
8557 _transient id roledelegate_;
8558 UITableView *table_;
8559 UISegmentedControl *segment_;
8563 - (void) showDoneButton;
8564 - (void) resizeSegmentedControl;
8568 @implementation SettingsController
8571 [self releaseSubviews];
8577 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8579 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8580 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8581 [table_ setDelegate:self];
8582 [table_ setDataSource:self];
8583 [[self view] addSubview:table_];
8585 NSArray *items = [NSArray arrayWithObjects:
8587 UCLocalize("HACKER"),
8588 UCLocalize("DEVELOPER"),
8590 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8591 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8592 [container_ addSubview:segment_];
8595 - (void) viewDidLoad {
8596 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8599 if ([Role_ isEqualToString:@"User"]) index = 0;
8600 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8601 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8603 [segment_ setSelectedSegmentIndex:index];
8604 [self showDoneButton];
8607 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8608 [self resizeSegmentedControl];
8611 - (void) releaseSubviews {
8618 [container_ release];
8622 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8623 if ((self = [super init]) != nil) {
8624 database_ = database;
8625 roledelegate_ = delegate;
8629 - (void) resizeSegmentedControl {
8630 CGFloat width = [[self view] frame].size.width;
8631 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8634 - (void) viewWillAppear:(BOOL)animated {
8635 [super viewWillAppear:animated];
8637 [self resizeSegmentedControl];
8640 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8641 [self resizeSegmentedControl];
8644 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8645 [self resizeSegmentedControl];
8649 NSString *role(nil);
8651 switch ([segment_ selectedSegmentIndex]) {
8652 case 0: role = @"User"; break;
8653 case 1: role = @"Hacker"; break;
8654 case 2: role = @"Developer"; break;
8659 if (![role isEqualToString:Role_]) {
8660 bool rolling(Role_ == nil);
8663 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8667 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8671 [roledelegate_ loadData];
8673 [roledelegate_ updateData];
8677 - (void) segmentChanged:(UISegmentedControl *)control {
8678 [self showDoneButton];
8681 - (void) saveAndClose {
8684 [[self navigationItem] setRightBarButtonItem:nil];
8685 [[self navigationController] dismissModalViewControllerAnimated:YES];
8688 - (void) doneButtonClicked {
8689 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8690 [spinner startAnimating];
8691 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8692 [[self navigationItem] setRightBarButtonItem:spinItem];
8694 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8697 - (void) showDoneButton {
8698 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8699 initWithTitle:UCLocalize("DONE")
8700 style:UIBarButtonItemStyleDone
8702 action:@selector(doneButtonClicked)
8703 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8706 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8707 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8711 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8715 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8716 return nil; // This method is required by the protocol.
8719 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8721 return UCLocalize("ROLE_EX");
8723 return [NSString stringWithFormat:
8724 @"%@: %@\n%@: %@\n%@: %@",
8725 UCLocalize("USER"), UCLocalize("USER_EX"),
8726 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8727 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8732 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8733 return section == 3 ? 44.0f : 0;
8736 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8737 return section == 3 ? container_ : nil;
8740 - (void) reloadData {
8742 [table_ reloadData];
8747 /* Stash Controller {{{ */
8748 @interface StashController : CYViewController {
8749 UIActivityIndicatorView *spinner_;
8756 @implementation StashController
8759 [self releaseSubviews];
8765 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8766 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8768 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8769 CGRect spinrect = [spinner_ frame];
8770 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8771 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8772 [spinner_ setFrame:spinrect];
8773 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8774 [[self view] addSubview:spinner_];
8775 [spinner_ startAnimating];
8778 captrect.size.width = [[self view] frame].size.width;
8779 captrect.size.height = 40.0f;
8780 captrect.origin.x = 0;
8781 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8782 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8783 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8784 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8785 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8786 [caption_ setTextColor:[UIColor whiteColor]];
8787 [caption_ setBackgroundColor:[UIColor clearColor]];
8788 [caption_ setShadowColor:[UIColor blackColor]];
8789 [caption_ setTextAlignment:UITextAlignmentCenter];
8790 [[self view] addSubview:caption_];
8793 statusrect.size.width = [[self view] frame].size.width;
8794 statusrect.size.height = 30.0f;
8795 statusrect.origin.x = 0;
8796 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8797 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8798 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8799 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8800 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8801 [status_ setTextColor:[UIColor whiteColor]];
8802 [status_ setBackgroundColor:[UIColor clearColor]];
8803 [status_ setShadowColor:[UIColor blackColor]];
8804 [status_ setTextAlignment:UITextAlignmentCenter];
8805 [[self view] addSubview:status_];
8808 - (void) releaseSubviews {
8822 @interface Cydia : UIApplication <
8823 ConfirmationControllerDelegate,
8826 UINavigationControllerDelegate,
8827 UITabBarControllerDelegate
8829 // XXX: evaluate all fields for _transient
8832 CYTabBarController *tabbar_;
8833 CYEmulatedLoadingController *emulated_;
8835 NSMutableArray *essential_;
8836 NSMutableArray *broken_;
8838 Database *database_;
8845 StashController *stash_;
8854 @implementation Cydia
8856 - (void) beginUpdate {
8857 [tabbar_ beginUpdate];
8861 return [tabbar_ updating];
8865 if ([broken_ count] != 0) {
8866 int count = [broken_ count];
8868 UIAlertView *alert = [[[UIAlertView alloc]
8869 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8870 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8872 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8874 UCLocalize("TEMPORARY_IGNORE"),
8878 [alert setContext:@"fixhalf"];
8879 [alert setNumberOfRows:2];
8881 } else if (!Ignored_ && [essential_ count] != 0) {
8882 int count = [essential_ count];
8884 UIAlertView *alert = [[[UIAlertView alloc]
8885 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8886 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8888 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8890 UCLocalize("UPGRADE_ESSENTIAL"),
8891 UCLocalize("COMPLETE_UPGRADE"),
8895 [alert setContext:@"upgrade"];
8900 - (void) _saveConfig {
8906 NSString *error(nil);
8908 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8910 NSError *error(nil);
8911 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8912 NSLog(@"failure to save metadata data: %@", error);
8917 NSLog(@"failure to serialize metadata: %@", error);
8922 // Navigation controller for the queuing badge.
8923 - (CYNavigationController *) queueNavigationController {
8924 NSArray *controllers = [tabbar_ viewControllers];
8925 return [controllers objectAtIndex:3];
8928 - (void) _updateData {
8931 [tabbar_ reloadData];
8933 CYNavigationController *navigation = [self queueNavigationController];
8935 id queuedelegate = nil;
8936 if ([[navigation viewControllers] count] > 0)
8937 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8939 [queuedelegate queueStatusDidChange];
8940 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8943 - (void) _refreshIfPossible:(NSDate *)update {
8944 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8946 bool recently = false;
8947 if (update != nil) {
8948 NSTimeInterval interval([update timeIntervalSinceNow]);
8949 if (interval <= 0 && interval > -(15*60))
8953 // Don't automatic refresh if:
8954 // - We already refreshed recently.
8955 // - We already auto-refreshed this launch.
8956 // - Auto-refresh is disabled.
8957 if (recently || loaded_ || ManualRefresh) {
8958 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8960 // If we are cancelling, we need to make sure it knows it's already loaded.
8964 // We are going to load, so remember that.
8968 SCNetworkReachabilityFlags flags; {
8969 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8970 SCNetworkReachabilityGetFlags(reachability, &flags);
8971 CFRelease(reachability);
8974 // XXX: this elaborate mess is what Apple is using to determine this? :(
8975 // XXX: do we care if the user has to intervene? maybe that's ok?
8977 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8978 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8979 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8980 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8981 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8982 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8986 // If we can reach the server, auto-refresh!
8988 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8993 - (void) refreshIfPossible {
8994 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8997 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8998 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8999 [hud setText:UCLocalize("RELOADING_DATA")];
9001 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9004 [self removeProgressHUD:hud];
9008 [essential_ removeAllObjects];
9009 [broken_ removeAllObjects];
9011 NSArray *packages([database_ packages]);
9012 for (Package *package in packages) {
9014 [broken_ addObject:package];
9015 if ([package upgradableAndEssential:NO]) {
9016 if ([package essential])
9017 [essential_ addObject:package];
9022 NSLog(@"changes:#%u", changes);
9024 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9027 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9028 [changesItem setBadgeValue:badge];
9029 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9030 [self setApplicationIconBadgeNumber:changes];
9033 [changesItem setBadgeValue:nil];
9034 [changesItem setAnimatedBadge:NO];
9035 [self setApplicationIconBadgeNumber:0];
9040 [self refreshIfPossible];
9043 - (void) updateData {
9052 @synchronized (self) {
9053 [self _reloadDataWithInvocation:nil];
9057 - (void) disemulate {
9058 if (emulated_ == nil)
9061 [window_ addSubview:[tabbar_ view]];
9062 [[emulated_ view] removeFromSuperview];
9063 [emulated_ release];
9065 [window_ setUserInteractionEnabled:YES];
9068 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9069 UINavigationController *navigation([[[CYNavigationController alloc] initWithRootViewController:controller] autorelease]);
9071 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9073 UIViewController *parent;
9074 if (emulated_ == nil)
9083 [parent presentModalViewController:navigation animated:YES];
9086 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9087 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9089 if (navigation != nil)
9090 [navigation pushViewController:progress animated:YES];
9092 [self presentModalViewController:progress force:YES];
9094 [progress invoke:invocation withTitle:title];
9098 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9099 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9102 - (void) repairWithInvocation:(NSInvocation *)invocation {
9104 [self invokeNewProgress:invocation forController:nil withTitle:UCLocalize("REPAIRING")];
9108 - (void) repairWithSelector:(SEL)selector {
9109 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9115 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9116 _assert(file != NULL);
9118 for (NSString *key in [Sources_ allKeys]) {
9119 NSDictionary *source([Sources_ objectForKey:key]);
9121 fprintf(file, "%s %s %s\n",
9122 [[source objectForKey:@"Type"] UTF8String],
9123 [[source objectForKey:@"URI"] UTF8String],
9124 [[source objectForKey:@"Distribution"] UTF8String]
9130 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:UCLocalize("UPDATING_SOURCES")];
9135 - (void) addTrivialSource:(NSString *)href {
9136 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9139 @"./", @"Distribution",
9140 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9145 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9146 @synchronized (self) {
9147 [self _reloadDataWithInvocation:invocation];
9151 - (void) reloadData {
9152 [self reloadDataWithInvocation:nil];
9156 pkgProblemResolver *resolver = [database_ resolver];
9158 resolver->InstallProtect();
9159 if (!resolver->Resolve(true))
9164 // XXX: this is a really crappy way of doing this.
9165 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9166 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9167 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9168 if ([tabbar_ updating])
9169 [tabbar_ cancelUpdate];
9171 if (![database_ prepare])
9174 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9175 [page setDelegate:self];
9176 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
9177 [confirm_ setDelegate:self];
9180 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9181 [tabbar_ presentModalViewController:confirm_ animated:YES];
9187 @synchronized (self) {
9192 - (void) clearPackage:(Package *)package {
9193 @synchronized (self) {
9200 - (void) installPackages:(NSArray *)packages {
9201 @synchronized (self) {
9202 for (Package *package in packages)
9209 - (void) installPackage:(Package *)package {
9210 @synchronized (self) {
9217 - (void) removePackage:(Package *)package {
9218 @synchronized (self) {
9225 - (void) distUpgrade {
9226 @synchronized (self) {
9227 if (![database_ upgrade])
9233 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9236 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:UCLocalize("RUNNING")];
9241 - (void) showSettings {
9242 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9243 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9245 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9246 [tabbar_ presentModalViewController:nav animated:YES];
9249 - (void) retainNetworkActivityIndicator {
9250 if (activity_++ == 0)
9251 [self setNetworkActivityIndicatorVisible:YES];
9254 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9258 - (void) releaseNetworkActivityIndicator {
9259 if (--activity_ == 0)
9260 [self setNetworkActivityIndicatorVisible:NO];
9263 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9268 - (void) cancelAndClear:(bool)clear {
9269 @synchronized (self) {
9281 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9282 NSString *context([alert context]);
9284 if ([context isEqualToString:@"conffile"]) {
9285 FILE *input = [database_ input];
9286 if (button == [alert cancelButtonIndex])
9287 fprintf(input, "N\n");
9288 else if (button == [alert firstOtherButtonIndex])
9289 fprintf(input, "Y\n");
9292 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9293 } else if ([context isEqualToString:@"fixhalf"]) {
9294 if (button == [alert cancelButtonIndex]) {
9295 @synchronized (self) {
9296 for (Package *broken in broken_) {
9299 NSString *id = [broken id];
9300 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9301 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9302 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9303 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9309 } else if (button == [alert firstOtherButtonIndex]) {
9310 [broken_ removeAllObjects];
9314 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9315 } else if ([context isEqualToString:@"upgrade"]) {
9316 if (button == [alert firstOtherButtonIndex]) {
9317 @synchronized (self) {
9318 for (Package *essential in essential_)
9319 [essential install];
9324 } else if (button == [alert firstOtherButtonIndex] + 1) {
9326 } else if (button == [alert cancelButtonIndex]) {
9330 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9334 - (void) system:(NSString *)command { _pooled
9336 system([command UTF8String]);
9340 - (void) applicationWillSuspend {
9342 [super applicationWillSuspend];
9345 - (BOOL) isSafeToSuspend {
9346 // Use external process status API internally.
9347 // This is probably a really bad idea.
9348 // XXX: what is the point of this? does this solve anything at all?
9349 uint64_t status = 0;
9351 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9352 notify_get_state(notify_token, &status);
9353 notify_cancel(notify_token);
9356 return locked_ == 0 && status == 0;
9359 - (void) applicationSuspend:(__GSEvent *)event {
9360 if ([self isSafeToSuspend])
9361 [super applicationSuspend:event];
9364 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9365 if ([self isSafeToSuspend])
9366 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9369 - (void) _setSuspended:(BOOL)value {
9370 if ([self isSafeToSuspend])
9371 [super _setSuspended:value];
9374 - (UIProgressHUD *) addProgressHUD {
9375 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9376 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9378 [window_ setUserInteractionEnabled:NO];
9381 UIViewController *target = tabbar_;
9382 while ([target modalViewController] != nil) target = [target modalViewController];
9383 [[target view] addSubview:hud];
9389 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9391 [hud removeFromSuperview];
9392 [window_ setUserInteractionEnabled:YES];
9396 - (CYViewController *) pageForPackage:(NSString *)name {
9397 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9400 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9401 NSString *scheme([[url scheme] lowercaseString]);
9402 if ([[url absoluteString] length] <= [scheme length] + 3)
9404 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9405 NSArray *components([path pathComponents]);
9407 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9408 return [self pageForPackage:[components objectAtIndex:1]];
9410 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9413 NSString *base([components objectAtIndex:0]);
9415 CYViewController *controller = nil;
9417 if ([base isEqualToString:@"url"]) {
9418 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9419 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9420 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9421 } else if (!external && [components count] == 1) {
9422 if ([base isEqualToString:@"manage"]) {
9423 controller = [[[ManageController alloc] init] autorelease];
9426 if ([base isEqualToString:@"sources"]) {
9427 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9430 if ([base isEqualToString:@"home"]) {
9431 controller = [[[HomeController alloc] init] autorelease];
9434 if ([base isEqualToString:@"sections"]) {
9435 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9438 if ([base isEqualToString:@"search"]) {
9439 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9442 if ([base isEqualToString:@"changes"]) {
9443 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9446 if ([base isEqualToString:@"installed"]) {
9447 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9449 } else if ([components count] == 2) {
9450 NSString *argument = [components objectAtIndex:1];
9452 if ([base isEqualToString:@"package"]) {
9453 controller = [self pageForPackage:argument];
9456 if (!external && [base isEqualToString:@"search"]) {
9457 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9458 [(SearchController *)controller setSearchTerm:argument];
9461 if (!external && [base isEqualToString:@"sections"]) {
9462 if ([argument isEqualToString:@"all"])
9464 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9467 if (!external && [base isEqualToString:@"sources"]) {
9468 if ([argument isEqualToString:@"add"]) {
9469 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9470 [(SourcesController *)controller showAddSourcePrompt];
9472 Source *source = [database_ sourceWithKey:argument];
9473 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9477 if (!external && [base isEqualToString:@"launch"]) {
9478 [self launchApplicationWithIdentifier:argument suspended:NO];
9481 } else if (!external && [components count] == 3) {
9482 NSString *arg1 = [components objectAtIndex:1];
9483 NSString *arg2 = [components objectAtIndex:2];
9485 if ([base isEqualToString:@"package"]) {
9486 if ([arg2 isEqualToString:@"settings"]) {
9487 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9488 } else if ([arg2 isEqualToString:@"files"]) {
9489 if (Package *package = [database_ packageWithName:arg1]) {
9490 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9491 [(FileTable *)controller setPackage:package];
9497 [controller setDelegate:self];
9501 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9502 CYViewController *page([self pageForURL:url forExternal:external]);
9505 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9506 [nav setViewControllers:[NSArray arrayWithObject:page]];
9507 [tabbar_ setUnselectedViewController:nav];
9513 - (void) applicationOpenURL:(NSURL *)url {
9514 [super applicationOpenURL:url];
9516 if (!loaded_) starturl_ = [url retain];
9517 else [self openCydiaURL:url forExternal:YES];
9520 - (void) applicationWillResignActive:(UIApplication *)application {
9521 // Stop refreshing if you get a phone call or lock the device.
9522 if ([tabbar_ updating])
9523 [tabbar_ cancelUpdate];
9525 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9526 [super applicationWillResignActive:application];
9529 - (void) applicationWillTerminate:(UIApplication *)application {
9531 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9532 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9533 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9538 - (void) setConfigurationData:(NSString *)data {
9539 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9541 if (!conffile_r(data)) {
9542 lprintf("E:invalid conffile\n");
9546 NSString *ofile = conffile_r[1];
9547 //NSString *nfile = conffile_r[2];
9549 UIAlertView *alert = [[[UIAlertView alloc]
9550 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9551 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9553 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9555 UCLocalize("ACCEPT_NEW_COPY"),
9556 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9560 [alert setContext:@"conffile"];
9561 [alert setNumberOfRows:2];
9565 - (void) addStashController {
9567 stash_ = [[StashController alloc] init];
9568 [window_ addSubview:[stash_ view]];
9571 - (void) removeStashController {
9572 [[stash_ view] removeFromSuperview];
9578 [self setIdleTimerDisabled:YES];
9580 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9581 UpdateExternalStatus(1);
9582 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9583 UpdateExternalStatus(0);
9585 [self removeStashController];
9587 if (ExecFork() == 0) {
9588 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9589 perror("launchctl stop");
9593 - (void) setupViewControllers {
9594 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9596 NSMutableArray *items([NSMutableArray arrayWithObjects:
9597 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9598 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9599 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9600 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9604 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9605 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9607 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9610 NSMutableArray *controllers([NSMutableArray array]);
9611 for (UITabBarItem *item in items) {
9612 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9613 [controller setTabBarItem:item];
9614 [controllers addObject:controller];
9616 [tabbar_ setViewControllers:controllers];
9618 [tabbar_ setUpdateDelegate:self];
9621 - (void) applicationDidFinishLaunching:(id)unused {
9623 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9624 [self setApplicationSupportsShakeToEdit:NO];
9626 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9627 initWithMemoryCapacity:524288
9628 diskCapacity:10485760
9629 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9632 [CYBrowserController _initialize];
9634 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9636 Font12_ = [[UIFont systemFontOfSize:12] retain];
9637 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9638 Font14_ = [[UIFont systemFontOfSize:14] retain];
9639 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9640 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9642 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9643 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9645 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9646 [window_ orderFront:self];
9647 [window_ makeKey:self];
9648 [window_ setHidden:NO];
9651 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9652 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9653 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9654 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9655 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9656 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9657 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9658 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9659 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9662 [self addStashController];
9663 // XXX: this would be much cleaner as a yieldToSelector:
9664 // that way the removeStashController could happen right here inline
9665 // we also could no longer require the useless stash_ field anymore
9666 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9670 database_ = [Database sharedInstance];
9671 [database_ setDelegate:self];
9673 [window_ setUserInteractionEnabled:NO];
9674 [self setupViewControllers];
9676 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9677 [window_ addSubview:[emulated_ view]];
9679 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9686 [window_ setUserInteractionEnabled:YES];
9687 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9690 if ([emulated_ modalViewController] != nil)
9691 [emulated_ dismissModalViewControllerAnimated:YES];
9692 [window_ setUserInteractionEnabled:NO];
9700 int selectedIndex = 0;
9701 NSMutableArray *items = nil;
9703 bool recently = false;
9704 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9705 if (closed != nil) {
9706 NSTimeInterval interval([closed timeIntervalSinceNow]);
9707 // XXX: Is 15 minutes the optimal time here?
9708 if (interval <= 0 && interval > -(15*60))
9712 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9713 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9716 for (NSArray *entry in items)
9717 if ([entry count] <= 0)
9720 if (!recently || !items || !enough) {
9722 items = [NSMutableArray array];
9723 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9724 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9725 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9727 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9729 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9730 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9732 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9735 [tabbar_ setSelectedIndex:selectedIndex];
9736 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9737 NSArray *stack = [items objectAtIndex:tab];
9738 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9739 NSMutableArray *current = [NSMutableArray array];
9741 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9742 NSString *addr = [stack objectAtIndex:nav];
9743 NSURL *url = [NSURL URLWithString:addr];
9744 CYViewController *page = [self pageForURL:url forExternal:NO];
9746 [current addObject:page];
9749 [navigation setViewControllers:current];
9752 // (Try to) show the startup URL.
9753 if (starturl_ != nil) {
9754 [self openCydiaURL:starturl_ forExternal:NO];
9755 [starturl_ release];
9760 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9761 if (item != nil && IsWildcat_) {
9762 [sheet showFromBarButtonItem:item animated:YES];
9764 [sheet showInView:window_];
9768 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9769 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9770 [progress setTitle:task];
9771 [progress addProgressEvent:event];
9774 - (void) addProgressEventForTask:(NSArray *)data {
9775 CydiaProgressEvent *event([data objectAtIndex:0]);
9776 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9777 [self addProgressEvent:event forTask:task];
9780 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9781 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9787 id Alloc_(id self, SEL selector) {
9788 id object = alloc_(self, selector);
9789 lprintf("[%s]A-%p\n", self->isa->name, object);
9794 id Dealloc_(id self, SEL selector) {
9795 id object = dealloc_(self, selector);
9796 lprintf("[%s]D-%p\n", self->isa->name, object);
9800 Class $WebDefaultUIKitDelegate;
9802 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9803 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9804 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9805 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9808 static NSNumber *shouldPlayKeyboardSounds;
9812 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9814 case 1104: // Keyboard Button Clicked
9815 case 1105: // Keyboard Delete Repeated
9816 if (shouldPlayKeyboardSounds == nil) {
9817 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9818 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9821 if (![shouldPlayKeyboardSounds boolValue])
9825 _UIHardware$_playSystemSound$(self, _cmd, sound);
9829 Class $UIApplication;
9831 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9832 static BOOL initialized = NO;
9833 static BOOL started = NO;
9835 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9836 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9838 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9839 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9840 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9841 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9843 if (initialized && !enabled) {
9845 [bundle performSelector:@selector(_accessibilityStopServer)];
9846 } else if (enabled) {
9850 [bundle performSelector:@selector(_accessibilityStartServer)];
9856 int main(int argc, char *argv[]) { _pooled
9859 UpdateExternalStatus(0);
9861 if (Class $UIDevice = objc_getClass("UIDevice")) {
9862 UIDevice *device([$UIDevice currentDevice]);
9863 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9867 UIScreen *screen([UIScreen mainScreen]);
9868 if ([screen respondsToSelector:@selector(scale)])
9869 ScreenScale_ = [screen scale];
9873 UIDevice *device([UIDevice currentDevice]);
9874 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9877 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9878 if (idiom == UIUserInterfaceIdiomPhone)
9880 else if (idiom == UIUserInterfaceIdiomPad)
9883 NSLog(@"unknown UIUserInterfaceIdiom!");
9886 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9888 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9890 /* Library Hacks {{{ */
9891 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9893 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9894 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9895 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9896 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9897 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9900 $UIHardware = objc_getClass("UIHardware");
9901 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9902 if (UIHardware$_playSystemSound$ != NULL) {
9903 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9904 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9907 $UIApplication = objc_getClass("UIApplication");
9908 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9909 if (UIApplication$_updateApplicationAccessibility != NULL) {
9910 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9911 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9914 /* Set Locale {{{ */
9915 Locale_ = CFLocaleCopyCurrent();
9916 Languages_ = [NSLocale preferredLanguages];
9917 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9918 //NSLog(@"%@", [Languages_ description]);
9921 if (Languages_ == nil || [Languages_ count] == 0)
9922 // XXX: consider just setting to C and then falling through?
9925 lang = [[Languages_ objectAtIndex:0] UTF8String];
9926 setenv("LANG", lang, true);
9927 std::setlocale(LC_ALL, lang);
9930 NSLog(@"Setting Language: %s", lang);
9933 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9935 /* Parse Arguments {{{ */
9936 bool substrate(false);
9942 for (int argi(1); argi != argc; ++argi)
9943 if (strcmp(argv[argi], "--") == 0) {
9945 argv[argi] = argv[0];
9951 for (int argi(1); argi != arge; ++argi)
9952 if (strcmp(args[argi], "--substrate") == 0)
9955 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9959 App_ = [[NSBundle mainBundle] bundlePath];
9965 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9966 alloc_ = alloc->method_imp;
9967 alloc->method_imp = (IMP) &Alloc_;*/
9969 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9970 dealloc_ = dealloc->method_imp;
9971 dealloc->method_imp = (IMP) &Dealloc_;*/
9973 /* System Information {{{ */
9977 size = sizeof(maxproc);
9978 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9979 perror("sysctlbyname(\"kern.maxproc\", ?)");
9980 else if (maxproc < 64) {
9982 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9983 perror("sysctlbyname(\"kern.maxproc\", #)");
9986 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9987 char *osversion = new char[size];
9988 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9989 perror("sysctlbyname(\"kern.osversion\", ?)");
9991 System_ = [NSString stringWithUTF8String:osversion];
9993 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9994 char *machine = new char[size];
9995 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9996 perror("sysctlbyname(\"hw.machine\", ?)");
10000 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
10001 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
10002 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
10003 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
10007 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
10008 NSData *data((NSData *) ecid);
10009 size_t length([data length]);
10010 uint8_t bytes[length];
10011 [data getBytes:bytes];
10012 char string[length * 2 + 1];
10013 for (size_t i(0); i != length; ++i)
10014 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10015 ChipID_ = [NSString stringWithUTF8String:string];
10019 IOObjectRelease(service);
10023 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10025 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10026 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10027 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10029 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10030 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10031 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10033 if (mcc != NULL && mnc != NULL)
10034 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10041 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10042 Build_ = [system objectForKey:@"ProductBuildVersion"];
10043 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10044 Product_ = [info objectForKey:@"SafariProductVersion"];
10045 Safari_ = [info objectForKey:@"CFBundleVersion"];
10048 /* Load Database {{{ */
10050 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10052 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10054 if (Metadata_ == NULL)
10055 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10057 Settings_ = [Metadata_ objectForKey:@"Settings"];
10059 Packages_ = [Metadata_ objectForKey:@"Packages"];
10060 Sections_ = [Metadata_ objectForKey:@"Sections"];
10061 Sources_ = [Metadata_ objectForKey:@"Sources"];
10063 Token_ = [Metadata_ objectForKey:@"Token"];
10066 if (Settings_ != nil)
10067 Role_ = [Settings_ objectForKey:@"Role"];
10069 if (Sections_ == nil) {
10070 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10071 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10074 if (Sources_ == nil) {
10075 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10076 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10081 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10084 if (Packages_ != nil) {
10086 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10090 [Metadata_ removeObjectForKey:@"Packages"];
10096 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10098 #define MobileSubstrate_(name) \
10099 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10100 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10101 if (handle == NULL) \
10102 NSLog(@"%s", dlerror()); \
10105 MobileSubstrate_(Activator)
10106 MobileSubstrate_(libstatusbar)
10107 MobileSubstrate_(SimulatedKeyEvents)
10108 MobileSubstrate_(WinterBoard)
10110 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10111 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10113 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10115 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10116 unlink("/tmp/.cydia.fw");
10118 } else if (access("/User", F_OK) != 0 || version < 2) {
10121 system("/usr/libexec/cydia/firmware.sh");
10125 _assert([[NSFileManager defaultManager]
10126 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10127 withIntermediateDirectories:YES
10132 if (access("/tmp/cydia.chk", F_OK) == 0) {
10133 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10134 _assert(errno == ENOENT);
10135 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10136 _assert(errno == ENOENT);
10139 /* APT Initialization {{{ */
10140 _assert(pkgInitConfig(*_config));
10141 _assert(pkgInitSystem(*_config, _system));
10144 _config->Set("APT::Acquire::Translation", lang);
10146 // XXX: this timeout might be important :(
10147 //_config->Set("Acquire::http::Timeout", 15);
10149 _config->Set("Acquire::http::MaxParallel", 3);
10151 /* Color Choices {{{ */
10152 space_ = CGColorSpaceCreateDeviceRGB();
10154 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10155 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10156 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10157 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10158 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10159 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10160 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10161 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10162 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10164 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10165 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10167 /* UIKit Configuration {{{ */
10168 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10169 if ($GSFontSetUseLegacyFontMetrics != NULL)
10170 $GSFontSetUseLegacyFontMetrics(YES);
10172 // XXX: I have a feeling this was important
10173 //UIKeyboardDisableAutomaticAppearance();
10176 Colon_ = UCLocalize("COLON_DELIMITED");
10177 Elision_ = UCLocalize("ELISION");
10178 Error_ = UCLocalize("ERROR");
10179 Warning_ = UCLocalize("WARNING");
10182 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10184 CGColorSpaceRelease(space_);
10185 CFRelease(Locale_);