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>
121 #include <Cytore.hpp>
123 #include "UICaboodle/BrowserView.h"
124 #include "UICaboodle/NSString-UICaboodle.h"
125 #include "UICaboodle/PerlCompatibleRegEx.hpp"
127 #include "SDURLCache/SDURLCache.h"
129 #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 #define Cydia_ CYDIA_VERSION
213 #define lprintf(args...) fprintf(stderr, args)
216 #define TraceLogging (1 && !ForRelease)
217 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
218 #define ProfileTimes (0 && !ForRelease)
219 #define ForSaurik (0 && !ForRelease)
220 #define LogBrowser (0 && !ForRelease)
221 #define TrackResize (0 && !ForRelease)
222 #define ManualRefresh (1 && !ForRelease)
223 #define ShowInternals (0 && !ForRelease)
224 #define AlwaysReload (0 && !ForRelease)
225 #define TryIndexedCollation (0 && !ForRelease)
229 #define _trace(args...)
234 #define _profile(name) {
237 #define PrintTimes() do {} while (false)
240 // Hash Functions/Structures {{{
241 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
249 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
251 static _finline NSString *CydiaURL(NSString *path) {
253 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
254 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
255 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
256 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
257 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
259 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
262 static _finline void UpdateExternalStatus(uint64_t newStatus) {
264 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
265 notify_set_state(notify_token, newStatus);
266 notify_cancel(notify_token);
268 notify_post("com.saurik.Cydia.status");
271 /* [NSObject yieldToSelector:(withObject:)] {{{*/
272 @interface NSObject (Cydia)
273 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
274 - (id) yieldToSelector:(SEL)selector;
277 @implementation NSObject (Cydia)
282 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
283 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
284 id object([[context objectAtIndex:1] nonretainedObjectValue]);
285 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
287 /* XXX: deal with exceptions */
288 id value([self performSelector:selector withObject:object]);
290 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
291 [context removeAllObjects];
292 if ([signature methodReturnLength] != 0 && value != nil)
293 [context addObject:value];
298 performSelectorOnMainThread:@selector(doNothing)
304 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
305 volatile bool stopped(false);
307 NSMutableArray *context([NSMutableArray arrayWithObjects:
308 [NSValue valueWithPointer:selector],
309 [NSValue valueWithNonretainedObject:object],
310 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
313 NSThread *thread([[[NSThread alloc]
315 selector:@selector(_yieldToContext:)
321 NSRunLoop *loop([NSRunLoop currentRunLoop]);
322 NSDate *future([NSDate distantFuture]);
323 NSString *mode([loop currentMode] ?: NSDefaultRunLoopMode);
326 while (!stopped && [loop runMode:mode beforeDate:future]);
329 return [context count] == 0 ? nil : [context objectAtIndex:0];
332 - (id) yieldToSelector:(SEL)selector {
333 return [self yieldToSelector:selector withObject:nil];
339 /* Cydia Alert View {{{ */
340 @interface CYAlertView : UIAlertView {
344 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
348 @implementation CYAlertView
350 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
351 if ((self = [super init]) != nil) {
352 [self setTitle:title];
353 [self setDelegate:self];
354 for (NSString *button in buttons) [self addButtonWithTitle:button];
355 [self setCancelButtonIndex:index];
359 - (void) _updateFrameForDisplay {
360 [super _updateFrameForDisplay];
361 if ([self cancelButtonIndex] == -1) {
362 NSArray *buttons = [self buttons];
363 if ([buttons count]) {
364 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
365 for (UIThreePartButton *button in buttons)
366 [button setBackground:background forState:0];
371 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
372 button_ = buttonIndex + 1;
376 [self dismissWithClickedButtonIndex:-1 animated:YES];
379 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
380 [self setRunsModal:YES];
389 /* NSForcedOrderingSearch doesn't work on the iPhone */
390 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
391 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
392 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
395 typedef uint32_t (*SKRadixFunction)(id, void *);
397 @interface NSMutableArray (Radix)
398 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
406 @implementation NSMutableArray (Radix)
408 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
409 size_t count([self count]);
410 struct RadixItem_ *swap(new RadixItem_[count * 2]);
412 for (size_t i(0); i != count; ++i) {
413 RadixItem_ &item(swap[i]);
416 id object([self objectAtIndex:i]);
417 item.key = function(object, argument);
420 struct RadixItem_ *lhs(swap), *rhs(swap + count);
422 static const size_t width = 32;
423 static const size_t bits = 11;
424 static const size_t slots = 1 << bits;
425 static const size_t passes = (width + (bits - 1)) / bits;
427 size_t *hist(new size_t[slots]);
429 for (size_t pass(0); pass != passes; ++pass) {
430 memset(hist, 0, sizeof(size_t) * slots);
432 for (size_t i(0); i != count; ++i) {
433 uint32_t key(lhs[i].key);
435 key &= _not(uint32_t) >> width - bits;
440 for (size_t i(0); i != slots; ++i) {
441 size_t local(offset);
446 for (size_t i(0); i != count; ++i) {
447 uint32_t key(lhs[i].key);
449 key &= _not(uint32_t) >> width - bits;
450 rhs[hist[key]++] = lhs[i];
453 RadixItem_ *tmp(lhs);
460 const void **values(new const void *[count]);
461 for (size_t i(0); i != count; ++i)
462 values[i] = [self objectAtIndex:lhs[i].index];
463 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
471 /* Insertion Sort {{{ */
473 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
474 const char *ptr = (const char *)list;
476 CFIndex half = count / 2;
477 const char *probe = ptr + elementSize * half;
478 CFComparisonResult cr = comparator(element, probe, context);
479 if (0 == cr) return (probe - (const char *)list) / elementSize;
480 ptr = (cr < 0) ? ptr : probe + elementSize;
481 count = (cr < 0) ? half : (half + (count & 1) - 1);
483 return (ptr - (const char *)list) / elementSize;
486 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
487 const char *ptr = (const char *)list;
489 CFIndex half = count / 2;
490 const char *probe = ptr + elementSize * half;
491 CFComparisonResult cr = comparator(element, probe, context);
492 if (0 == cr) return (probe - (const char *)list) / elementSize;
493 ptr = (cr < 0) ? ptr : probe + elementSize;
494 count = (cr < 0) ? half : (half + (count & 1) - 1);
496 return (ptr - (const char *)list) / elementSize;
499 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
500 if (range.length == 0)
502 const void **values(new const void *[range.length]);
503 CFArrayGetValues(array, range, values);
505 #if HistogramInsertionSort > 0
506 uint32_t total(0), *offsets(new uint32_t[range.length]);
509 for (CFIndex index(1); index != range.length; ++index) {
510 const void *value(values[index]);
511 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
512 CFIndex correct(index);
513 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
514 #if HistogramInsertionSort > 1
515 NSLog(@"%@ < %@", value, values[correct - 1]);
520 if (correct != index) {
521 size_t offset(index - correct);
522 #if HistogramInsertionSort
526 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
528 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
529 values[correct] = value;
533 CFArrayReplaceValues(array, range, values, range.length);
536 #if HistogramInsertionSort > 0
537 for (CFIndex index(0); index != range.length; ++index)
538 if (offsets[index] != 0)
539 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
540 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
547 /* Apple Bug Fixes {{{ */
548 @implementation UIWebDocumentView (Cydia)
550 - (void) _setScrollerOffset:(CGPoint)offset {
551 UIScroller *scroller([self _scroller]);
553 CGSize size([scroller contentSize]);
554 CGSize bounds([scroller bounds].size);
557 max.x = size.width - bounds.width;
558 max.y = size.height - bounds.height;
566 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
567 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
569 [scroller setOffset:offset];
575 @interface NSInvocation (Cydia)
576 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target;
579 @implementation NSInvocation (Cydia)
581 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target {
582 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]]);
583 [invocation setTarget:target];
584 [invocation setSelector:selector];
590 @implementation WebScriptObject (NSFastEnumeration)
592 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
593 size_t length([self count] - state->state);
596 else if (length > count)
598 for (size_t i(0); i != length; ++i)
599 objects[i] = [self objectAtIndex:state->state++];
600 state->itemsPtr = objects;
601 state->mutationsPtr = (unsigned long *) self;
607 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
608 size_t length([self length] - state->state);
611 else if (length > count)
613 for (size_t i(0); i != length; ++i)
614 objects[i] = [self item:state->state++];
615 state->itemsPtr = objects;
616 state->mutationsPtr = (unsigned long *) self;
620 /* Cydia NSString Additions {{{ */
621 @interface NSString (Cydia)
622 - (NSComparisonResult) compareByPath:(NSString *)other;
623 - (NSString *) stringByCachingURLWithCurrentCDN;
624 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
627 @implementation NSString (UICaboodle)
629 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
630 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
633 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
634 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
639 @implementation NSString (Cydia)
641 - (NSComparisonResult) compareByPath:(NSString *)other {
642 NSString *prefix = [self commonPrefixWithString:other options:0];
643 size_t length = [prefix length];
645 NSRange lrange = NSMakeRange(length, [self length] - length);
646 NSRange rrange = NSMakeRange(length, [other length] - length);
648 lrange = [self rangeOfString:@"/" options:0 range:lrange];
649 rrange = [other rangeOfString:@"/" options:0 range:rrange];
651 NSComparisonResult value;
653 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
654 value = NSOrderedSame;
655 else if (lrange.location == NSNotFound)
656 value = NSOrderedAscending;
657 else if (rrange.location == NSNotFound)
658 value = NSOrderedDescending;
660 value = NSOrderedSame;
662 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
663 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
664 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
665 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
667 NSComparisonResult result = [lpath compare:rpath];
668 return result == NSOrderedSame ? value : result;
671 - (NSString *) stringByCachingURLWithCurrentCDN {
673 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
674 withString:@"://cache.cydia.saurik.com/"
678 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
679 return [(id)CFURLCreateStringByAddingPercentEscapes(
684 kCFStringEncodingUTF8
691 /* C++ NSString Wrapper Cache {{{ */
692 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
693 return size == 0 ? NULL :
694 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
695 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
698 static _finline CFStringRef CYStringCreate(const char *data) {
699 return CYStringCreate(data, strlen(data));
708 _finline void clear_() {
709 if (cache_ != NULL) {
716 _finline bool empty() const {
720 _finline size_t size() const {
724 _finline char *data() const {
728 _finline void clear() {
733 _finline CYString() :
740 _finline ~CYString() {
744 void operator =(const CYString &rhs) {
748 if (rhs.cache_ == nil)
751 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
754 void copy(apr_pool_t *pool) {
755 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
756 memcpy(temp, data_, size_);
761 void set(apr_pool_t *pool, const char *data, size_t size) {
767 data_ = const_cast<char *>(data);
775 _finline void set(apr_pool_t *pool, const char *data) {
776 set(pool, data, data == NULL ? 0 : strlen(data));
779 _finline void set(apr_pool_t *pool, const std::string &rhs) {
780 set(pool, rhs.data(), rhs.size());
783 bool operator ==(const CYString &rhs) const {
784 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
787 _finline operator CFStringRef() {
789 cache_ = CYStringCreate(data_, size_);
793 _finline operator id() {
794 return (NSString *) static_cast<CFStringRef>(*this);
797 _finline operator const char *() {
798 return reinterpret_cast<const char *>(data_);
802 /* C++ NSString Algorithm Adapters {{{ */
804 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
807 struct NSStringMapHash :
808 std::unary_function<NSString *, size_t>
810 _finline size_t operator ()(NSString *value) const {
811 return CFStringHashNSString((CFStringRef) value);
815 struct NSStringMapLess :
816 std::binary_function<NSString *, NSString *, bool>
818 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
819 return [lhs compare:rhs] == NSOrderedAscending;
823 struct NSStringMapEqual :
824 std::binary_function<NSString *, NSString *, bool>
826 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
827 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
828 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
829 //[lhs isEqualToString:rhs];
834 /* Mime Addresses {{{ */
835 @interface Address : NSObject {
841 - (NSString *) address;
843 - (void) setAddress:(NSString *)address;
845 + (Address *) addressWithString:(NSString *)string;
846 - (Address *) initWithString:(NSString *)string;
850 @implementation Address
859 - (NSString *) name {
863 - (NSString *) address {
867 - (void) setAddress:(NSString *)address {
869 [address_ autorelease];
873 address_ = [address retain];
876 + (Address *) addressWithString:(NSString *)string {
877 return [[[Address alloc] initWithString:string] autorelease];
880 + (NSArray *) _attributeKeys {
881 return [NSArray arrayWithObjects:
887 - (NSArray *) attributeKeys {
888 return [[self class] _attributeKeys];
891 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
892 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
895 - (Address *) initWithString:(NSString *)string {
896 if ((self = [super init]) != nil) {
897 const char *data = [string UTF8String];
898 size_t size = [string length];
900 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
902 if (address_r(data, size)) {
903 name_ = [address_r[1] retain];
904 address_ = [address_r[2] retain];
906 name_ = [string retain];
914 /* CoreGraphics Primitives {{{ */
919 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
920 CGFloat color[] = {red, green, blue, alpha};
921 return CGColorCreate(space, color);
930 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
931 color_(Create_(space, red, green, blue, alpha))
933 Set(space, red, green, blue, alpha);
938 CGColorRelease(color_);
945 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
947 color_ = Create_(space, red, green, blue, alpha);
950 operator CGColorRef() {
956 /* Random Global Variables {{{ */
957 static const int PulseInterval_ = 50000;
959 static const NSString *UI_;
962 static bool RestartSubstrate_;
963 static NSArray *Finishes_;
965 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
966 #define NotifyConfig_ "/etc/notify.conf"
968 static bool Queuing_;
970 static CYColor Blue_;
971 static CYColor Blueish_;
972 static CYColor Black_;
974 static CYColor White_;
975 static CYColor Gray_;
976 static CYColor Green_;
977 static CYColor Purple_;
978 static CYColor Purplish_;
980 static UIColor *InstallingColor_;
981 static UIColor *RemovingColor_;
983 static NSString *App_;
985 static BOOL Advanced_;
986 static BOOL Ignored_;
988 static UIFont *Font12_;
989 static UIFont *Font12Bold_;
990 static UIFont *Font14_;
991 static UIFont *Font18Bold_;
992 static UIFont *Font22Bold_;
994 static const char *Machine_ = NULL;
995 static NSString *System_ = nil;
996 static NSString *SerialNumber_ = nil;
997 static NSString *ChipID_ = nil;
998 static _H<NSString> Token_;
999 static NSString *UniqueID_ = nil;
1000 static NSString *PLMN_ = nil;
1001 static NSString *Build_ = nil;
1002 static NSString *Product_ = nil;
1003 static NSString *Safari_ = nil;
1005 static CFLocaleRef Locale_;
1006 static NSArray *Languages_;
1007 static CGColorSpaceRef space_;
1009 static NSDictionary *SectionMap_;
1010 static NSMutableDictionary *Metadata_;
1011 static _transient NSMutableDictionary *Settings_;
1012 static _transient NSString *Role_;
1013 static _transient NSMutableDictionary *Packages_;
1014 static _transient NSMutableDictionary *Sections_;
1015 static _transient NSMutableDictionary *Sources_;
1016 static bool Changed_;
1020 static CGFloat ScreenScale_;
1021 static NSString *Idiom_;
1023 static NSMutableDictionary *SessionData_;
1024 static NSObject *HostConfig_;
1025 static NSMutableSet *BridgedHosts_;
1026 static NSMutableSet *PipelinedHosts_;
1028 static NSString *kCydiaProgressEventTypeError = @"Error";
1029 static NSString *kCydiaProgressEventTypeInformation = @"Information";
1030 static NSString *kCydiaProgressEventTypeStatus = @"Status";
1031 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
1034 /* Display Helpers {{{ */
1035 inline float Interpolate(float begin, float end, float fraction) {
1036 return (end - begin) * fraction + begin;
1039 static _finline const char *StripVersion_(const char *version) {
1040 const char *colon(strchr(version, ':'));
1041 return colon == NULL ? version : colon + 1;
1044 NSString *LocalizeSection(NSString *section) {
1045 static Pcre title_r("^(.*?) \\((.*)\\)$");
1046 if (title_r(section)) {
1047 NSString *parent(title_r[1]);
1048 NSString *child(title_r[2]);
1050 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1051 LocalizeSection(parent),
1052 LocalizeSection(child)
1056 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1059 NSString *Simplify(NSString *title) {
1060 const char *data = [title UTF8String];
1061 size_t size = [title length];
1063 static Pcre square_r("^\\[(.*)\\]$");
1064 if (square_r(data, size))
1065 return Simplify(square_r[1]);
1067 static Pcre paren_r("^\\((.*)\\)$");
1068 if (paren_r(data, size))
1069 return Simplify(paren_r[1]);
1071 static Pcre title_r("^(.*?) \\((.*)\\)$");
1072 if (title_r(data, size))
1073 return Simplify(title_r[1]);
1079 NSString *GetLastUpdate() {
1080 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1083 return UCLocalize("NEVER_OR_UNKNOWN");
1085 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1086 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1088 CFRelease(formatter);
1090 return [(NSString *) formatted autorelease];
1093 bool isSectionVisible(NSString *section) {
1094 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1095 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1096 return hidden == nil || ![hidden boolValue];
1101 /* Delegate Prototypes {{{ */
1104 @class CydiaProgressEvent;
1106 @protocol DatabaseDelegate
1107 - (void) repairWithSelector:(SEL)selector;
1108 - (void) setConfigurationData:(NSString *)data;
1109 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
1112 @class CYPackageController;
1114 @protocol CydiaDelegate
1115 - (void) retainNetworkActivityIndicator;
1116 - (void) releaseNetworkActivityIndicator;
1117 - (void) clearPackage:(Package *)package;
1118 - (void) installPackage:(Package *)package;
1119 - (void) installPackages:(NSArray *)packages;
1120 - (void) removePackage:(Package *)package;
1121 - (void) beginUpdate;
1123 - (void) distUpgrade;
1125 - (void) updateData;
1127 - (void) addTrivialSource:(NSString *)href;
1128 - (void) showSettings;
1129 - (UIProgressHUD *) addProgressHUD;
1130 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1131 - (CYViewController *) pageForPackage:(NSString *)name;
1132 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1133 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1137 /* ProgressEvent Interface/Delegate {{{ */
1138 @interface CydiaProgressEvent : NSObject {
1139 _H<NSString> message_;
1143 _H<NSString> package_;
1145 _H<NSString> version_;
1148 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type;
1149 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package;
1150 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item;
1152 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type;
1154 - (NSString *) message;
1155 - (NSString *) type;
1158 - (NSString *) package;
1160 - (NSString *) version;
1162 - (void) setItem:(NSArray *)item;
1163 - (void) setPackage:(NSString *)package;
1164 - (void) setURL:(NSString *)url;
1165 - (void) setVersion:(NSString *)version;
1167 - (NSString *) compound:(NSString *)value;
1168 - (NSString *) compoundMessage;
1169 - (NSString *) compoundTitle;
1173 @protocol ProgressDelegate
1174 - (void) addProgressEvent:(CydiaProgressEvent *)event;
1175 - (void) setProgressPercent:(NSNumber *)percent;
1176 - (void) setProgressStatus:(NSDictionary *)status;
1177 - (void) setProgressCancellable:(NSNumber *)cancellable;
1178 - (bool) isProgressCancelled;
1179 - (void) setTitle:(NSString *)title;
1182 /* Status Delegation {{{ */
1184 public pkgAcquireStatus
1187 _transient NSObject<ProgressDelegate> *delegate_;
1197 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1198 delegate_ = delegate;
1201 NSObject<ProgressDelegate> *getDelegate() const {
1205 virtual bool MediaChange(std::string media, std::string drive) {
1209 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1212 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1213 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1214 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
1215 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1218 virtual void Done(pkgAcquire::ItemDesc &item) {
1221 virtual void Fail(pkgAcquire::ItemDesc &item) {
1223 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1224 item.Owner->Status == pkgAcquire::Item::StatDone
1228 std::string &error(item.Owner->ErrorText);
1232 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
1233 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1236 virtual bool Pulse(pkgAcquire *Owner) {
1237 bool value = pkgAcquireStatus::Pulse(Owner);
1240 double(CurrentBytes + CurrentItems) /
1241 double(TotalBytes + TotalItems)
1244 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1245 [NSNumber numberWithDouble:percent], @"Percent",
1247 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1248 [NSNumber numberWithDouble:TotalBytes], @"Total",
1249 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1250 nil] waitUntilDone:YES];
1252 if (value && ![delegate_ isProgressCancelled])
1260 _finline bool WasCancelled() const {
1264 virtual void Start() {
1265 pkgAcquireStatus::Start();
1266 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1269 virtual void Stop() {
1270 pkgAcquireStatus::Stop();
1271 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1272 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1276 /* Database Interface {{{ */
1277 typedef std::map< unsigned long, _H<Source> > SourceMap;
1279 @interface Database : NSObject {
1285 pkgCacheFile cache_;
1286 pkgDepCache::Policy *policy_;
1287 pkgRecords *records_;
1288 pkgProblemResolver *resolver_;
1289 pkgAcquire *fetcher_;
1291 SPtr<pkgPackageManager> manager_;
1292 pkgSourceList *list_;
1294 SourceMap sourceMap_;
1295 NSMutableArray *sourceList_;
1297 CFMutableArrayRef packages_;
1299 _transient NSObject<DatabaseDelegate> *delegate_;
1300 _transient NSObject<ProgressDelegate> *progress_;
1308 std::map<const char *, _H<NSString> > sections_;
1311 + (Database *) sharedInstance;
1314 - (void) _readCydia:(NSNumber *)fd;
1315 - (void) _readStatus:(NSNumber *)fd;
1316 - (void) _readOutput:(NSNumber *)fd;
1320 - (Package *) packageWithName:(NSString *)name;
1322 - (pkgCacheFile &) cache;
1323 - (pkgDepCache::Policy *) policy;
1324 - (pkgRecords *) records;
1325 - (pkgProblemResolver *) resolver;
1326 - (pkgAcquire &) fetcher;
1327 - (pkgSourceList &) list;
1328 - (NSArray *) packages;
1329 - (NSArray *) sources;
1330 - (Source *) sourceWithKey:(NSString *)key;
1331 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1339 - (void) updateWithStatus:(Status &)status;
1341 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1343 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1344 - (NSObject<ProgressDelegate> *) progressDelegate;
1346 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1348 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1352 /* ProgressEvent Implementation {{{ */
1353 @implementation CydiaProgressEvent
1355 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1356 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1359 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1360 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1361 [event setPackage:package];
1365 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1366 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1368 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1369 NSArray *fields([description componentsSeparatedByString:@" "]);
1370 [event setItem:fields];
1372 if ([fields count] > 3) {
1373 [event setPackage:[fields objectAtIndex:2]];
1374 [event setVersion:[fields objectAtIndex:3]];
1377 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1382 + (NSArray *) _attributeKeys {
1383 return [NSArray arrayWithObjects:
1393 - (NSArray *) attributeKeys {
1394 return [[self class] _attributeKeys];
1397 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1398 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1401 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1402 if ((self = [super init]) != nil) {
1408 - (NSString *) message {
1412 - (NSString *) type {
1416 - (NSArray *) item {
1417 return (id) item_ ?: [NSNull null];
1420 - (void) setItem:(NSArray *)item {
1424 - (NSString *) package {
1425 return (id) package_ ?: [NSNull null];
1428 - (void) setPackage:(NSString *)package {
1432 - (NSString *) url {
1433 return (id) url_ ?: [NSNull null];
1436 - (void) setURL:(NSString *)url {
1440 - (void) setVersion:(NSString *)version {
1444 - (NSString *) version {
1445 return (id) version_ ?: [NSNull null];
1448 - (NSString *) compound:(NSString *)value {
1450 NSString *mode(nil); {
1451 NSString *type([self type]);
1452 if ([type isEqualToString:kCydiaProgressEventTypeError])
1453 mode = UCLocalize("ERROR");
1454 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1455 mode = UCLocalize("WARNING");
1459 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1465 - (NSString *) compoundMessage {
1466 return [self compound:[self message]];
1469 - (NSString *) compoundTitle {
1472 if (package_ == nil)
1474 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1475 title = [package name];
1479 return [self compound:title];
1485 // Cytore Definitions {{{
1486 struct PackageValue :
1489 Cytore::Offset<PackageValue> next_;
1491 uint32_t index_ : 23;
1492 uint32_t subscribed_ : 1;
1509 Cytore::Offset<PackageValue> packages_[1 << 16];
1512 static Cytore::File<MetaValue> MetaFile_;
1514 // Cytore Helper Functions {{{
1515 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1516 SplitHash nhash = { hashlittle(name, length) };
1518 PackageValue *metadata;
1520 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1521 offset: if (offset->IsNull()) {
1522 *offset = MetaFile_.New<PackageValue>(length + 1);
1523 metadata = &MetaFile_.Get(*offset);
1525 if (metadata == NULL) {
1529 metadata = new PackageValue();
1530 memset(metadata, 0, sizeof(*metadata));
1533 memcpy(metadata->name_, name, length + 1);
1534 metadata->nhash_ = nhash.u16[1];
1536 metadata = &MetaFile_.Get(*offset);
1538 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1539 offset = &metadata->next_;
1547 static void PackageImport(const void *key, const void *value, void *context) {
1548 bool &fail(*reinterpret_cast<bool *>(context));
1551 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1552 NSLog(@"failed to import package %@", key);
1556 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1557 NSDictionary *package((NSDictionary *) value);
1559 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1560 if ([subscribed boolValue] && !metadata->subscribed_)
1561 metadata->subscribed_ = true;
1563 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1564 time_t time([date timeIntervalSince1970]);
1565 if (metadata->first_ > time || metadata->first_ == 0)
1566 metadata->first_ = time;
1569 NSDate *date([package objectForKey:@"LastSeen"]);
1570 NSString *version([package objectForKey:@"LastVersion"]);
1572 if (date != nil && version != nil) {
1573 time_t time([date timeIntervalSince1970]);
1574 if (metadata->last_ < time || metadata->last_ == 0)
1575 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1576 size_t length(strlen(buffer));
1577 uint16_t vhash(hashlittle(buffer, length));
1579 size_t capped(std::min<size_t>(8, length));
1580 char *latest(buffer + length - capped);
1582 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1583 metadata->vhash_ = vhash;
1585 metadata->last_ = time;
1591 /* Source Class {{{ */
1592 @interface Source : NSObject {
1593 CYString depiction_;
1594 CYString description_;
1600 CYString distribution_;
1605 _H<NSString> authority_;
1607 CYString defaultIcon_;
1609 _H<NSDictionary> record_;
1613 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1615 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1617 - (NSString *) depictionForPackage:(NSString *)package;
1618 - (NSString *) supportForPackage:(NSString *)package;
1620 - (NSDictionary *) record;
1624 - (NSString *) distribution;
1625 - (NSString *) type;
1627 - (NSString *) host;
1629 - (NSString *) name;
1630 - (NSString *) shortDescription;
1631 - (NSString *) label;
1632 - (NSString *) origin;
1633 - (NSString *) version;
1635 - (NSString *) defaultIcon;
1639 @implementation Source
1643 distribution_.clear();
1646 description_.clear();
1652 defaultIcon_.clear();
1660 // XXX: this is a very inefficient way to call these deconstructors
1665 + (NSArray *) _attributeKeys {
1666 return [NSArray arrayWithObjects:
1673 @"shortDescription",
1681 - (NSArray *) attributeKeys {
1682 return [[self class] _attributeKeys];
1685 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1686 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1689 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1692 trusted_ = index->IsTrusted();
1694 uri_.set(pool, index->GetURI());
1695 distribution_.set(pool, index->GetDist());
1696 type_.set(pool, index->GetType());
1698 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1699 if (dindex != NULL) {
1701 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1704 pkgTagFile tags(&fd);
1706 pkgTagSection section;
1713 {"default-icon", &defaultIcon_},
1714 {"depiction", &depiction_},
1715 {"description", &description_},
1717 {"origin", &origin_},
1718 {"support", &support_},
1719 {"version", &version_},
1722 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1723 const char *start, *end;
1725 if (section.Find(names[i].name_, start, end)) {
1726 CYString &value(*names[i].value_);
1727 value.set(pool, start, end - start);
1733 record_ = [Sources_ objectForKey:[self key]];
1735 NSURL *url([NSURL URLWithString:uri_]);
1739 host_ = [host_ lowercaseString];
1742 // XXX: this is due to a bug in _H<>
1743 authority_ = (id) host_;
1745 authority_ = [url path];
1748 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1749 if ((self = [super init]) != nil) {
1750 [self setMetaIndex:index inPool:pool];
1754 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1755 NSDictionary *lhr = [self record];
1756 NSDictionary *rhr = [source record];
1759 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1761 NSString *lhs = [self name];
1762 NSString *rhs = [source name];
1764 if ([lhs length] != 0 && [rhs length] != 0) {
1765 unichar lhc = [lhs characterAtIndex:0];
1766 unichar rhc = [rhs characterAtIndex:0];
1768 if (isalpha(lhc) && !isalpha(rhc))
1769 return NSOrderedAscending;
1770 else if (!isalpha(lhc) && isalpha(rhc))
1771 return NSOrderedDescending;
1774 return [lhs compare:rhs options:LaxCompareOptions_];
1777 - (NSString *) depictionForPackage:(NSString *)package {
1778 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1781 - (NSString *) supportForPackage:(NSString *)package {
1782 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1785 - (NSDictionary *) record {
1793 - (NSString *) uri {
1797 - (NSString *) distribution {
1798 return distribution_;
1801 - (NSString *) type {
1805 - (NSString *) key {
1806 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1809 - (NSString *) host {
1813 - (NSString *) name {
1814 return origin_.empty() ? (id) authority_ : origin_;
1817 - (NSString *) shortDescription {
1818 return description_;
1821 - (NSString *) label {
1822 return label_.empty() ? (id) authority_ : label_;
1825 - (NSString *) origin {
1829 - (NSString *) version {
1833 - (NSString *) defaultIcon {
1834 return defaultIcon_;
1839 /* CydiaOperation Class {{{ */
1840 @interface CydiaOperation : NSObject {
1841 NSString *operator_;
1845 - (NSString *) operator;
1846 - (NSString *) value;
1850 @implementation CydiaOperation
1853 [operator_ release];
1858 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1859 if ((self = [super init]) != nil) {
1860 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1861 value_ = [[NSString alloc] initWithUTF8String:value];
1865 + (NSArray *) _attributeKeys {
1866 return [NSArray arrayWithObjects:
1872 - (NSArray *) attributeKeys {
1873 return [[self class] _attributeKeys];
1876 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1877 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1880 - (NSString *) operator {
1884 - (NSString *) value {
1890 /* CydiaClause Class {{{ */
1891 @interface CydiaClause : NSObject {
1893 CydiaOperation *version_;
1896 - (NSString *) package;
1897 - (CydiaOperation *) version;
1901 @implementation CydiaClause
1909 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1910 if ((self = [super init]) != nil) {
1911 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1913 if (const char *version = dep.TargetVer())
1914 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1916 version_ = [[NSNull null] retain];
1920 + (NSArray *) _attributeKeys {
1921 return [NSArray arrayWithObjects:
1927 - (NSArray *) attributeKeys {
1928 return [[self class] _attributeKeys];
1931 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1932 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1935 - (NSString *) package {
1939 - (CydiaOperation *) version {
1945 /* CydiaRelation Class {{{ */
1946 @interface CydiaRelation : NSObject {
1947 NSString *relationship_;
1948 NSMutableArray *clauses_;
1951 - (NSString *) relationship;
1952 - (NSArray *) clauses;
1956 @implementation CydiaRelation
1959 [relationship_ release];
1964 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1965 if ((self = [super init]) != nil) {
1966 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
1967 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
1969 pkgCache::DepIterator start;
1970 pkgCache::DepIterator end;
1971 dep.GlobOr(start, end); // ++dep
1974 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1976 // yes, seriously. (wtf?)
1984 + (NSArray *) _attributeKeys {
1985 return [NSArray arrayWithObjects:
1991 - (NSArray *) attributeKeys {
1992 return [[self class] _attributeKeys];
1995 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1996 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1999 - (NSString *) relationship {
2000 return relationship_;
2003 - (NSArray *) clauses {
2007 - (void) addClause:(CydiaClause *)clause {
2008 [clauses_ addObject:clause];
2013 /* Package Class {{{ */
2014 struct ParsedPackage {
2019 CYString depiction_;
2029 @interface Package : NSObject {
2032 uint32_t essential_ : 1;
2033 uint32_t obsolete_ : 1;
2034 uint32_t ignored_ : 1;
2038 _transient Database *database_;
2040 pkgCache::VerIterator version_;
2041 pkgCache::PkgIterator iterator_;
2042 pkgCache::VerFileIterator file_;
2048 CYString installed_;
2050 const char *section_;
2051 _transient NSString *section$_;
2055 PackageValue *metadata_;
2056 ParsedPackage *parsed_;
2058 NSMutableArray *tags_;
2061 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2062 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2064 - (pkgCache::PkgIterator) iterator;
2067 - (NSString *) section;
2068 - (NSString *) simpleSection;
2070 - (NSString *) longSection;
2071 - (NSString *) shortSection;
2075 - (Address *) maintainer;
2077 - (NSString *) longDescription;
2078 - (NSString *) shortDescription;
2081 - (PackageValue *) metadata;
2084 - (bool) subscribed;
2085 - (bool) setSubscribed:(bool)subscribed;
2089 - (NSString *) latest;
2090 - (NSString *) installed;
2091 - (BOOL) uninstalled;
2094 - (BOOL) upgradableAndEssential:(BOOL)essential;
2097 - (BOOL) unfiltered;
2101 - (BOOL) halfConfigured;
2102 - (BOOL) halfInstalled;
2104 - (NSString *) mode;
2107 - (NSString *) name;
2109 - (NSString *) homepage;
2110 - (NSString *) depiction;
2111 - (Address *) author;
2113 - (NSString *) support;
2115 - (NSArray *) files;
2116 - (NSArray *) warnings;
2117 - (NSArray *) applications;
2119 - (Source *) source;
2121 - (BOOL) matches:(NSString *)text;
2123 - (bool) hasSupportingRole;
2124 - (BOOL) hasTag:(NSString *)tag;
2125 - (NSString *) primaryPurpose;
2126 - (NSArray *) purposes;
2127 - (bool) isCommercial;
2129 - (void) setIndex:(size_t)index;
2131 - (CYString &) cyname;
2133 - (uint32_t) compareBySection:(NSArray *)sections;
2138 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2139 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2140 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2141 - (bool) isVisibleInSection:(NSString *)section;
2142 - (bool) isVisibleInSource:(Source *)source;
2146 uint32_t PackageChangesRadix(Package *self, void *) {
2151 uint32_t timestamp : 30;
2152 uint32_t ignored : 1;
2153 uint32_t upgradable : 1;
2157 bool upgradable([self upgradableAndEssential:YES]);
2158 value.bits.upgradable = upgradable ? 1 : 0;
2161 value.bits.timestamp = 0;
2162 value.bits.ignored = [self ignored] ? 0 : 1;
2163 value.bits.upgradable = 1;
2165 value.bits.timestamp = [self seen] >> 2;
2166 value.bits.ignored = 0;
2167 value.bits.upgradable = 0;
2170 return _not(uint32_t) - value.key;
2173 uint32_t PackagePrefixRadix(Package *self, void *context) {
2174 size_t offset(reinterpret_cast<size_t>(context));
2175 CYString &name([self cyname]);
2177 size_t size(name.size());
2180 char *text(name.data());
2183 if (!isdigit(text[0]))
2187 while (size != digits && isdigit(text[digits]))
2195 if (offset == 0 && zeros != 0) {
2196 memset(data, '0', zeros);
2197 memcpy(data + zeros, text, 4 - zeros);
2199 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2200 if (size <= offset - zeros)
2203 text += offset - zeros;
2204 size -= offset - zeros;
2207 memcpy(data, text, 4);
2209 memcpy(data, text, size);
2210 memset(data + size, 0, 4 - size);
2213 for (size_t i(0); i != 4; ++i)
2214 if (isalpha(data[i]))
2222 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2224 /* XXX: ntohl may be more honest */
2225 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2228 CYString &(*PackageName)(Package *self, SEL sel);
2230 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2231 _profile(PackageNameCompare)
2232 CYString &lhi(PackageName(lhs, @selector(cyname)));
2233 CYString &rhi(PackageName(rhs, @selector(cyname)));
2234 CFStringRef lhn(lhi), rhn(rhi);
2237 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2238 else if (rhn == NULL)
2239 return NSOrderedDescending;
2241 _profile(PackageNameCompare$NumbersLast)
2242 if (!lhi.empty() && !rhi.empty()) {
2243 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2244 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2245 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2246 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2247 return lha ? NSOrderedAscending : NSOrderedDescending;
2251 CFIndex length = CFStringGetLength(lhn);
2253 _profile(PackageNameCompare$Compare)
2254 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2259 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2260 return PackageNameCompare(*lhs, *rhs, context);
2263 struct PackageNameOrdering :
2264 std::binary_function<Package *, Package *, bool>
2266 _finline bool operator ()(Package *lhs, Package *rhs) const {
2267 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2271 @implementation Package
2273 - (NSString *) description {
2274 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2278 if (parsed_ != NULL)
2287 + (NSString *) webScriptNameForSelector:(SEL)selector {
2289 else if (selector == @selector(clear))
2291 else if (selector == @selector(getField:))
2293 else if (selector == @selector(hasTag:))
2295 else if (selector == @selector(install))
2297 else if (selector == @selector(remove))
2303 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2304 return [self webScriptNameForSelector:selector] == nil;
2307 + (NSArray *) _attributeKeys {
2308 return [NSArray arrayWithObjects:
2327 @"shortDescription",
2340 - (NSArray *) attributeKeys {
2341 return [[self class] _attributeKeys];
2344 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2345 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2348 - (NSArray *) relations {
2349 @synchronized (database_) {
2350 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2351 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2352 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2356 - (NSString *) getField:(NSString *)name {
2357 @synchronized (database_) {
2358 if ([database_ era] != era_ || file_.end())
2361 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2363 const char *start, *end;
2364 if (!parser.Find([name UTF8String], start, end))
2365 return (NSString *) [NSNull null];
2367 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2371 if (parsed_ != NULL)
2373 @synchronized (database_) {
2374 if ([database_ era] != era_ || file_.end())
2377 ParsedPackage *parsed(new ParsedPackage);
2380 _profile(Package$parse)
2381 pkgRecords::Parser *parser;
2383 _profile(Package$parse$Lookup)
2384 parser = &[database_ records]->Lookup(file_);
2389 _profile(Package$parse$Find)
2394 {"icon", &parsed->icon_},
2395 {"depiction", &parsed->depiction_},
2396 {"homepage", &parsed->homepage_},
2397 {"website", &website},
2398 {"bugs", &parsed->bugs_},
2399 {"support", &parsed->support_},
2400 {"sponsor", &parsed->sponsor_},
2401 {"author", &parsed->author_},
2404 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2405 const char *start, *end;
2407 if (parser->Find(names[i].name_, start, end)) {
2408 CYString &value(*names[i].value_);
2409 _profile(Package$parse$Value)
2410 value.set(pool_, start, end - start);
2416 _profile(Package$parse$Tagline)
2417 const char *start, *end;
2418 if (parser->ShortDesc(start, end)) {
2419 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2422 while (stop != start && stop[-1] == '\r')
2424 parsed->tagline_.set(pool_, start, stop - start);
2428 _profile(Package$parse$Retain)
2429 if (parsed->homepage_.empty())
2430 parsed->homepage_ = website;
2431 if (parsed->homepage_ == parsed->depiction_)
2432 parsed->homepage_.clear();
2437 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2438 if ((self = [super init]) != nil) {
2439 _profile(Package$initWithVersion)
2442 database_ = database;
2443 era_ = [database era];
2447 pkgCache::PkgIterator iterator(version.ParentPkg());
2448 iterator_ = iterator;
2450 _profile(Package$initWithVersion$Version)
2451 if (!version_.end())
2452 file_ = version_.FileList();
2454 pkgCache &cache([database_ cache]);
2455 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2459 _profile(Package$initWithVersion$Cache)
2460 name_.set(NULL, iterator.Display());
2462 latest_.set(NULL, StripVersion_(version_.VerStr()));
2464 pkgCache::VerIterator current(iterator.CurrentVer());
2466 installed_.set(NULL, StripVersion_(current.VerStr()));
2469 _profile(Package$initWithVersion$Tags)
2470 pkgCache::TagIterator tag(iterator.TagList());
2472 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2474 const char *name(tag.Name());
2475 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2477 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2478 if (strcmp(name + 6, "enduser") == 0)
2480 else if (strcmp(name + 6, "hacker") == 0)
2482 else if (strcmp(name + 6, "developer") == 0)
2484 else if (strcmp(name + 6, "cydia") == 0)
2490 if (strncmp(name, "cydia::", 7) == 0) {
2491 if (strcmp(name + 7, "essential") == 0)
2493 else if (strcmp(name + 7, "obsolete") == 0)
2498 } while (!tag.end());
2502 _profile(Package$initWithVersion$Metadata)
2503 const char *mixed(iterator.Name());
2504 size_t size(strlen(mixed));
2505 char lower[size + 1];
2507 for (size_t i(0); i != size; ++i)
2508 lower[i] = mixed[i] | 0x20;
2511 PackageValue *metadata(PackageFind(lower, size));
2512 metadata_ = metadata;
2514 id_.set(NULL, metadata->name_, size);
2516 const char *latest(version_.VerStr());
2517 size_t length(strlen(latest));
2519 uint16_t vhash(hashlittle(latest, length));
2521 size_t capped(std::min<size_t>(8, length));
2522 latest = latest + length - capped;
2524 if (metadata->first_ == 0)
2525 metadata->first_ = now_;
2527 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2528 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2529 metadata->vhash_ = vhash;
2530 metadata->last_ = now_;
2531 } else if (metadata->last_ == 0)
2532 metadata->last_ = metadata->first_;
2535 _profile(Package$initWithVersion$Section)
2536 section_ = iterator.Section();
2539 _profile(Package$initWithVersion$Flags)
2540 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2541 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2546 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2547 pkgCache::VerIterator version;
2549 _profile(Package$packageWithIterator$GetCandidateVer)
2550 version = [database policy]->GetCandidateVer(iterator);
2558 _profile(Package$packageWithIterator$Allocate)
2559 package = [Package allocWithZone:zone];
2562 _profile(Package$packageWithIterator$Initialize)
2564 initWithVersion:version
2571 _profile(Package$packageWithIterator$Autorelease)
2572 package = [package autorelease];
2578 - (pkgCache::PkgIterator) iterator {
2582 - (NSString *) section {
2583 if (section$_ == nil) {
2584 if (section_ == NULL)
2587 _profile(Package$section$mappedSectionForPointer)
2588 section$_ = [database_ mappedSectionForPointer:section_];
2593 - (NSString *) simpleSection {
2594 if (NSString *section = [self section])
2595 return Simplify(section);
2600 - (NSString *) longSection {
2601 return LocalizeSection([self section]);
2604 - (NSString *) shortSection {
2605 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2608 - (NSString *) uri {
2611 pkgIndexFile *index;
2612 pkgCache::PkgFileIterator file(file_.File());
2613 if (![database_ list].FindIndex(file, index))
2615 return [NSString stringWithUTF8String:iterator_->Path];
2616 //return [NSString stringWithUTF8String:file.Site()];
2617 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2621 - (Address *) maintainer {
2622 @synchronized (database_) {
2623 if ([database_ era] != era_ || file_.end())
2626 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2627 const std::string &maintainer(parser->Maintainer());
2628 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2632 @synchronized (database_) {
2633 if ([database_ era] != era_ || version_.end())
2636 return version_->InstalledSize;
2639 - (NSString *) longDescription {
2640 @synchronized (database_) {
2641 if ([database_ era] != era_ || file_.end())
2644 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2645 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2647 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2648 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2649 if ([lines count] < 2)
2652 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2653 for (size_t i(1), e([lines count]); i != e; ++i) {
2654 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2655 [trimmed addObject:trim];
2658 return [trimmed componentsJoinedByString:@"\n"];
2661 - (NSString *) shortDescription {
2662 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2666 _profile(Package$index)
2667 CFStringRef name((CFStringRef) [self name]);
2668 if (CFStringGetLength(name) == 0)
2670 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2671 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2673 return toupper(character);
2677 - (PackageValue *) metadata {
2682 PackageValue *metadata([self metadata]);
2683 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2686 - (bool) subscribed {
2687 return [self metadata]->subscribed_;
2690 - (bool) setSubscribed:(bool)subscribed {
2691 PackageValue *metadata([self metadata]);
2692 if (metadata->subscribed_ == subscribed)
2694 metadata->subscribed_ = subscribed;
2702 - (NSString *) latest {
2706 - (NSString *) installed {
2710 - (BOOL) uninstalled {
2711 return installed_.empty();
2715 return !version_.end();
2718 - (BOOL) upgradableAndEssential:(BOOL)essential {
2719 _profile(Package$upgradableAndEssential)
2720 pkgCache::VerIterator current(iterator_.CurrentVer());
2722 return essential && essential_;
2724 return !version_.end() && version_ != current;
2728 - (BOOL) essential {
2733 return [database_ cache][iterator_].InstBroken();
2736 - (BOOL) unfiltered {
2737 _profile(Package$unfiltered$obsolete)
2738 if (_unlikely(obsolete_))
2742 _profile(Package$unfiltered$hasSupportingRole)
2743 if (_unlikely(![self hasSupportingRole]))
2751 if (![self unfiltered])
2756 _profile(Package$visible$section)
2757 section = [self section];
2760 _profile(Package$visible$isSectionVisible)
2761 if (!isSectionVisible(section))
2769 unsigned char current(iterator_->CurrentState);
2770 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2773 - (BOOL) halfConfigured {
2774 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2777 - (BOOL) halfInstalled {
2778 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2782 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2783 return state.Mode != pkgDepCache::ModeKeep;
2786 - (NSString *) mode {
2787 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2789 switch (state.Mode) {
2790 case pkgDepCache::ModeDelete:
2791 if ((state.iFlags & pkgDepCache::Purge) != 0)
2795 case pkgDepCache::ModeKeep:
2796 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2797 return @"REINSTALL";
2798 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2802 case pkgDepCache::ModeInstall:
2803 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2804 return @"REINSTALL";
2805 else*/ switch (state.Status) {
2807 return @"DOWNGRADE";
2813 return @"NEW_INSTALL";
2824 - (NSString *) name {
2825 return name_.empty() ? id_ : name_;
2828 - (UIImage *) icon {
2829 NSString *section = [self simpleSection];
2832 if (parsed_ != NULL)
2833 if (NSString *href = parsed_->icon_)
2834 if ([href hasPrefix:@"file:///"])
2835 // XXX: correct escaping
2836 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2837 if (icon == nil) if (section != nil)
2838 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2839 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2840 if ([dicon hasPrefix:@"file:///"])
2841 // XXX: correct escaping
2842 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2844 icon = [UIImage applicationImageNamed:@"unknown.png"];
2848 - (NSString *) homepage {
2849 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2852 - (NSString *) depiction {
2853 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2856 - (Address *) sponsor {
2857 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2860 - (Address *) author {
2861 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2864 - (NSString *) support {
2865 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2868 - (NSArray *) files {
2869 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2870 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2873 fin.open([path UTF8String]);
2878 while (std::getline(fin, line))
2879 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2884 - (NSString *) state {
2885 @synchronized (database_) {
2886 if ([database_ era] != era_ || file_.end())
2889 switch (iterator_->CurrentState) {
2890 case pkgCache::State::NotInstalled:
2891 return @"NotInstalled";
2892 case pkgCache::State::UnPacked:
2894 case pkgCache::State::HalfConfigured:
2895 return @"HalfConfigured";
2896 case pkgCache::State::HalfInstalled:
2897 return @"HalfInstalled";
2898 case pkgCache::State::ConfigFiles:
2899 return @"ConfigFiles";
2900 case pkgCache::State::Installed:
2901 return @"Installed";
2902 case pkgCache::State::TriggersAwaited:
2903 return @"TriggersAwaited";
2904 case pkgCache::State::TriggersPending:
2905 return @"TriggersPending";
2908 return (NSString *) [NSNull null];
2911 - (NSString *) selection {
2912 @synchronized (database_) {
2913 if ([database_ era] != era_ || file_.end())
2916 switch (iterator_->SelectedState) {
2917 case pkgCache::State::Unknown:
2919 case pkgCache::State::Install:
2921 case pkgCache::State::Hold:
2923 case pkgCache::State::DeInstall:
2924 return @"DeInstall";
2925 case pkgCache::State::Purge:
2929 return (NSString *) [NSNull null];
2932 - (NSArray *) warnings {
2933 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2934 const char *name(iterator_.Name());
2936 size_t length(strlen(name));
2937 if (length < 2) invalid:
2938 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2939 else for (size_t i(0); i != length; ++i)
2941 /* XXX: technically this is not allowed */
2942 (name[i] < 'A' || name[i] > 'Z') &&
2943 (name[i] < 'a' || name[i] > 'z') &&
2944 (name[i] < '0' || name[i] > '9') &&
2945 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2948 if (strcmp(name, "cydia") != 0) {
2951 bool _private = false;
2954 bool repository = [[self section] isEqualToString:@"Repositories"];
2956 if (NSArray *files = [self files])
2957 for (NSString *file in files)
2958 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2960 else if (!user && [file isEqualToString:@"/User"])
2962 else if (!_private && [file isEqualToString:@"/private"])
2964 else if (!stash && [file isEqualToString:@"/var/stash"])
2967 /* XXX: this is not sensitive enough. only some folders are valid. */
2968 if (cydia && !repository)
2969 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2971 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2973 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2975 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2978 return [warnings count] == 0 ? nil : warnings;
2981 - (NSArray *) applications {
2982 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2984 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2986 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2987 if (NSArray *files = [self files])
2988 for (NSString *file in files)
2989 if (application_r(file)) {
2990 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2991 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2992 if ([id isEqualToString:me])
2995 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2997 display = application_r[1];
2999 NSString *bundle([file stringByDeletingLastPathComponent]);
3000 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3001 if (icon == nil || [icon length] == 0)
3003 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3005 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3006 [applications addObject:application];
3008 [application addObject:id];
3009 [application addObject:display];
3010 [application addObject:url];
3013 return [applications count] == 0 ? nil : applications;
3016 - (Source *) source {
3017 if (source_ == nil) {
3018 @synchronized (database_) {
3019 if ([database_ era] != era_ || file_.end())
3020 source_ = (Source *) [NSNull null];
3022 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
3026 return source_ == (Source *) [NSNull null] ? nil : source_;
3029 - (BOOL) matches:(NSString *)text {
3035 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
3036 if (range.location != NSNotFound)
3039 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
3040 if (range.location != NSNotFound)
3045 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
3046 if (range.location != NSNotFound)
3052 - (bool) hasSupportingRole {
3057 if ([Role_ isEqualToString:@"User"])
3061 if ([Role_ isEqualToString:@"Hacker"])
3065 if ([Role_ isEqualToString:@"Developer"])
3070 - (NSArray *) tags {
3074 - (BOOL) hasTag:(NSString *)tag {
3075 return tags_ == nil ? NO : [tags_ containsObject:tag];
3078 - (NSString *) primaryPurpose {
3079 for (NSString *tag in tags_)
3080 if ([tag hasPrefix:@"purpose::"])
3081 return [tag substringFromIndex:9];
3085 - (NSArray *) purposes {
3086 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3087 for (NSString *tag in tags_)
3088 if ([tag hasPrefix:@"purpose::"])
3089 [purposes addObject:[tag substringFromIndex:9]];
3090 return [purposes count] == 0 ? nil : purposes;
3093 - (bool) isCommercial {
3094 return [self hasTag:@"cydia::commercial"];
3097 - (void) setIndex:(size_t)index {
3098 if (metadata_->index_ != index)
3099 metadata_->index_ = index;
3102 - (CYString &) cyname {
3103 return name_.empty() ? id_ : name_;
3106 - (uint32_t) compareBySection:(NSArray *)sections {
3107 NSString *section([self section]);
3108 for (size_t i(0), e([sections count]); i != e; ++i) {
3109 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3113 return _not(uint32_t);
3117 @synchronized (database_) {
3118 pkgProblemResolver *resolver = [database_ resolver];
3119 resolver->Clear(iterator_);
3121 pkgCacheFile &cache([database_ cache]);
3122 cache->SetReInstall(iterator_, false);
3123 cache->MarkKeep(iterator_, false);
3127 @synchronized (database_) {
3128 pkgProblemResolver *resolver = [database_ resolver];
3129 resolver->Clear(iterator_);
3130 resolver->Protect(iterator_);
3132 pkgCacheFile &cache([database_ cache]);
3133 cache->SetReInstall(iterator_, false);
3134 cache->MarkInstall(iterator_, false);
3136 pkgDepCache::StateCache &state((*cache)[iterator_]);
3137 if (!state.Install())
3138 cache->SetReInstall(iterator_, true);
3142 @synchronized (database_) {
3143 pkgProblemResolver *resolver = [database_ resolver];
3144 resolver->Clear(iterator_);
3145 resolver->Remove(iterator_);
3146 resolver->Protect(iterator_);
3148 pkgCacheFile &cache([database_ cache]);
3149 cache->SetReInstall(iterator_, false);
3150 cache->MarkDelete(iterator_, true);
3153 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3154 _profile(Package$isUnfilteredAndSearchedForBy)
3157 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3158 value &= [self unfiltered];
3161 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3162 value &= [self matches:search];
3169 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3170 if ([search length] == 0)
3173 _profile(Package$isUnfilteredAndSelectedForBy)
3176 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3177 value &= [self unfiltered];
3180 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3181 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3188 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3189 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3192 - (bool) isVisibleInSection:(NSString *)name {
3193 NSString *section([self section]);
3197 section == nil && [name length] == 0 ||
3198 [name isEqualToString:section]
3199 ) && [self visible];
3202 - (bool) isVisibleInSource:(Source *)source {
3203 return [self source] == source && [self visible];
3208 /* Section Class {{{ */
3209 @interface Section : NSObject {
3214 NSString *localized_;
3217 - (NSComparisonResult) compareByLocalized:(Section *)section;
3218 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3219 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3220 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3221 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3222 - (NSString *) name;
3229 - (void) addToCount;
3231 - (void) setCount:(size_t)count;
3232 - (NSString *) localized;
3236 @implementation Section
3240 if (localized_ != nil)
3241 [localized_ release];
3245 - (NSComparisonResult) compareByLocalized:(Section *)section {
3246 NSString *lhs(localized_);
3247 NSString *rhs([section localized]);
3249 /*if ([lhs length] != 0 && [rhs length] != 0) {
3250 unichar lhc = [lhs characterAtIndex:0];
3251 unichar rhc = [rhs characterAtIndex:0];
3253 if (isalpha(lhc) && !isalpha(rhc))
3254 return NSOrderedAscending;
3255 else if (!isalpha(lhc) && isalpha(rhc))
3256 return NSOrderedDescending;
3259 return [lhs compare:rhs options:LaxCompareOptions_];
3262 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3263 if ((self = [self initWithName:name localize:NO]) != nil) {
3264 if (localized != nil)
3265 localized_ = [localized retain];
3269 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3270 return [self initWithName:name row:0 localize:localize];
3273 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3274 if ((self = [super init]) != nil) {
3275 name_ = [name retain];
3279 localized_ = [LocalizeSection(name_) retain];
3283 /* XXX: localize the index thingees */
3284 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3285 if ((self = [super init]) != nil) {
3286 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3292 - (NSString *) name {
3312 - (void) addToCount {
3316 - (void) setCount:(size_t)count {
3320 - (NSString *) localized {
3327 static NSString *Colon_;
3328 static NSString *Elision_;
3329 static NSString *Error_;
3330 static NSString *Warning_;
3332 /* Database Implementation {{{ */
3333 @implementation Database
3335 + (Database *) sharedInstance {
3336 static Database *instance;
3337 if (instance == nil)
3338 instance = [[Database alloc] init];
3346 - (void) releasePackages {
3347 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3348 CFArrayRemoveAllValues(packages_);
3352 // XXX: actually implement this thing
3354 [sourceList_ release];
3355 [self releasePackages];
3356 apr_pool_destroy(pool_);
3357 NSRecycleZone(zone_);
3361 - (void) _readCydia:(NSNumber *)fd { _pooled
3362 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3363 std::istream is(&ib);
3366 static Pcre finish_r("^finish:([^:]*)$");
3368 while (std::getline(is, line)) {
3369 const char *data(line.c_str());
3370 size_t size = line.size();
3371 lprintf("C:%s\n", data);
3373 if (finish_r(data, size)) {
3374 NSString *finish = finish_r[1];
3375 int index = [Finishes_ indexOfObject:finish];
3376 if (index != INT_MAX && index > Finish_)
3384 - (void) _readStatus:(NSNumber *)fd { _pooled
3385 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3386 std::istream is(&ib);
3389 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3390 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3392 while (std::getline(is, line)) {
3393 const char *data(line.c_str());
3394 size_t size(line.size());
3395 lprintf("S:%s\n", data);
3397 if (conffile_r(data, size)) {
3398 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3399 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3400 } else if (strncmp(data, "status: ", 8) == 0) {
3401 // status: <package>: {unpacked,half-configured,installed}
3402 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3403 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3404 } else if (strncmp(data, "processing: ", 12) == 0) {
3405 // processing: configure: config-test
3406 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3407 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3408 } else if (pmstatus_r(data, size)) {
3409 std::string type([pmstatus_r[1] UTF8String]);
3411 NSString *package = pmstatus_r[2];
3412 if ([package isEqualToString:@"dpkg-exec"])
3415 float percent([pmstatus_r[3] floatValue]);
3416 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3418 NSString *string = pmstatus_r[4];
3420 if (type == "pmerror") {
3421 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3422 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3423 } else if (type == "pmstatus") {
3424 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3425 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3426 } else if (type == "pmconffile")
3427 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3429 lprintf("E:unknown pmstatus\n");
3431 lprintf("E:unknown status\n");
3437 - (void) _readOutput:(NSNumber *)fd { _pooled
3438 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3439 std::istream is(&ib);
3442 while (std::getline(is, line)) {
3443 lprintf("O:%s\n", line.c_str());
3445 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3446 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3456 - (Package *) packageWithName:(NSString *)name {
3457 @synchronized (self) {
3458 if (static_cast<pkgDepCache *>(cache_) == NULL)
3460 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3461 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3465 if ((self = [super init]) != nil) {
3472 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3473 apr_pool_create(&pool_, NULL);
3475 size_t capacity(MetaFile_->active_);
3481 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3482 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3486 _assert(pipe(fds) != -1);
3489 _config->Set("APT::Keep-Fds::", cydiafd_);
3490 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3493 detachNewThreadSelector:@selector(_readCydia:)
3495 withObject:[NSNumber numberWithInt:fds[0]]
3498 _assert(pipe(fds) != -1);
3502 detachNewThreadSelector:@selector(_readStatus:)
3504 withObject:[NSNumber numberWithInt:fds[0]]
3507 _assert(pipe(fds) != -1);
3508 _assert(dup2(fds[0], 0) != -1);
3509 _assert(close(fds[0]) != -1);
3511 input_ = fdopen(fds[1], "a");
3513 _assert(pipe(fds) != -1);
3514 _assert(dup2(fds[1], 1) != -1);
3515 _assert(close(fds[1]) != -1);
3518 detachNewThreadSelector:@selector(_readOutput:)
3520 withObject:[NSNumber numberWithInt:fds[0]]
3525 - (pkgCacheFile &) cache {
3529 - (pkgDepCache::Policy *) policy {
3533 - (pkgRecords *) records {
3537 - (pkgProblemResolver *) resolver {
3541 - (pkgAcquire &) fetcher {
3545 - (pkgSourceList &) list {
3549 - (NSArray *) packages {
3550 return (NSArray *) packages_;
3553 - (NSArray *) sources {
3557 - (Source *) sourceWithKey:(NSString *)key {
3558 for (Source *source in [self sources]) {
3559 if ([[source key] isEqualToString:key])
3564 - (bool) popErrorWithTitle:(NSString *)title {
3567 while (!_error->empty()) {
3569 bool warning(!_error->PopMessage(error));
3574 size_t size(error.size());
3575 if (size == 0 || error[size - 1] != '\n')
3577 error.resize(size - 1);
3580 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3582 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3588 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3589 return [self popErrorWithTitle:title] || !success;
3592 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3593 @synchronized (self) {
3596 [self releasePackages];
3599 [sourceList_ removeAllObjects];
3619 apr_pool_clear(pool_);
3621 NSRecycleZone(zone_);
3622 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3624 int chk(creat("/tmp/cydia.chk", 0644));
3628 if (invocation != nil)
3629 [invocation invoke];
3631 NSString *title(UCLocalize("DATABASE"));
3634 OpProgress progress;
3635 while (!cache_.Open(progress, true)) { pop:
3637 bool warning(!_error->PopMessage(error));
3638 lprintf("cache_.Open():[%s]\n", error.c_str());
3640 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3641 [delegate_ repairWithSelector:@selector(configure)];
3642 else if (error == "The package lists or status file could not be parsed or opened.")
3643 [delegate_ repairWithSelector:@selector(update)];
3644 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3645 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3646 // else if (error == "Malformed Status line")
3647 // else if (error == "The list of sources could not be read.")
3649 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3659 unlink("/tmp/cydia.chk");
3661 now_ = [[NSDate date] timeIntervalSince1970];
3663 policy_ = new pkgDepCache::Policy();
3664 records_ = new pkgRecords(cache_);
3665 resolver_ = new pkgProblemResolver(cache_);
3666 fetcher_ = new pkgAcquire(&status_);
3669 list_ = new pkgSourceList();
3670 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3673 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3674 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3678 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3681 if (cache_->BrokenCount() != 0) {
3682 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3685 if (cache_->BrokenCount() != 0) {
3686 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3690 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3694 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3695 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3696 [sourceList_ addObject:object];
3698 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3699 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3700 // XXX: this could be more intelligent
3701 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3702 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3704 sourceMap_[cached->ID] = object;
3709 /*std::vector<Package *> packages;
3710 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3711 [packages_ release];
3716 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3717 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3718 //packages.push_back(package);
3719 CFArrayAppendValue(packages_, [package retain]);
3723 /*if (packages.empty())
3724 packages_ = [[NSArray alloc] init];
3726 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3729 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3730 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3731 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3739 /*if (!packages.empty())
3740 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3741 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3743 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3745 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3747 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3751 size_t count(CFArrayGetCount(packages_));
3752 MetaFile_->active_ = count;
3754 for (size_t index(0); index != count; ++index)
3755 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3759 } } CYPoolEnd() _trace(); }
3762 @synchronized (self) {
3764 resolver_ = new pkgProblemResolver(cache_);
3766 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3767 if (!cache_[iterator].Keep())
3768 cache_->MarkKeep(iterator, false);
3769 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3770 cache_->SetReInstall(iterator, false);
3773 - (void) configure {
3774 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3776 system([dpkg UTF8String]);
3781 // XXX: I don't remember this condition
3786 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3788 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3790 if ([self popErrorWithTitle:title])
3794 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3797 public pkgArchiveCleaner
3800 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3805 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3812 fetcher_->Shutdown();
3814 pkgRecords records(cache_);
3816 lock_ = new FileFd();
3817 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3819 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3821 if ([self popErrorWithTitle:title])
3825 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3828 manager_ = (_system->CreatePM(cache_));
3829 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3836 bool substrate(RestartSubstrate_);
3837 RestartSubstrate_ = false;
3839 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3841 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3843 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3845 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3846 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3849 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3851 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3853 [self popErrorWithTitle:title];
3857 bool failed = false;
3858 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3859 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3861 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3867 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3875 RestartSubstrate_ = true;
3878 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3880 if (_error->PendingError()) {
3885 if (result == pkgPackageManager::Failed) {
3890 if (result != pkgPackageManager::Completed) {
3895 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3897 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3899 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3900 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3903 if (![before isEqualToArray:after])
3908 NSString *title(UCLocalize("UPGRADE"));
3909 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3915 [self updateWithStatus:status_];
3918 - (void) updateWithStatus:(Status &)status {
3919 NSString *title(UCLocalize("REFRESHING_DATA"));
3922 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3926 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3927 if ([self popErrorWithTitle:title])
3930 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3932 bool success(ListUpdate(status, list, PulseInterval_));
3933 if (status.WasCancelled())
3936 [self popErrorWithTitle:title forOperation:success];
3938 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3940 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3944 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3945 delegate_ = delegate;
3948 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3949 progress_ = delegate;
3950 status_.setDelegate(delegate);
3953 - (NSObject<ProgressDelegate> *) progressDelegate {
3957 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3958 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3959 return i == sourceMap_.end() ? nil : i->second;
3962 - (NSString *) mappedSectionForPointer:(const char *)section {
3963 _H<NSString> *mapped;
3965 _profile(Database$mappedSectionForPointer$Cache)
3966 mapped = §ions_[section];
3969 if (*mapped == NULL) {
3970 size_t length(strlen(section));
3971 char spaced[length + 1];
3973 _profile(Database$mappedSectionForPointer$Replace)
3974 for (size_t index(0); index != length; ++index)
3975 spaced[index] = section[index] == '_' ? ' ' : section[index];
3976 spaced[length] = '\0';
3981 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3982 string = [NSString stringWithUTF8String:spaced];
3985 _profile(Database$mappedSectionForPointer$Map)
3986 string = [SectionMap_ objectForKey:string] ?: string;
3996 static NSMutableSet *Diversions_;
3998 @interface Diversion : NSObject {
4001 _H<NSString> format_;
4006 @implementation Diversion
4008 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4009 if ((self = [super init]) != nil) {
4010 pattern_ = [from UTF8String];
4016 - (NSString *) divert:(NSString *)url {
4017 return !pattern_(url) ? nil : pattern_->*format_;
4020 + (NSURL *) divertURL:(NSURL *)url {
4022 NSString *href([url absoluteString]);
4024 for (Diversion *diversion in Diversions_)
4025 if (NSString *diverted = [diversion divert:href]) {
4027 NSLog(@"div: %@", diverted);
4029 url = [NSURL URLWithString:diverted];
4036 - (NSString *) key {
4040 - (NSUInteger) hash {
4044 - (BOOL) isEqual:(Diversion *)object {
4045 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4050 @interface CydiaObject : NSObject {
4052 _transient id delegate_;
4055 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4059 @interface CYBrowserController : BrowserController {
4060 CydiaObject *cydia_;
4063 + (void) addDiversion:(Diversion *)diversion;
4067 /* Web Scripting {{{ */
4068 @implementation CydiaObject
4071 [indirect_ release];
4075 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4076 if ((self = [super init]) != nil) {
4077 indirect_ = [indirect retain];
4081 - (void) setDelegate:(id)delegate {
4082 delegate_ = delegate;
4085 + (NSArray *) _attributeKeys {
4086 return [NSArray arrayWithObjects:
4101 - (NSArray *) attributeKeys {
4102 return [[self class] _attributeKeys];
4105 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4106 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4109 - (NSString *) version {
4113 - (NSString *) device {
4114 return [[UIDevice currentDevice] uniqueIdentifier];
4117 - (NSString *) firmware {
4118 return [[UIDevice currentDevice] systemVersion];
4121 - (NSString *) hostname {
4122 return [[UIDevice currentDevice] name];
4125 - (NSString *) idiom {
4126 return (id) Idiom_ ?: [NSNull null];
4129 - (NSString *) plmn {
4130 return (id) PLMN_ ?: [NSNull null];
4133 - (NSString *) ecid {
4134 return (id) ChipID_ ?: [NSNull null];
4137 - (NSString *) serial {
4138 return SerialNumber_;
4141 - (NSString *) role {
4142 return (id) Role_ ?: [NSNull null];
4145 - (NSString *) model {
4146 return [NSString stringWithUTF8String:Machine_];
4149 - (NSString *) token {
4150 return (id) Token_ ?: [NSNull null];
4153 + (NSString *) webScriptNameForSelector:(SEL)selector {
4155 else if (selector == @selector(addBridgedHost:))
4156 return @"addBridgedHost";
4157 else if (selector == @selector(addPipelinedHost:scheme:))
4158 return @"addPipelinedHost";
4159 else if (selector == @selector(addTrivialSource:))
4160 return @"addTrivialSource";
4161 else if (selector == @selector(close))
4163 else if (selector == @selector(divert::))
4165 else if (selector == @selector(du:))
4167 else if (selector == @selector(stringWithFormat:arguments:))
4169 else if (selector == @selector(getAllSources))
4170 return @"getAllSourcs";
4171 else if (selector == @selector(getKernelNumber:))
4172 return @"getKernelNumber";
4173 else if (selector == @selector(getKernelString:))
4174 return @"getKernelString";
4175 else if (selector == @selector(getInstalledPackages))
4176 return @"getInstalledPackages";
4177 else if (selector == @selector(getLocaleIdentifier))
4178 return @"getLocaleIdentifier";
4179 else if (selector == @selector(getPreferredLanguages))
4180 return @"getPreferredLanguages";
4181 else if (selector == @selector(getPackageById:))
4182 return @"getPackageById";
4183 else if (selector == @selector(getSessionValue:))
4184 return @"getSessionValue";
4185 else if (selector == @selector(installPackages:))
4186 return @"installPackages";
4187 else if (selector == @selector(localizedStringForKey:value:table:))
4189 else if (selector == @selector(popViewController:))
4190 return @"popViewController";
4191 else if (selector == @selector(refreshSources))
4192 return @"refreshSources";
4193 else if (selector == @selector(removeButton))
4194 return @"removeButton";
4195 else if (selector == @selector(setSessionValue::))
4196 return @"setSessionValue";
4197 else if (selector == @selector(substitutePackageNames:))
4198 return @"substitutePackageNames";
4199 else if (selector == @selector(scrollToBottom:))
4200 return @"scrollToBottom";
4201 else if (selector == @selector(setAllowsNavigationAction:))
4202 return @"setAllowsNavigationAction";
4203 else if (selector == @selector(setBadgeValue:))
4204 return @"setBadgeValue";
4205 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4206 return @"setButtonImage";
4207 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4208 return @"setButtonTitle";
4209 else if (selector == @selector(setHidesBackButton:))
4210 return @"setHidesBackButton";
4211 else if (selector == @selector(setHidesNavigationBar:))
4212 return @"setHidesNavigationBar";
4213 else if (selector == @selector(setNavigationBarStyle:))
4214 return @"setNavigationBarStyle";
4215 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4216 return @"setNavigationBarTintColor";
4217 else if (selector == @selector(setPasteboardString:))
4218 return @"setPasteboardString";
4219 else if (selector == @selector(setPasteboardURL:))
4220 return @"setPasteboardURL";
4221 else if (selector == @selector(setToken:))
4223 else if (selector == @selector(setViewportWidth:))
4224 return @"setViewportWidth";
4225 else if (selector == @selector(statfs:))
4227 else if (selector == @selector(supports:))
4233 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4234 return [self webScriptNameForSelector:selector] == nil;
4237 - (BOOL) supports:(NSString *)feature {
4238 return [feature isEqualToString:@"window.open"];
4241 - (void) divert:(NSString *)from :(NSString *)to {
4242 [CYBrowserController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4245 - (NSNumber *) getKernelNumber:(NSString *)name {
4246 const char *string([name UTF8String]);
4249 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4250 return (id) [NSNull null];
4252 if (size != sizeof(int))
4253 return (id) [NSNull null];
4256 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4257 return (id) [NSNull null];
4259 return [NSNumber numberWithInt:value];
4262 - (NSString *) getKernelString:(NSString *)name {
4263 const char *string([name UTF8String]);
4266 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4267 return (id) [NSNull null];
4269 char value[size + 1];
4270 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4271 return (id) [NSNull null];
4273 // XXX: just in case you request something ludicrous
4276 return [NSString stringWithCString:value];
4279 - (id) getSessionValue:(NSString *)key {
4280 @synchronized (SessionData_) {
4281 return [SessionData_ objectForKey:key];
4284 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4285 @synchronized (SessionData_) {
4286 if (value == (id) [WebUndefined undefined])
4287 [SessionData_ removeObjectForKey:key];
4289 [SessionData_ setObject:value forKey:key];
4292 - (void) addBridgedHost:(NSString *)host {
4293 @synchronized (HostConfig_) {
4294 [BridgedHosts_ addObject:host];
4297 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4298 @synchronized (HostConfig_) {
4299 if (scheme != (id) [WebUndefined undefined])
4300 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4302 [PipelinedHosts_ addObject:host];
4305 - (void) popViewController:(NSNumber *)value {
4306 if (value == (id) [WebUndefined undefined])
4307 value = [NSNumber numberWithBool:YES];
4308 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4311 - (void) addTrivialSource:(NSString *)href {
4312 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4315 - (void) refreshSources {
4316 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4319 - (NSArray *) getAllSources {
4320 return [[Database sharedInstance] sources];
4323 - (NSArray *) getInstalledPackages {
4324 Database *database([Database sharedInstance]);
4325 @synchronized (database) {
4326 NSArray *packages([database packages]);
4327 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4328 for (Package *package in packages)
4329 if (![package uninstalled])
4330 [installed addObject:package];
4334 - (Package *) getPackageById:(NSString *)id {
4335 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4339 return (Package *) [NSNull null];
4342 - (NSString *) getLocaleIdentifier {
4343 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4346 - (NSArray *) getPreferredLanguages {
4350 - (NSArray *) statfs:(NSString *)path {
4353 if (path == nil || statfs([path UTF8String], &stat) == -1)
4356 return [NSArray arrayWithObjects:
4357 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4358 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4359 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4363 - (NSNumber *) du:(NSString *)path {
4364 NSNumber *value(nil);
4367 _assert(pipe(fds) != -1);
4369 pid_t pid(ExecFork());
4371 _assert(dup2(fds[1], 1) != -1);
4372 _assert(close(fds[0]) != -1);
4373 _assert(close(fds[1]) != -1);
4374 /* XXX: this should probably not use du */
4375 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4380 _assert(close(fds[1]) != -1);
4382 if (FILE *du = fdopen(fds[0], "r")) {
4384 while (fgets(line, sizeof(line), du) != NULL) {
4385 size_t length(strlen(line));
4386 while (length != 0 && line[length - 1] == '\n')
4387 line[--length] = '\0';
4388 if (char *tab = strchr(line, '\t')) {
4390 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4395 } else _assert(close(fds[0]));
4399 if (waitpid(pid, &status, 0) == -1)
4402 else _assert(false);
4408 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4411 - (void) installPackages:(NSArray *)packages {
4412 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4415 - (NSString *) substitutePackageNames:(NSString *)message {
4416 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4417 for (size_t i(0), e([words count]); i != e; ++i) {
4418 NSString *word([words objectAtIndex:i]);
4419 if (Package *package = [[Database sharedInstance] packageWithName:word])
4420 [words replaceObjectAtIndex:i withObject:[package name]];
4423 return [words componentsJoinedByString:@" "];
4426 - (void) removeButton {
4427 [indirect_ removeButton];
4430 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4431 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4434 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4435 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4438 - (void) setBadgeValue:(id)value {
4439 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4442 - (void) setAllowsNavigationAction:(NSString *)value {
4443 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4446 - (void) setHidesBackButton:(NSString *)value {
4447 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4450 - (void) setHidesNavigationBar:(NSString *)value {
4451 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4454 - (void) setNavigationBarStyle:(NSString *)value {
4455 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4458 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4459 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4460 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4461 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4464 - (void) setPasteboardString:(NSString *)value {
4465 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4468 - (void) setPasteboardURL:(NSString *)value {
4469 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4472 - (void) _setToken:(NSString *)token {
4476 [Metadata_ removeObjectForKey:@"Token"];
4478 [Metadata_ setObject:Token_ forKey:@"Token"];
4483 - (void) setToken:(NSString *)token {
4484 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4487 - (void) scrollToBottom:(NSNumber *)animated {
4488 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4491 - (void) setViewportWidth:(float)width {
4492 [indirect_ setViewportWidthOnMainThread:width];
4495 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4496 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4497 unsigned count([arguments count]);
4499 for (unsigned i(0); i != count; ++i)
4500 values[i] = [arguments objectAtIndex:i];
4501 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4504 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4505 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4507 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4509 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4515 /* @ Loading... Indicator {{{ */
4516 @interface CYLoadingIndicator : UIView {
4517 _H<UIActivityIndicatorView> spinner_;
4519 _H<UIView> container_;
4522 @property (readonly, nonatomic) UILabel *label;
4523 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4527 @implementation CYLoadingIndicator
4529 - (id) initWithFrame:(CGRect)frame {
4530 if ((self = [super initWithFrame:frame]) != nil) {
4531 container_ = [[[UIView alloc] init] autorelease];
4532 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4534 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4535 [spinner_ startAnimating];
4536 [container_ addSubview:spinner_];
4538 label_ = [[[UILabel alloc] init] autorelease];
4539 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4540 [label_ setBackgroundColor:[UIColor clearColor]];
4541 [label_ setTextColor:[UIColor blackColor]];
4542 [label_ setShadowColor:[UIColor whiteColor]];
4543 [label_ setShadowOffset:CGSizeMake(0, 1)];
4544 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4545 [container_ addSubview:label_];
4547 CGSize viewsize = frame.size;
4548 CGSize spinnersize = [spinner_ bounds].size;
4549 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4550 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4552 CGRect containrect = {
4553 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4554 CGSizeMake(bothwidth, spinnersize.height)
4557 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4565 [container_ setFrame:containrect];
4566 [spinner_ setFrame:spinrect];
4567 [label_ setFrame:textrect];
4568 [self addSubview:container_];
4572 - (UILabel *) label {
4576 - (UIActivityIndicatorView *) activityIndicatorView {
4582 /* Emulated Loading Controller {{{ */
4583 @interface CYEmulatedLoadingController : CYViewController {
4584 _transient Database *database_;
4585 _H<CYLoadingIndicator> indicator_;
4586 _H<UITabBar> tabbar_;
4587 _H<UINavigationBar> navbar_;
4592 @implementation CYEmulatedLoadingController
4594 - (id) initWithDatabase:(Database *)database {
4595 if ((self = [super init]) != nil) {
4596 database_ = database;
4601 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4603 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4604 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4605 [[self view] addSubview:table];
4607 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4608 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4609 [[self view] addSubview:indicator_];
4611 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4612 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4613 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4614 [[self view] addSubview:tabbar_];
4616 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4617 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4618 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4619 [[self view] addSubview:navbar_];
4622 - (void) releaseSubviews {
4631 /* Cydia Browser Controller {{{ */
4632 @implementation CYBrowserController
4639 - (NSURL *) navigationURL {
4640 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4643 + (void) initialize {
4644 Diversions_ = [[NSMutableSet alloc] initWithCapacity:0];
4647 + (void) addDiversion:(Diversion *)diversion {
4648 [Diversions_ addObject:diversion];
4651 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4652 [super webView:view didClearWindowObject:window forFrame:frame];
4654 WebDataSource *source([frame dataSource]);
4655 NSURLResponse *response([source response]);
4656 NSURL *url([response URL]);
4657 NSString *scheme([[url scheme] lowercaseString]);
4659 bool bridged(false);
4661 @synchronized (HostConfig_) {
4662 if ([scheme isEqualToString:@"file"])
4664 else if ([scheme isEqualToString:@"https"])
4665 if ([BridgedHosts_ containsObject:[url host]])
4670 [window setValue:cydia_ forKey:@"cydia"];
4673 - (NSURL *) URLWithURL:(NSURL *)url {
4674 return [Diversion divertURL:url];
4677 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4678 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4680 if (System_ != NULL)
4681 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4682 if (Machine_ != NULL)
4683 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4685 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4690 - (void) setDelegate:(id)delegate {
4691 [super setDelegate:delegate];
4692 [cydia_ setDelegate:delegate];
4696 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4697 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4699 WebView *webview([[webview_ _documentView] webView]);
4701 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4704 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4706 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4707 if (Product_ != nil)
4708 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4710 [webview setApplicationNameForUserAgent:application];
4718 @interface NSObject (CydiaScript)
4719 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4722 @implementation NSObject (CydiaScript)
4724 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4730 @implementation NSArray (CydiaScript)
4732 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4733 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4734 for (size_t i(0), e([self count]); i != e; ++i)
4735 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4741 @implementation NSDictionary (CydiaScript)
4743 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4744 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4746 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4753 /* Confirmation Controller {{{ */
4754 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4755 if (!iterator.end())
4756 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4757 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4759 pkgCache::PkgIterator package(dep.TargetPkg());
4762 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4769 @protocol ConfirmationControllerDelegate
4770 - (void) cancelAndClear:(bool)clear;
4771 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4775 @interface ConfirmationController : CYBrowserController {
4776 _transient Database *database_;
4778 UIAlertView *essential_;
4780 NSDictionary *changes_;
4781 NSMutableArray *issues_;
4782 NSDictionary *sizes_;
4787 - (id) initWithDatabase:(Database *)database;
4791 @implementation ConfirmationController
4798 if (essential_ != nil)
4799 [essential_ release];
4806 RestartSubstrate_ = true;
4807 [delegate_ confirmWithNavigationController:[self navigationController]];
4810 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4811 NSString *context([alert context]);
4813 if ([context isEqualToString:@"remove"]) {
4814 if (button == [alert cancelButtonIndex])
4815 [self dismissModalViewControllerAnimated:YES];
4816 else if (button == [alert firstOtherButtonIndex]) {
4820 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4821 } else if ([context isEqualToString:@"unable"]) {
4822 [self dismissModalViewControllerAnimated:YES];
4823 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4825 [super alertView:alert clickedButtonAtIndex:button];
4829 - (void) _doContinue {
4830 [self dismissModalViewControllerAnimated:YES];
4831 [delegate_ cancelAndClear:NO];
4834 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4835 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4839 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4840 [super webView:view didClearWindowObject:window forFrame:frame];
4842 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4843 changes_, @"changes",
4847 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4850 - (id) initWithDatabase:(Database *)database {
4851 if ((self = [super init]) != nil) {
4852 database_ = database;
4854 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4855 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4856 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4857 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4858 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4862 pkgCacheFile &cache([database_ cache]);
4863 NSArray *packages([database_ packages]);
4864 pkgDepCache::Policy *policy([database_ policy]);
4866 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4868 for (Package *package in packages) {
4869 pkgCache::PkgIterator iterator([package iterator]);
4870 NSString *name([package id]);
4872 if ([package broken]) {
4873 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4875 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4877 reasons, @"reasons",
4880 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4884 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4885 pkgCache::DepIterator start;
4886 pkgCache::DepIterator end;
4887 dep.GlobOr(start, end); // ++dep
4889 if (!cache->IsImportantDep(end))
4891 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4894 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4896 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4897 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4898 clauses, @"clauses",
4902 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4904 pkgCache::PkgIterator target(start.TargetPkg());
4905 if (target->ProvidesList != 0)
4906 reason = @"missing";
4908 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4910 reason = @"installed";
4911 installed = [NSString stringWithUTF8String:ver.VerStr()];
4912 } else if (!cache[target].CandidateVerIter(cache).end())
4913 reason = @"uninstalled";
4914 else if (target->ProvidesList == 0)
4915 reason = @"uninstallable";
4917 reason = @"virtual";
4920 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4921 [NSString stringWithUTF8String:start.CompType()], @"operator",
4922 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4925 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4926 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4927 version, @"version",
4929 installed, @"installed",
4932 // yes, seriously. (wtf?)
4940 pkgDepCache::StateCache &state(cache[iterator]);
4942 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4944 if (state.NewInstall())
4945 [installs addObject:name];
4946 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4947 [reinstalls addObject:name];
4948 else if (state.Upgrade())
4949 [upgrades addObject:name];
4950 else if (state.Downgrade())
4951 [downgrades addObject:name];
4952 else if (!state.Delete())
4954 else if (special_r(name))
4955 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4956 [NSNull null], @"package",
4957 [NSArray arrayWithObjects:
4958 [NSDictionary dictionaryWithObjectsAndKeys:
4959 @"Conflicts", @"relationship",
4960 [NSArray arrayWithObjects:
4961 [NSDictionary dictionaryWithObjectsAndKeys:
4963 [NSNull null], @"version",
4964 @"installed", @"reason",
4971 if ([package essential])
4973 [removes addObject:name];
4976 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4977 substrate_ |= DepSubstrate(iterator.CurrentVer());
4982 else if (Advanced_) {
4983 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4985 essential_ = [[UIAlertView alloc]
4986 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4987 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4989 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4991 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4995 [essential_ setContext:@"remove"];
4997 essential_ = [[UIAlertView alloc]
4998 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4999 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5001 cancelButtonTitle:UCLocalize("OKAY")
5002 otherButtonTitles:nil
5005 [essential_ setContext:@"unable"];
5008 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
5009 installs, @"installs",
5010 reinstalls, @"reinstalls",
5011 upgrades, @"upgrades",
5012 downgrades, @"downgrades",
5013 removes, @"removes",
5016 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
5017 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5018 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5021 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5023 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
5024 initWithTitle:UCLocalize("CANCEL")
5025 style:UIBarButtonItemStylePlain
5027 action:@selector(cancelButtonClicked)
5033 - (void) applyRightButton {
5034 if ([issues_ count] == 0 && ![self isLoading])
5035 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5036 initWithTitle:UCLocalize("CONFIRM")
5037 style:UIBarButtonItemStyleDone
5039 action:@selector(confirmButtonClicked)
5042 [[self navigationItem] setRightBarButtonItem:nil];
5046 - (void) cancelButtonClicked {
5047 [self dismissModalViewControllerAnimated:YES];
5048 [delegate_ cancelAndClear:YES];
5052 - (void) confirmButtonClicked {
5053 if (essential_ != nil)
5063 /* Progress Data {{{ */
5064 @interface CydiaProgressData : NSObject {
5065 _transient id delegate_;
5074 _H<NSMutableArray> events_;
5075 _H<NSString> title_;
5077 _H<NSString> status_;
5078 _H<NSString> finish_;
5083 @implementation CydiaProgressData
5085 + (NSArray *) _attributeKeys {
5086 return [NSArray arrayWithObjects:
5098 - (NSArray *) attributeKeys {
5099 return [[self class] _attributeKeys];
5102 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5103 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5107 if ((self = [super init]) != nil) {
5108 events_ = [NSMutableArray arrayWithCapacity:32];
5112 - (void) setDelegate:(id)delegate {
5113 delegate_ = delegate;
5116 - (void) setPercent:(float)value {
5120 - (NSNumber *) percent {
5121 return [NSNumber numberWithFloat:percent_];
5124 - (void) setCurrent:(float)value {
5128 - (NSNumber *) current {
5129 return [NSNumber numberWithFloat:current_];
5132 - (void) setTotal:(float)value {
5136 - (NSNumber *) total {
5137 return [NSNumber numberWithFloat:total_];
5140 - (void) setSpeed:(float)value {
5144 - (NSNumber *) speed {
5145 return [NSNumber numberWithFloat:speed_];
5148 - (NSArray *) events {
5152 - (void) removeAllEvents {
5153 [events_ removeAllObjects];
5156 - (void) addEvent:(CydiaProgressEvent *)event {
5157 [events_ addObject:event];
5160 - (void) setTitle:(NSString *)text {
5164 - (NSString *) title {
5168 - (void) setFinish:(NSString *)text {
5172 - (NSString *) finish {
5173 return (id) finish_ ?: [NSNull null];
5176 - (void) setRunning:(bool)running {
5180 - (NSNumber *) running {
5181 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5186 /* Progress Controller {{{ */
5187 @interface ProgressController : CYBrowserController <
5190 _transient Database *database_;
5191 _H<CydiaProgressData> progress_;
5195 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5197 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5199 - (void) setTitle:(NSString *)title;
5200 - (void) setCancellable:(bool)cancellable;
5204 @implementation ProgressController
5207 [database_ setProgressDelegate:nil];
5208 [progress_ setDelegate:nil];
5212 - (void) updateCancel {
5213 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5214 initWithTitle:UCLocalize("CANCEL")
5215 style:UIBarButtonItemStylePlain
5217 action:@selector(cancel)
5218 ] autorelease] : nil)];
5221 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5222 if ((self = [super init]) != nil) {
5223 database_ = database;
5224 delegate_ = delegate;
5226 [database_ setProgressDelegate:self];
5228 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5229 [progress_ setDelegate:self];
5231 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5233 [scroller_ setBackgroundColor:[UIColor blackColor]];
5235 [[self navigationItem] setHidesBackButton:YES];
5237 [self updateCancel];
5241 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5242 [super webView:view didClearWindowObject:window forFrame:frame];
5243 [window setValue:progress_ forKey:@"cydiaProgress"];
5246 - (void) updateProgress {
5247 [self dispatchEvent:@"CydiaProgressUpdate"];
5250 - (void) viewWillAppear:(BOOL)animated {
5251 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5252 [super viewWillAppear:animated];
5256 UpdateExternalStatus(0);
5263 [delegate_ terminateWithSuccess];
5264 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5265 [delegate_ suspendWithAnimation:YES];
5267 [delegate_ suspend];*/
5279 system("/usr/bin/sbreload");
5285 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5286 SBReboot(SBSSpringBoardServerPort());
5288 reboot2(RB_AUTOBOOT);
5295 - (void) setTitle:(NSString *)title {
5296 [progress_ setTitle:title];
5297 [self updateProgress];
5300 - (UIBarButtonItem *) rightButton {
5301 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5302 initWithTitle:UCLocalize("CLOSE")
5303 style:UIBarButtonItemStylePlain
5305 action:@selector(close)
5309 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5310 UpdateExternalStatus(1);
5312 [progress_ setRunning:true];
5313 [self setTitle:title];
5314 // implicit updateProgress
5316 SHA1SumValue notifyconf; {
5318 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5321 MMap mmap(file, MMap::ReadOnly);
5323 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5324 notifyconf = sha1.Result();
5328 SHA1SumValue springlist; {
5330 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5333 MMap mmap(file, MMap::ReadOnly);
5335 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5336 springlist = sha1.Result();
5340 if (invocation != nil) {
5341 [invocation yieldToSelector:@selector(invoke)];
5342 [self setTitle:@"COMPLETE"];
5347 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5350 MMap mmap(file, MMap::ReadOnly);
5352 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5353 if (!(notifyconf == sha1.Result()))
5360 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5363 MMap mmap(file, MMap::ReadOnly);
5365 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5366 if (!(springlist == sha1.Result()))
5372 if (RestartSubstrate_)
5376 RestartSubstrate_ = false;
5379 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5380 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5381 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5382 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5383 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5387 system("su -c /usr/bin/uicache mobile");
5390 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5392 [progress_ setRunning:false];
5393 [self updateProgress];
5395 [self applyRightButton];
5398 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5399 [progress_ addEvent:event];
5400 [self updateProgress];
5403 - (bool) isProgressCancelled {
5404 return cancel_ == 2;
5409 [self updateCancel];
5412 - (void) setCancellable:(bool)cancellable {
5413 unsigned cancel(cancel_);
5417 else if (cancel_ == 0)
5420 if (cancel != cancel_)
5421 [self updateCancel];
5424 - (void) setProgressCancellable:(NSNumber *)cancellable {
5425 [self setCancellable:[cancellable boolValue]];
5428 - (void) setProgressPercent:(NSNumber *)percent {
5429 [progress_ setPercent:[percent floatValue]];
5430 [self updateProgress];
5433 - (void) setProgressStatus:(NSDictionary *)status {
5434 if (status == nil) {
5435 [progress_ setCurrent:0];
5436 [progress_ setTotal:0];
5437 [progress_ setSpeed:0];
5439 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5441 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5442 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5443 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5446 [self updateProgress];
5452 /* Cell Content View {{{ */
5453 @protocol ContentDelegate
5454 - (void) drawContentRect:(CGRect)rect;
5457 @interface ContentView : UIView {
5458 _transient id<ContentDelegate> delegate_;
5463 @implementation ContentView
5465 - (id) initWithFrame:(CGRect)frame {
5466 if ((self = [super initWithFrame:frame]) != nil) {
5467 [self setNeedsDisplayOnBoundsChange:YES];
5471 - (void) setDelegate:(id<ContentDelegate>)delegate {
5472 delegate_ = delegate;
5475 - (void) drawRect:(CGRect)rect {
5476 [super drawRect:rect];
5477 [delegate_ drawContentRect:rect];
5482 /* Cydia TableView Cell {{{ */
5483 @interface CYTableViewCell : UITableViewCell {
5484 ContentView *content_;
5490 @implementation CYTableViewCell
5497 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5498 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5500 if (view == content_) {
5501 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5502 highlighted_ = highlighted;
5505 [super _updateHighlightColorsForView:view highlighted:highlighted];
5508 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5509 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5510 highlighted_ = selected;
5512 [super setSelected:selected animated:animated];
5513 [content_ setNeedsDisplay];
5519 /* Package Cell {{{ */
5520 @interface PackageCell : CYTableViewCell <
5525 NSString *description_;
5533 - (PackageCell *) init;
5534 - (void) setPackage:(Package *)package;
5536 - (void) drawContentRect:(CGRect)rect;
5540 @implementation PackageCell
5542 - (void) clearPackage {
5553 if (description_ != nil) {
5554 [description_ release];
5558 if (source_ != nil) {
5563 if (badge_ != nil) {
5568 if (placard_ != nil) {
5578 [self clearPackage];
5582 - (PackageCell *) init {
5583 CGRect frame(CGRectMake(0, 0, 320, 74));
5584 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5585 UIView *content([self contentView]);
5586 CGRect bounds([content bounds]);
5588 content_ = [[ContentView alloc] initWithFrame:bounds];
5589 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5590 [content addSubview:content_];
5592 [content_ setDelegate:self];
5593 [content_ setOpaque:YES];
5597 - (NSString *) accessibilityLabel {
5598 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5601 - (void) setPackage:(Package *)package {
5602 [self clearPackage];
5605 Source *source = [package source];
5607 icon_ = [[package icon] retain];
5608 name_ = [[package name] retain];
5611 description_ = [package longDescription];
5612 if (description_ == nil)
5613 description_ = [package shortDescription];
5614 if (description_ != nil)
5615 description_ = [description_ retain];
5617 commercial_ = [package isCommercial];
5619 package_ = [package retain];
5621 NSString *label = nil;
5622 bool trusted = false;
5624 if (source != nil) {
5625 label = [source label];
5626 trusted = [source trusted];
5627 } else if ([[package id] isEqualToString:@"firmware"])
5628 label = UCLocalize("APPLE");
5630 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5632 NSString *from(label);
5634 NSString *section = [package simpleSection];
5635 if (section != nil && ![section isEqualToString:label]) {
5636 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5637 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5640 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5641 source_ = [from retain];
5643 if (NSString *purpose = [package primaryPurpose])
5644 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5645 badge_ = [badge_ retain];
5650 if (NSString *mode = [package_ mode]) {
5651 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5652 color = RemovingColor_;
5653 //placard = @"removing";
5655 color = InstallingColor_;
5656 //placard = @"installing";
5659 // XXX: the removing/installing placards are not @2x
5662 color = [UIColor whiteColor];
5664 if ([package installed] != nil)
5665 placard = @"installed";
5670 [content_ setBackgroundColor:color];
5673 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5674 placard_ = [placard_ retain];
5676 [self setNeedsDisplay];
5677 [content_ setNeedsDisplay];
5680 - (void) drawContentRect:(CGRect)rect {
5681 bool highlighted(highlighted_);
5682 float width([self bounds].size.width);
5685 CGContextRef context(UIGraphicsGetCurrentContext());
5686 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5687 CGContextFillRect(context, rect);
5692 rect.size = [icon_ size];
5694 rect.size.width /= 2;
5695 rect.size.height /= 2;
5697 rect.origin.x = 25 - rect.size.width / 2;
5698 rect.origin.y = 25 - rect.size.height / 2;
5700 [icon_ drawInRect:rect];
5703 if (badge_ != nil) {
5705 rect.size = [badge_ size];
5707 rect.size.width /= 2;
5708 rect.size.height /= 2;
5710 rect.origin.x = 36 - rect.size.width / 2;
5711 rect.origin.y = 36 - rect.size.height / 2;
5713 [badge_ drawInRect:rect];
5720 UISetColor(commercial_ ? Purple_ : Black_);
5721 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5722 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5725 UISetColor(commercial_ ? Purplish_ : Gray_);
5726 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5728 if (placard_ != nil)
5729 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5734 /* Section Cell {{{ */
5735 @interface SectionCell : CYTableViewCell <
5747 - (void) setSection:(Section *)section editing:(BOOL)editing;
5751 @implementation SectionCell
5753 - (void) clearSection {
5754 if (basic_ != nil) {
5759 if (section_ != nil) {
5769 if (count_ != nil) {
5776 [self clearSection];
5782 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5783 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5784 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5785 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5786 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5788 UIView *content([self contentView]);
5789 CGRect bounds([content bounds]);
5791 content_ = [[ContentView alloc] initWithFrame:bounds];
5792 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5793 [content addSubview:content_];
5794 [content_ setBackgroundColor:[UIColor whiteColor]];
5796 [content_ setDelegate:self];
5800 - (void) onSwitch:(id)sender {
5801 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5802 if (metadata == nil) {
5803 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5804 [Sections_ setObject:metadata forKey:basic_];
5807 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5811 - (void) setSection:(Section *)section editing:(BOOL)editing {
5812 if (editing != editing_) {
5814 [switch_ removeFromSuperview];
5816 [self addSubview:switch_];
5820 [self clearSection];
5822 if (section == nil) {
5823 name_ = [UCLocalize("ALL_PACKAGES") retain];
5826 basic_ = [section name];
5828 basic_ = [basic_ retain];
5830 section_ = [section localized];
5831 if (section_ != nil)
5832 section_ = [section_ retain];
5834 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5835 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5838 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5841 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5842 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5844 [content_ setNeedsDisplay];
5847 - (void) setFrame:(CGRect)frame {
5848 [super setFrame:frame];
5850 CGRect rect([switch_ frame]);
5851 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5854 - (NSString *) accessibilityLabel {
5858 - (void) drawContentRect:(CGRect)rect {
5859 bool highlighted(highlighted_ && !editing_);
5861 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5866 float width(rect.size.width);
5872 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5874 CGSize size = [count_ sizeWithFont:Font14_];
5878 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5884 /* File Table {{{ */
5885 @interface FileTable : CYViewController <
5886 UITableViewDataSource,
5889 _transient Database *database_;
5892 NSMutableArray *files_;
5896 - (id) initWithDatabase:(Database *)database;
5897 - (void) setPackage:(Package *)package;
5901 @implementation FileTable
5904 [self releaseSubviews];
5913 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5914 return files_ == nil ? 0 : [files_ count];
5917 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5921 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5922 static NSString *reuseIdentifier = @"Cell";
5924 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5926 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5927 [cell setFont:[UIFont systemFontOfSize:16]];
5929 [cell setText:[files_ objectAtIndex:indexPath.row]];
5930 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5935 - (NSURL *) navigationURL {
5936 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5940 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5942 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5943 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5944 [list_ setRowHeight:24.0f];
5945 [list_ setDataSource:self];
5946 [list_ setDelegate:self];
5947 [[self view] addSubview:list_];
5950 - (void) viewDidLoad {
5951 [super viewDidLoad];
5953 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5956 - (void) releaseSubviews {
5961 - (id) initWithDatabase:(Database *)database {
5962 if ((self = [super init]) != nil) {
5963 database_ = database;
5965 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5969 - (void) setPackage:(Package *)package {
5970 if (package_ != nil) {
5971 [package_ autorelease];
5980 [files_ removeAllObjects];
5982 if (package != nil) {
5983 package_ = [package retain];
5984 name_ = [[package id] retain];
5986 if (NSArray *files = [package files])
5987 [files_ addObjectsFromArray:files];
5989 if ([files_ count] != 0) {
5990 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5991 [files_ removeObjectAtIndex:0];
5992 [files_ sortUsingSelector:@selector(compareByPath:)];
5994 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5995 [stack addObject:@"/"];
5997 for (int i(0), e([files_ count]); i != e; ++i) {
5998 NSString *file = [files_ objectAtIndex:i];
5999 while (![file hasPrefix:[stack lastObject]])
6000 [stack removeLastObject];
6001 NSString *directory = [stack lastObject];
6002 [stack addObject:[file stringByAppendingString:@"/"]];
6003 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6004 ([stack count] - 2) * 3, "",
6005 [file substringFromIndex:[directory length]]
6014 - (void) reloadData {
6017 [self setPackage:[database_ packageWithName:name_]];
6022 /* Package Controller {{{ */
6023 @interface CYPackageController : CYBrowserController <
6024 UIActionSheetDelegate
6026 _transient Database *database_;
6027 _H<Package> package_;
6030 _H<NSMutableArray> buttons_;
6031 _H<UIBarButtonItem> button_;
6034 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
6038 @implementation CYPackageController
6040 - (NSURL *) navigationURL {
6041 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6044 /* XXX: this is not safe at all... localization of /fail/ */
6045 - (void) _clickButtonWithName:(NSString *)name {
6046 if ([name isEqualToString:UCLocalize("CLEAR")])
6047 [delegate_ clearPackage:package_];
6048 else if ([name isEqualToString:UCLocalize("INSTALL")])
6049 [delegate_ installPackage:package_];
6050 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6051 [delegate_ installPackage:package_];
6052 else if ([name isEqualToString:UCLocalize("REMOVE")])
6053 [delegate_ removePackage:package_];
6054 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6055 [delegate_ installPackage:package_];
6056 else _assert(false);
6059 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6060 NSString *context([sheet context]);
6062 if ([context isEqualToString:@"modify"]) {
6063 if (button != [sheet cancelButtonIndex]) {
6064 NSString *buttonName = [buttons_ objectAtIndex:button];
6065 [self _clickButtonWithName:buttonName];
6068 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6072 - (bool) _allowJavaScriptPanel {
6077 - (void) _customButtonClicked {
6078 int count([buttons_ count]);
6083 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6085 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6086 [buttons addObjectsFromArray:buttons_];
6088 UIActionSheet *sheet = [[[UIActionSheet alloc]
6091 cancelButtonTitle:nil
6092 destructiveButtonTitle:nil
6093 otherButtonTitles:nil
6096 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6098 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6099 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6101 [sheet setContext:@"modify"];
6103 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6107 // We don't want to allow non-commercial packages to do custom things to the install button,
6108 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6109 - (void) customButtonClicked {
6111 [super customButtonClicked];
6113 [self _customButtonClicked];
6116 - (void) reloadButtonClicked {
6117 // Don't reload a commerical package by tapping the loading button,
6118 // but if it's not an Install button, we should forward it on.
6119 if (![package_ uninstalled])
6120 [self _customButtonClicked];
6123 - (void) applyLoadingTitle {
6124 // Don't show "Loading" as the title. Ever.
6127 - (UIBarButtonItem *) rightButton {
6132 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
6133 if ((self = [super init]) != nil) {
6134 database_ = database;
6135 buttons_ = [NSMutableArray arrayWithCapacity:4];
6136 name_ = [NSString stringWithString:name];
6137 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
6141 - (void) reloadData {
6144 package_ = [database_ packageWithName:name_];
6146 [buttons_ removeAllObjects];
6148 if (package_ != nil) {
6149 [(Package *) package_ parse];
6151 commercial_ = [package_ isCommercial];
6153 if ([package_ mode] != nil)
6154 [buttons_ addObject:UCLocalize("CLEAR")];
6155 if ([package_ source] == nil);
6156 else if ([package_ upgradableAndEssential:NO])
6157 [buttons_ addObject:UCLocalize("UPGRADE")];
6158 else if ([package_ uninstalled])
6159 [buttons_ addObject:UCLocalize("INSTALL")];
6161 [buttons_ addObject:UCLocalize("REINSTALL")];
6162 if (![package_ uninstalled])
6163 [buttons_ addObject:UCLocalize("REMOVE")];
6167 switch ([buttons_ count]) {
6168 case 0: title = nil; break;
6169 case 1: title = [buttons_ objectAtIndex:0]; break;
6170 default: title = UCLocalize("MODIFY"); break;
6173 button_ = [[[UIBarButtonItem alloc]
6175 style:UIBarButtonItemStylePlain
6177 action:@selector(customButtonClicked)
6181 - (bool) isLoading {
6182 return commercial_ ? [super isLoading] : false;
6188 /* Package List Controller {{{ */
6189 @interface PackageListController : CYViewController <
6190 UITableViewDataSource,
6193 _transient Database *database_;
6195 NSMutableArray *packages_;
6196 NSMutableArray *sections_;
6198 NSMutableArray *index_;
6199 NSMutableDictionary *indices_;
6203 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6204 - (void) setDelegate:(id)delegate;
6205 - (void) resetCursor;
6209 @implementation PackageListController
6212 [packages_ release];
6213 [sections_ release];
6222 - (void) deselectWithAnimation:(BOOL)animated {
6223 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6226 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6227 CGRect base = [[self view] bounds];
6228 base.size.height -= bounds.size.height;
6229 base.origin = [list_ frame].origin;
6231 [UIView beginAnimations:nil context:NULL];
6232 [UIView setAnimationBeginsFromCurrentState:YES];
6233 [UIView setAnimationCurve:curve];
6234 [UIView setAnimationDuration:duration];
6235 [list_ setFrame:base];
6236 [UIView commitAnimations];
6239 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6240 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6243 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6244 [self resizeForKeyboardBounds:bounds duration:0];
6247 - (void) keyboardWillShow:(NSNotification *)notification {
6250 NSTimeInterval duration;
6251 UIViewAnimationCurve curve;
6252 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6253 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6254 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6255 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6257 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);
6258 UIViewController *base = self;
6259 while ([base parentViewController] != nil)
6260 base = [base parentViewController];
6261 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6262 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6264 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6267 - (void) keyboardWillHide:(NSNotification *)notification {
6268 NSTimeInterval duration;
6269 UIViewAnimationCurve curve;
6270 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6271 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6273 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6276 - (void) viewWillAppear:(BOOL)animated {
6277 [super viewWillAppear:animated];
6279 [self resizeForKeyboardBounds:CGRectZero];
6280 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6281 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6284 - (void) viewWillDisappear:(BOOL)animated {
6285 [super viewWillDisappear:animated];
6287 [self resizeForKeyboardBounds:CGRectZero];
6288 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6289 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6292 - (void) viewDidAppear:(BOOL)animated {
6293 [super viewDidAppear:animated];
6294 [self deselectWithAnimation:animated];
6297 - (void) didSelectPackage:(Package *)package {
6298 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6299 [view setDelegate:delegate_];
6300 [[self navigationController] pushViewController:view animated:YES];
6303 #if TryIndexedCollation
6304 + (BOOL) hasIndexedCollation {
6305 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6309 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6310 NSInteger count([sections_ count]);
6311 return count == 0 ? 1 : count;
6314 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6315 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6317 return [[sections_ objectAtIndex:section] name];
6320 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6321 if ([sections_ count] == 0)
6323 return [[sections_ objectAtIndex:section] count];
6326 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6327 @synchronized (database_) {
6328 if ([database_ era] != era_)
6331 Section *section([sections_ objectAtIndex:[path section]]);
6332 NSInteger row([path row]);
6333 Package *package([packages_ objectAtIndex:([section row] + row)]);
6334 return [[package retain] autorelease];
6337 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6338 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6340 cell = [[[PackageCell alloc] init] autorelease];
6341 [cell setPackage:[self packageAtIndexPath:path]];
6345 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6346 Package *package([self packageAtIndexPath:path]);
6347 package = [database_ packageWithName:[package id]];
6348 [self didSelectPackage:package];
6351 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6352 // XXX: is 20 the most optimal number here?
6353 return [packages_ count] > 20 ? index_ : nil;
6356 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6357 #if TryIndexedCollation
6358 if ([[self class] hasIndexedCollation]) {
6359 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6366 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6367 if ((self = [super init]) != nil) {
6368 database_ = database;
6369 title_ = [title copy];
6370 [[self navigationItem] setTitle:title_];
6372 #if TryIndexedCollation
6373 if ([[self class] hasIndexedCollation])
6374 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6377 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6379 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6381 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6382 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6384 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6385 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6386 [list_ setRowHeight:73];
6387 [[self view] addSubview:list_];
6389 [list_ setDataSource:self];
6390 [list_ setDelegate:self];
6394 - (void) setDelegate:(id)delegate {
6395 delegate_ = delegate;
6398 - (bool) hasPackage:(Package *)package {
6402 - (void) reloadData {
6405 era_ = [database_ era];
6406 NSArray *packages = [database_ packages];
6408 [packages_ removeAllObjects];
6409 [sections_ removeAllObjects];
6411 _profile(PackageTable$reloadData$Filter)
6412 for (Package *package in packages)
6413 if ([self hasPackage:package])
6414 [packages_ addObject:package];
6417 [indices_ removeAllObjects];
6419 Section *section = nil;
6421 #if TryIndexedCollation
6422 if ([[self class] hasIndexedCollation]) {
6423 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6424 NSArray *titles = [collation sectionIndexTitles];
6427 _profile(PackageTable$reloadData$Section)
6428 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6432 _profile(PackageTable$reloadData$Section$Package)
6433 package = [packages_ objectAtIndex:offset];
6434 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6437 while (secidx < index) {
6440 _profile(PackageTable$reloadData$Section$Allocate)
6441 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6444 _profile(PackageTable$reloadData$Section$Add)
6445 [sections_ addObject:section];
6449 [section addToCount];
6455 [index_ removeAllObjects];
6457 _profile(PackageTable$reloadData$Section)
6458 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6462 _profile(PackageTable$reloadData$Section$Package)
6463 package = [packages_ objectAtIndex:offset];
6464 index = [package index];
6467 if (section == nil || [section index] != index) {
6468 _profile(PackageTable$reloadData$Section$Allocate)
6469 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6472 [index_ addObject:[section name]];
6473 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6475 _profile(PackageTable$reloadData$Section$Add)
6476 [sections_ addObject:section];
6480 [section addToCount];
6485 _profile(PackageTable$reloadData$List)
6490 - (void) resetCursor {
6491 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6496 /* Filtered Package List Controller {{{ */
6497 @interface FilteredPackageListController : PackageListController {
6503 - (void) setObject:(id)object;
6504 - (void) setObject:(id)object forFilter:(SEL)filter;
6506 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6510 @implementation FilteredPackageListController
6518 - (void) setFilter:(SEL)filter {
6521 /* XXX: this is an unsafe optimization of doomy hell */
6522 Method method(class_getInstanceMethod([Package class], filter));
6523 _assert(method != NULL);
6524 imp_ = method_getImplementation(method);
6525 _assert(imp_ != NULL);
6528 - (void) setObject:(id)object {
6534 object_ = [object retain];
6537 - (void) setObject:(id)object forFilter:(SEL)filter {
6538 [self setFilter:filter];
6539 [self setObject:object];
6542 - (bool) hasPackage:(Package *)package {
6543 _profile(FilteredPackageTable$hasPackage)
6544 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6548 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6549 if ((self = [super initWithDatabase:database title:title]) != nil) {
6550 [self setFilter:filter];
6551 [self setObject:object];
6558 /* Home Controller {{{ */
6559 @interface HomeController : CYBrowserController {
6564 @implementation HomeController
6567 if ((self = [super init]) != nil) {
6568 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6573 - (NSURL *) navigationURL {
6574 return [NSURL URLWithString:@"cydia://home"];
6577 - (void) aboutButtonClicked {
6578 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6580 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6581 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6582 [alert setCancelButtonIndex:0];
6585 @"Copyright (C) 2008-2011\n"
6586 "Jay Freeman (saurik)\n"
6587 "saurik@saurik.com\n"
6588 "http://www.saurik.com/"
6594 - (void) viewDidLoad {
6595 [super viewDidLoad];
6597 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6598 initWithTitle:UCLocalize("ABOUT")
6599 style:UIBarButtonItemStylePlain
6601 action:@selector(aboutButtonClicked)
6605 - (void) unloadData {
6612 /* Manage Controller {{{ */
6613 @interface ManageController : CYBrowserController {
6616 - (void) queueStatusDidChange;
6620 @implementation ManageController
6623 if ((self = [super init]) != nil) {
6624 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6628 - (NSURL *) navigationURL {
6629 return [NSURL URLWithString:@"cydia://manage"];
6632 - (void) viewDidLoad {
6633 [super viewDidLoad];
6635 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6636 initWithTitle:UCLocalize("SETTINGS")
6637 style:UIBarButtonItemStylePlain
6639 action:@selector(settingsButtonClicked)
6642 [self queueStatusDidChange];
6645 - (void) settingsButtonClicked {
6646 [delegate_ showSettings];
6650 - (void) queueButtonClicked {
6654 - (void) applyLoadingTitle {
6655 // Disable "Loading" title.
6658 - (void) applyRightButton {
6659 // Disable right button.
6663 - (void) queueStatusDidChange {
6665 if (!IsWildcat_ && Queuing_) {
6666 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6667 initWithTitle:UCLocalize("QUEUE")
6668 style:UIBarButtonItemStyleDone
6670 action:@selector(queueButtonClicked)
6673 [[self navigationItem] setRightBarButtonItem:nil];
6678 - (bool) isLoading {
6679 // Never show as loading.
6686 /* Refresh Bar {{{ */
6687 @interface RefreshBar : UINavigationBar {
6688 UIProgressIndicator *indicator_;
6689 UITextLabel *prompt_;
6690 UIProgressBar *progress_;
6691 UINavigationButton *cancel_;
6696 @implementation RefreshBar
6699 [indicator_ release];
6701 [progress_ release];
6706 - (void) positionViews {
6707 CGRect frame = [cancel_ frame];
6708 frame.size = [cancel_ sizeThatFits:frame.size];
6709 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6710 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6711 [cancel_ setFrame:frame];
6713 CGSize prgsize = {75, 100};
6715 [self frame].size.width - prgsize.width - 10,
6716 ([self frame].size.height - prgsize.height) / 2
6718 [progress_ setFrame:prgrect];
6720 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6721 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6722 CGRect indrect = {{indoffset, indoffset}, indsize};
6723 [indicator_ setFrame:indrect];
6725 CGSize prmsize = {215, indsize.height + 4};
6727 indoffset * 2 + indsize.width,
6728 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6730 [prompt_ setFrame:prmrect];
6733 - (void) setFrame:(CGRect)frame {
6734 [super setFrame:frame];
6735 [self positionViews];
6738 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6739 if ((self = [super initWithFrame:frame]) != nil) {
6740 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6742 [self setBarStyle:UIBarStyleBlack];
6744 UIBarStyle barstyle([self _barStyle:NO]);
6745 bool ugly(barstyle == UIBarStyleDefault);
6747 UIProgressIndicatorStyle style = ugly ?
6748 UIProgressIndicatorStyleMediumBrown :
6749 UIProgressIndicatorStyleMediumWhite;
6751 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6752 [indicator_ setStyle:style];
6753 [indicator_ startAnimation];
6754 [self addSubview:indicator_];
6756 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6757 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6758 [prompt_ setBackgroundColor:[UIColor clearColor]];
6759 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6760 [self addSubview:prompt_];
6762 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6763 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6764 [progress_ setStyle:0];
6765 [self addSubview:progress_];
6767 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6768 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6769 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6770 [cancel_ setBarStyle:barstyle];
6772 [self positionViews];
6776 - (void) setCancellable:(bool)cancellable {
6778 [self addSubview:cancel_];
6780 [cancel_ removeFromSuperview];
6784 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6785 [progress_ setProgress:0];
6789 [self setCancellable:NO];
6792 - (void) setPrompt:(NSString *)prompt {
6793 [prompt_ setText:prompt];
6796 - (void) setProgress:(float)progress {
6797 [progress_ setProgress:progress];
6803 /* Cydia Navigation Controller Interface {{{ */
6804 @interface UINavigationController (Cydia)
6806 - (NSArray *) navigationURLCollection;
6807 - (void) unloadData;
6812 /* Cydia Tab Bar Controller {{{ */
6813 @interface CYTabBarController : UITabBarController <
6814 UITabBarControllerDelegate,
6817 _transient Database *database_;
6818 RefreshBar *refreshbar_;
6822 // XXX: ok, "updatedelegate_"?...
6823 _transient NSObject<CydiaDelegate> *updatedelegate_;
6826 UIViewController *remembered_;
6827 _transient UIViewController *transient_;
6830 - (NSArray *) navigationURLCollection;
6831 - (void) dropBar:(BOOL)animated;
6832 - (void) beginUpdate;
6833 - (void) raiseBar:(BOOL)animated;
6835 - (void) unloadData;
6839 @implementation CYTabBarController
6841 - (void) setUnselectedViewController:(UIViewController *)transient {
6842 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6843 if (transient != nil) {
6844 if (transient_ == nil)
6845 remembered_ = [[controllers objectAtIndex:0] retain];
6846 transient_ = transient;
6847 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6848 [controllers replaceObjectAtIndex:0 withObject:transient_];
6849 [self setSelectedIndex:0];
6850 [self setViewControllers:controllers];
6851 [self concealTabBarSelection];
6852 } else if (remembered_ != nil) {
6853 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6854 transient_ = transient;
6855 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6856 [remembered_ release];
6858 [self setViewControllers:controllers];
6859 [self revealTabBarSelection];
6863 - (UIViewController *) unselectedViewController {
6867 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6868 if ([self unselectedViewController])
6869 [self setUnselectedViewController:nil];
6872 - (NSArray *) navigationURLCollection {
6873 NSMutableArray *items([NSMutableArray array]);
6875 // XXX: Should this deal with transient view controllers?
6876 for (id navigation in [self viewControllers]) {
6877 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6879 [items addObject:stack];
6885 - (void) unloadData {
6886 UIViewController *selected([self selectedViewController]);
6887 for (UINavigationController *controller in [self viewControllers])
6888 [controller unloadData];
6890 [selected reloadData];
6892 if (UIViewController *unselected = [self unselectedViewController])
6893 [unselected reloadData];
6899 [refreshbar_ release];
6900 [[NSNotificationCenter defaultCenter] removeObserver:self];
6905 - (id) initWithDatabase:(Database *)database {
6906 if ((self = [super init]) != nil) {
6907 database_ = database;
6908 [self setDelegate:self];
6910 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6911 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6913 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6917 - (void) setUpdate:(NSDate *)date {
6921 - (void) beginUpdate {
6922 [refreshbar_ start];
6925 [updatedelegate_ retainNetworkActivityIndicator];
6929 detachNewThreadSelector:@selector(performUpdate)
6935 - (void) performUpdate { _pooled
6937 status.setDelegate(self);
6938 [database_ updateWithStatus:status];
6941 performSelectorOnMainThread:@selector(completeUpdate)
6947 - (void) stopUpdateWithSelector:(SEL)selector {
6949 [updatedelegate_ releaseNetworkActivityIndicator];
6951 [self raiseBar:YES];
6954 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6957 - (void) completeUpdate {
6960 [self stopUpdateWithSelector:@selector(reloadData)];
6963 - (void) cancelUpdate {
6964 [self stopUpdateWithSelector:@selector(updateData)];
6967 - (void) cancelPressed {
6968 [self cancelUpdate];
6975 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6976 [refreshbar_ setPrompt:[event compoundMessage]];
6979 - (bool) isProgressCancelled {
6983 - (void) setProgressCancellable:(NSNumber *)cancellable {
6984 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6987 - (void) setProgressPercent:(NSNumber *)percent {
6988 [refreshbar_ setProgress:[percent floatValue]];
6991 - (void) setProgressStatus:(NSDictionary *)status {
6993 [self setProgressPercent:[status objectForKey:@"Percent"]];
6996 - (void) setUpdateDelegate:(id)delegate {
6997 updatedelegate_ = delegate;
7000 - (CGFloat) statusBarHeight {
7001 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7002 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7004 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7008 - (UIView *) transitionView {
7009 if ([self respondsToSelector:@selector(_transitionView)])
7010 return [self _transitionView];
7012 return MSHookIvar<id>(self, "_viewControllerTransitionView");
7015 - (void) dropBar:(BOOL)animated {
7020 UIView *transition([self transitionView]);
7021 [[self view] addSubview:refreshbar_];
7023 CGRect barframe([refreshbar_ frame]);
7025 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7026 barframe.origin.y = [self statusBarHeight];
7028 barframe.origin.y = 0;
7030 [refreshbar_ setFrame:barframe];
7033 [UIView beginAnimations:nil context:NULL];
7035 CGRect viewframe = [transition frame];
7036 viewframe.origin.y += barframe.size.height;
7037 viewframe.size.height -= barframe.size.height;
7038 [transition setFrame:viewframe];
7041 [UIView commitAnimations];
7043 // Ensure bar has the proper width for our view, it might have changed
7044 barframe.size.width = viewframe.size.width;
7045 [refreshbar_ setFrame:barframe];
7047 // XXX: fix Apple's layout bug
7048 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7051 - (void) raiseBar:(BOOL)animated {
7056 UIView *transition([self transitionView]);
7057 [refreshbar_ removeFromSuperview];
7059 CGRect barframe([refreshbar_ frame]);
7062 [UIView beginAnimations:nil context:NULL];
7064 CGRect viewframe = [transition frame];
7065 viewframe.origin.y -= barframe.size.height;
7066 viewframe.size.height += barframe.size.height;
7067 [transition setFrame:viewframe];
7070 [UIView commitAnimations];
7072 // XXX: fix Apple's layout bug
7073 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7077 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7078 // XXX: fix Apple's layout bug
7079 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7083 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7084 bool dropped(dropped_);
7089 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7094 // XXX: fix Apple's layout bug
7095 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7098 - (void) statusBarFrameChanged:(NSNotification *)notification {
7108 /* Cydia Navigation Controller Implementation {{{ */
7109 @implementation UINavigationController (Cydia)
7111 - (NSArray *) navigationURLCollection {
7112 NSMutableArray *stack([NSMutableArray array]);
7114 for (CYViewController *controller in [self viewControllers]) {
7115 NSString *url = [[controller navigationURL] absoluteString];
7117 [stack addObject:url];
7123 - (void) reloadData {
7126 if (UIViewController *visible = [self visibleViewController])
7127 [visible reloadData];
7130 - (void) unloadData {
7131 for (CYViewController *page in [self viewControllers])
7140 /* Cydia:// Protocol {{{ */
7141 @interface CydiaURLProtocol : NSURLProtocol {
7146 @implementation CydiaURLProtocol
7148 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7149 NSURL *url([request URL]);
7153 NSString *scheme([[url scheme] lowercaseString]);
7154 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7156 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7162 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7166 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7167 id<NSURLProtocolClient> client([self client]);
7169 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7171 NSData *data(UIImagePNGRepresentation(icon));
7173 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7174 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7175 [client URLProtocol:self didLoadData:data];
7176 [client URLProtocolDidFinishLoading:self];
7180 - (void) startLoading {
7181 id<NSURLProtocolClient> client([self client]);
7182 NSURLRequest *request([self request]);
7184 NSURL *url([request URL]);
7185 NSString *href([url absoluteString]);
7186 NSString *scheme([[url scheme] lowercaseString]);
7190 if ([scheme isEqualToString:@"cydia"])
7191 path = [href substringFromIndex:8];
7192 else if ([scheme isEqualToString:@"about"])
7193 path = [href substringFromIndex:12];
7194 else _assert(false);
7196 NSRange slash([path rangeOfString:@"/"]);
7199 if (slash.location == NSNotFound) {
7203 command = [path substringToIndex:slash.location];
7204 path = [path substringFromIndex:(slash.location + 1)];
7207 Database *database([Database sharedInstance]);
7209 if ([command isEqualToString:@"package-icon"]) {
7212 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7213 Package *package([database packageWithName:path]);
7216 UIImage *icon([package icon]);
7217 [self _returnPNGWithImage:icon forRequest:request];
7218 } else if ([command isEqualToString:@"source-icon"]) {
7221 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7222 NSString *source(Simplify(path));
7223 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7225 icon = [UIImage applicationImageNamed:@"unknown.png"];
7226 [self _returnPNGWithImage:icon forRequest:request];
7227 } else if ([command isEqualToString:@"uikit-image"]) {
7230 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7231 UIImage *icon(_UIImageWithName(path));
7232 [self _returnPNGWithImage:icon forRequest:request];
7233 } else if ([command isEqualToString:@"section-icon"]) {
7236 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7237 NSString *section(Simplify(path));
7238 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7240 icon = [UIImage applicationImageNamed:@"unknown.png"];
7241 [self _returnPNGWithImage:icon forRequest:request];
7243 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7247 - (void) stopLoading {
7253 /* Section Controller {{{ */
7254 @interface SectionController : FilteredPackageListController {
7255 _H<NSString> section_;
7258 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7262 @implementation SectionController
7264 - (NSURL *) navigationURL {
7265 NSString *name = section_;
7269 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7272 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7275 title = UCLocalize("ALL_PACKAGES");
7276 else if (![name isEqual:@""])
7277 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7279 title = UCLocalize("NO_SECTION");
7281 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7288 /* Sections Controller {{{ */
7289 @interface SectionsController : CYViewController <
7290 UITableViewDataSource,
7293 _transient Database *database_;
7294 NSMutableArray *sections_;
7295 NSMutableArray *filtered_;
7299 - (id) initWithDatabase:(Database *)database;
7300 - (void) editButtonClicked;
7304 @implementation SectionsController
7307 [self releaseSubviews];
7308 [sections_ release];
7309 [filtered_ release];
7314 - (NSURL *) navigationURL {
7315 return [NSURL URLWithString:@"cydia://sections"];
7318 - (void) updateNavigationItem {
7319 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7320 if ([sections_ count] == 0) {
7321 [[self navigationItem] setRightBarButtonItem:nil];
7323 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7324 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7326 action:@selector(editButtonClicked)
7327 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7331 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7332 [super setEditing:editing animated:animated];
7337 [delegate_ updateData];
7339 [self updateNavigationItem];
7342 - (void) viewDidAppear:(BOOL)animated {
7343 [super viewDidAppear:animated];
7344 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7347 - (void) viewWillDisappear:(BOOL)animated {
7348 [super viewWillDisappear:animated];
7349 if ([self isEditing]) [self setEditing:NO];
7352 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7353 Section *section = nil;
7354 int index = [indexPath row];
7355 if (![self isEditing]) {
7358 section = [filtered_ objectAtIndex:index];
7360 section = [sections_ objectAtIndex:index];
7365 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7366 if ([self isEditing])
7367 return [sections_ count];
7369 return [filtered_ count] + 1;
7372 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7376 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7377 static NSString *reuseIdentifier = @"SectionCell";
7379 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7381 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7383 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7388 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7389 if ([self isEditing])
7392 Section *section = [self sectionAtIndexPath:indexPath];
7394 SectionController *controller = [[[SectionController alloc]
7395 initWithDatabase:database_
7396 section:[section name]
7398 [controller setDelegate:delegate_];
7400 [[self navigationController] pushViewController:controller animated:YES];
7404 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7406 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7407 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7408 [list_ setRowHeight:45.0f];
7409 [list_ setDataSource:self];
7410 [list_ setDelegate:self];
7411 [[self view] addSubview:list_];
7414 - (void) viewDidLoad {
7415 [super viewDidLoad];
7417 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7420 - (void) releaseSubviews {
7425 - (id) initWithDatabase:(Database *)database {
7426 if ((self = [super init]) != nil) {
7427 database_ = database;
7429 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7430 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7434 - (void) reloadData {
7437 NSArray *packages = [database_ packages];
7439 [sections_ removeAllObjects];
7440 [filtered_ removeAllObjects];
7442 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7445 for (Package *package in packages) {
7446 NSString *name([package section]);
7447 NSString *key(name == nil ? @"" : name);
7451 _profile(SectionsView$reloadData$Section)
7452 section = [sections objectForKey:key];
7453 if (section == nil) {
7454 _profile(SectionsView$reloadData$Section$Allocate)
7455 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7456 [sections setObject:section forKey:key];
7461 [section addToCount];
7463 _profile(SectionsView$reloadData$Filter)
7464 if (![package valid] || ![package visible])
7472 [sections_ addObjectsFromArray:[sections allValues]];
7474 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7476 for (Section *section in sections_) {
7477 size_t count([section row]);
7481 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7482 [section setCount:count];
7483 [filtered_ addObject:section];
7486 [self updateNavigationItem];
7491 - (void) editButtonClicked {
7492 [self setEditing:![self isEditing] animated:YES];
7498 /* Changes Controller {{{ */
7499 @interface ChangesController : CYViewController <
7500 UITableViewDataSource,
7503 _transient Database *database_;
7505 CFMutableArrayRef packages_;
7506 NSMutableArray *sections_;
7511 - (id) initWithDatabase:(Database *)database;
7515 @implementation ChangesController
7518 [self releaseSubviews];
7519 CFRelease(packages_);
7520 [sections_ release];
7525 - (NSURL *) navigationURL {
7526 return [NSURL URLWithString:@"cydia://changes"];
7529 - (void) viewDidAppear:(BOOL)animated {
7530 [super viewDidAppear:animated];
7531 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7534 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7535 NSInteger count([sections_ count]);
7536 return count == 0 ? 1 : count;
7539 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7540 if ([sections_ count] == 0)
7542 return [[sections_ objectAtIndex:section] name];
7545 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7546 if ([sections_ count] == 0)
7548 return [[sections_ objectAtIndex:section] count];
7551 - (Package *) packageAtIndex:(NSUInteger)index {
7552 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7555 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7556 @synchronized (database_) {
7557 if ([database_ era] != era_)
7560 NSUInteger sectionIndex([path section]);
7561 if (sectionIndex >= [sections_ count])
7563 Section *section([sections_ objectAtIndex:sectionIndex]);
7564 NSInteger row([path row]);
7565 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7568 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7569 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7571 cell = [[[PackageCell alloc] init] autorelease];
7572 [cell setPackage:[self packageAtIndexPath:path]];
7576 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7577 Package *package([self packageAtIndexPath:path]);
7578 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7579 [view setDelegate:delegate_];
7580 [[self navigationController] pushViewController:view animated:YES];
7584 - (void) refreshButtonClicked {
7585 [delegate_ beginUpdate];
7586 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7589 - (void) upgradeButtonClicked {
7590 [delegate_ distUpgrade];
7594 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7596 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7597 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7598 [list_ setRowHeight:73];
7599 [list_ setDataSource:self];
7600 [list_ setDelegate:self];
7601 [[self view] addSubview:list_];
7604 - (void) viewDidLoad {
7605 [super viewDidLoad];
7607 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7610 - (void) releaseSubviews {
7615 - (id) initWithDatabase:(Database *)database {
7616 if ((self = [super init]) != nil) {
7617 database_ = database;
7619 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7620 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7624 // this mostly works because reloadData (below) is @synchronized (database_)
7625 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7626 - (void) _reloadPackages:(NSArray *)packages {
7627 CFRelease(packages_);
7628 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7631 _profile(ChangesController$_reloadPackages$Filter)
7632 for (Package *package in packages)
7633 if ([package upgradableAndEssential:YES] || [package visible])
7634 CFArrayAppendValue(packages_, package);
7637 _profile(ChangesController$_reloadPackages$radixSort)
7638 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7643 - (void) _reloadData {
7644 @synchronized (database_) {
7645 era_ = [database_ era];
7646 NSArray *packages = [database_ packages];
7648 [sections_ removeAllObjects];
7651 UIProgressHUD *hud([delegate_ addProgressHUD]);
7652 [hud setText:UCLocalize("LOADING")];
7653 //NSLog(@"HUD:%@::%@", delegate_, hud);
7654 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7655 [delegate_ removeProgressHUD:hud];
7657 [self _reloadPackages:packages];
7660 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7661 Section *ignored = nil;
7662 Section *section = nil;
7666 bool unseens = false;
7668 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7670 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7671 Package *package = [self packageAtIndex:offset];
7673 BOOL uae = [package upgradableAndEssential:YES];
7677 time_t seen([package seen]);
7679 if (section == nil || last != seen) {
7683 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7686 _profile(ChangesController$reloadData$Allocate)
7687 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7688 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7689 [sections_ addObject:section];
7693 [section addToCount];
7694 } else if ([package ignored]) {
7695 if (ignored == nil) {
7696 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7698 [ignored addToCount];
7701 [upgradable addToCount];
7706 CFRelease(formatter);
7709 Section *last = [sections_ lastObject];
7710 size_t count = [last count];
7711 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7712 [sections_ removeLastObject];
7715 if ([ignored count] != 0)
7716 [sections_ insertObject:ignored atIndex:0];
7718 [sections_ insertObject:upgradable atIndex:0];
7723 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7724 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7725 style:UIBarButtonItemStylePlain
7727 action:@selector(upgradeButtonClicked)
7730 if (![delegate_ updating])
7731 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7732 initWithTitle:UCLocalize("REFRESH")
7733 style:UIBarButtonItemStylePlain
7735 action:@selector(refreshButtonClicked)
7741 - (void) reloadData {
7743 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7748 /* Search Controller {{{ */
7749 @interface SearchController : FilteredPackageListController <
7752 _H<UISearchBar> search_;
7756 - (id) initWithDatabase:(Database *)database;
7757 - (void) setSearchTerm:(NSString *)term;
7758 - (void) reloadData;
7762 @implementation SearchController
7765 [search_ setDelegate:nil];
7769 - (NSURL *) navigationURL {
7770 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7771 return [NSURL URLWithString:@"cydia://search"];
7773 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7776 - (void) setSearchTerm:(NSString *)searchTerm {
7777 [search_ setText:searchTerm];
7781 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7782 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7783 [search_ resignFirstResponder];
7787 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7788 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7792 - (id) initWithDatabase:(Database *)database {
7793 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7794 search_ = [[[UISearchBar alloc] init] autorelease];
7795 [search_ setDelegate:self];
7799 - (void) viewDidAppear:(BOOL)animated {
7800 [super viewDidAppear:animated];
7802 if (!searchloaded_) {
7803 searchloaded_ = YES;
7804 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7805 [search_ layoutSubviews];
7806 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7808 UITextField *textField;
7809 if ([search_ respondsToSelector:@selector(searchField)])
7810 textField = [search_ searchField];
7812 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7814 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7815 [textField setEnablesReturnKeyAutomatically:NO];
7816 [[self navigationItem] setTitleView:textField];
7820 - (void) reloadData {
7821 [self setObject:[search_ text]];
7827 - (void) didSelectPackage:(Package *)package {
7828 [search_ resignFirstResponder];
7829 [super didSelectPackage:package];
7834 /* Package Settings Controller {{{ */
7835 @interface PackageSettingsController : CYViewController <
7836 UITableViewDataSource,
7839 _transient Database *database_;
7842 UITableView *table_;
7843 UISwitch *subscribedSwitch_;
7844 UISwitch *ignoredSwitch_;
7845 UITableViewCell *subscribedCell_;
7846 UITableViewCell *ignoredCell_;
7849 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7853 @implementation PackageSettingsController
7856 [self releaseSubviews];
7863 - (NSURL *) navigationURL {
7864 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7867 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7868 if (package_ == nil)
7871 if ([package_ installed] == nil)
7877 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7878 if (package_ == nil)
7881 // both sections contain just one item right now.
7885 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7889 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7891 return UCLocalize("SHOW_ALL_CHANGES_EX");
7893 return UCLocalize("IGNORE_UPGRADES_EX");
7896 - (void) onSubscribed:(id)control {
7897 bool value([control isOn]);
7898 if (package_ == nil)
7900 if ([package_ setSubscribed:value])
7901 [delegate_ updateData];
7904 - (void) _updateIgnored {
7905 const char *package([name_ UTF8String]);
7906 bool on([ignoredSwitch_ isOn]);
7908 pid_t pid(ExecFork());
7910 FILE *dpkg(popen("dpkg --set-selections", "w"));
7911 fwrite(package, strlen(package), 1, dpkg);
7914 fwrite(" hold\n", 6, 1, dpkg);
7916 fwrite(" install\n", 9, 1, dpkg);
7926 int result(waitpid(pid, &status, 0));
7929 _assert(result == pid);
7935 - (void) onIgnored:(id)control {
7936 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7937 [invocation setTarget:self];
7938 [invocation setSelector:@selector(_updateIgnored)];
7940 [delegate_ reloadDataWithInvocation:invocation];
7943 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7944 if (package_ == nil)
7947 switch ([indexPath section]) {
7948 case 0: return subscribedCell_;
7949 case 1: return ignoredCell_;
7958 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7960 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7961 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7962 [table_ setDataSource:self];
7963 [table_ setDelegate:self];
7964 [[self view] addSubview:table_];
7966 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7967 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7968 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7970 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7971 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7972 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7974 subscribedCell_ = [[UITableViewCell alloc] init];
7975 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7976 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7977 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7979 ignoredCell_ = [[UITableViewCell alloc] init];
7980 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7981 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7982 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7985 - (void) viewDidLoad {
7986 [super viewDidLoad];
7988 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7991 - (void) releaseSubviews {
7992 [ignoredCell_ release];
7995 [subscribedCell_ release];
7996 subscribedCell_ = nil;
8001 [ignoredSwitch_ release];
8002 ignoredSwitch_ = nil;
8004 [subscribedSwitch_ release];
8005 subscribedSwitch_ = nil;
8008 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8009 if ((self = [super init]) != nil) {
8010 database_ = database;
8011 name_ = [package retain];
8015 - (void) reloadData {
8018 if (package_ != nil)
8019 [package_ autorelease];
8020 package_ = [database_ packageWithName:name_];
8022 if (package_ != nil) {
8023 package_ = [package_ retain];
8024 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8025 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8026 } // XXX: what now, G?
8028 [table_ reloadData];
8034 /* Installed Controller {{{ */
8035 @interface InstalledController : FilteredPackageListController {
8039 - (id) initWithDatabase:(Database *)database;
8041 - (void) updateRoleButton;
8042 - (void) queueStatusDidChange;
8046 @implementation InstalledController
8052 - (NSURL *) navigationURL {
8053 return [NSURL URLWithString:@"cydia://installed"];
8056 - (id) initWithDatabase:(Database *)database {
8057 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8058 [self updateRoleButton];
8059 [self queueStatusDidChange];
8064 - (void) queueButtonClicked {
8069 - (void) queueStatusDidChange {
8073 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8074 initWithTitle:UCLocalize("QUEUE")
8075 style:UIBarButtonItemStyleDone
8077 action:@selector(queueButtonClicked)
8080 [[self navigationItem] setLeftBarButtonItem:nil];
8086 - (void) updateRoleButton {
8087 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8088 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8089 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8090 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8092 action:@selector(roleButtonClicked)
8096 - (void) roleButtonClicked {
8097 [self setObject:[NSNumber numberWithBool:expert_]];
8101 [self updateRoleButton];
8107 /* Source Cell {{{ */
8108 @interface SourceCell : CYTableViewCell <
8116 - (void) setSource:(Source *)source;
8120 @implementation SourceCell
8122 - (void) clearSource {
8132 - (void) setSource:(Source *)source {
8136 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
8138 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8139 icon_ = [icon_ retain];
8141 origin_ = [[source name] retain];
8142 label_ = [[source uri] retain];
8144 [content_ setNeedsDisplay];
8152 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8153 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8154 UIView *content([self contentView]);
8155 CGRect bounds([content bounds]);
8157 content_ = [[ContentView alloc] initWithFrame:bounds];
8158 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8159 [content_ setBackgroundColor:[UIColor whiteColor]];
8160 [content addSubview:content_];
8162 [content_ setDelegate:self];
8163 [content_ setOpaque:YES];
8167 - (NSString *) accessibilityLabel {
8171 - (void) drawContentRect:(CGRect)rect {
8172 bool highlighted(highlighted_);
8173 float width(rect.size.width);
8176 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8183 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8187 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8192 /* Source Controller {{{ */
8193 @interface SourceController : FilteredPackageListController {
8194 _transient Source *source_;
8198 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8202 @implementation SourceController
8204 - (NSURL *) navigationURL {
8205 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8208 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8209 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8211 key_ = [[source key] retain];
8215 - (void) reloadData {
8216 source_ = [database_ sourceWithKey:key_];
8218 key_ = [[source_ key] retain];
8219 [self setObject:source_];
8221 [[self navigationItem] setTitle:[source_ label]];
8228 /* Sources Controller {{{ */
8229 @interface SourcesController : CYViewController <
8230 UITableViewDataSource,
8233 _transient Database *database_;
8235 NSMutableArray *sources_;
8239 UIProgressHUD *hud_;
8242 //NSURLConnection *installer_;
8243 NSURLConnection *trivial_;
8244 NSURLConnection *trivial_bz2_;
8245 NSURLConnection *trivial_gz_;
8246 //NSURLConnection *automatic_;
8251 - (id) initWithDatabase:(Database *)database;
8252 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8256 @implementation SourcesController
8258 - (void) _releaseConnection:(NSURLConnection *)connection {
8259 if (connection != nil) {
8260 [connection cancel];
8261 //[connection setDelegate:nil];
8262 [connection release];
8267 [self releaseSubviews];
8273 //[self _releaseConnection:installer_];
8274 [self _releaseConnection:trivial_];
8275 [self _releaseConnection:trivial_gz_];
8276 [self _releaseConnection:trivial_bz2_];
8277 //[self _releaseConnection:automatic_];
8283 - (NSURL *) navigationURL {
8284 return [NSURL URLWithString:@"cydia://sources"];
8287 - (void) viewDidAppear:(BOOL)animated {
8288 [super viewDidAppear:animated];
8289 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8292 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8293 return offset_ == 0 ? 1 : 2;
8296 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8297 switch (section + (offset_ == 0 ? 1 : 0)) {
8298 case 0: return UCLocalize("ENTERED_BY_USER");
8299 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8305 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8306 int count = [sources_ count];
8308 case 0: return (offset_ == 0 ? count : offset_);
8309 case 1: return count - offset_;
8315 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8317 switch (indexPath.section) {
8318 case 0: idx = indexPath.row; break;
8319 case 1: idx = indexPath.row + offset_; break;
8323 return [sources_ objectAtIndex:idx];
8326 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8327 static NSString *cellIdentifier = @"SourceCell";
8329 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8330 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8331 [cell setSource:[self sourceAtIndexPath:indexPath]];
8332 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8337 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8338 Source *source = [self sourceAtIndexPath:indexPath];
8340 SourceController *controller = [[[SourceController alloc]
8341 initWithDatabase:database_
8345 [controller setDelegate:delegate_];
8347 [[self navigationController] pushViewController:controller animated:YES];
8350 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8351 Source *source = [self sourceAtIndexPath:indexPath];
8352 return [source record] != nil;
8355 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8356 Source *source = [self sourceAtIndexPath:indexPath];
8357 [Sources_ removeObjectForKey:[source key]];
8358 [delegate_ syncData];
8362 [delegate_ addTrivialSource:href_];
8363 [delegate_ syncData];
8366 - (NSString *) getWarning {
8367 NSString *href(href_);
8368 NSRange colon([href rangeOfString:@"://"]);
8369 if (colon.location != NSNotFound)
8370 href = [href substringFromIndex:(colon.location + 3)];
8371 href = [href stringByAddingPercentEscapes];
8372 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8373 href = [href stringByCachingURLWithCurrentCDN];
8375 NSURL *url([NSURL URLWithString:href]);
8377 NSStringEncoding encoding;
8378 NSError *error(nil);
8380 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8381 return [warning length] == 0 ? nil : warning;
8385 - (void) _endConnection:(NSURLConnection *)connection {
8386 // XXX: the memory management in this method is horribly awkward
8388 NSURLConnection **field = NULL;
8389 if (connection == trivial_)
8391 else if (connection == trivial_bz2_)
8392 field = &trivial_bz2_;
8393 else if (connection == trivial_gz_)
8394 field = &trivial_gz_;
8395 _assert(field != NULL);
8396 [connection release];
8401 trivial_bz2_ == nil &&
8407 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8410 UIAlertView *alert = [[[UIAlertView alloc]
8411 initWithTitle:UCLocalize("SOURCE_WARNING")
8414 cancelButtonTitle:UCLocalize("CANCEL")
8416 UCLocalize("ADD_ANYWAY"),
8420 [alert setContext:@"warning"];
8421 [alert setNumberOfRows:1];
8425 } else if (error_ != nil) {
8426 UIAlertView *alert = [[[UIAlertView alloc]
8427 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8428 message:[error_ localizedDescription]
8430 cancelButtonTitle:UCLocalize("OK")
8431 otherButtonTitles:nil
8434 [alert setContext:@"urlerror"];
8437 UIAlertView *alert = [[[UIAlertView alloc]
8438 initWithTitle:UCLocalize("NOT_REPOSITORY")
8439 message:UCLocalize("NOT_REPOSITORY_EX")
8441 cancelButtonTitle:UCLocalize("OK")
8442 otherButtonTitles:nil
8445 [alert setContext:@"trivial"];
8449 [delegate_ releaseNetworkActivityIndicator];
8451 [delegate_ removeProgressHUD:hud_];
8460 if (error_ != nil) {
8467 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8468 switch ([response statusCode]) {
8474 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8475 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8477 error_ = [error retain];
8478 [self _endConnection:connection];
8481 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8482 [self _endConnection:connection];
8485 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8486 NSMutableURLRequest *request = [NSMutableURLRequest
8487 requestWithURL:[NSURL URLWithString:href]
8488 cachePolicy:NSURLRequestUseProtocolCachePolicy
8489 timeoutInterval:120.0
8492 [request setHTTPMethod:method];
8494 if (Machine_ != NULL)
8495 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8496 if (UniqueID_ != nil)
8497 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8499 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8502 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8503 NSString *context([alert context]);
8505 if ([context isEqualToString:@"source"]) {
8508 NSString *href = [[alert textField] text];
8510 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8512 if (![href hasSuffix:@"/"])
8513 href_ = [href stringByAppendingString:@"/"];
8516 href_ = [href_ retain];
8518 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8519 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8520 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8521 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8525 // XXX: this is stupid
8526 hud_ = [[delegate_ addProgressHUD] retain];
8527 [hud_ setText:UCLocalize("VERIFYING_URL")];
8528 [delegate_ retainNetworkActivityIndicator];
8537 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8538 } else if ([context isEqualToString:@"trivial"])
8539 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8540 else if ([context isEqualToString:@"urlerror"])
8541 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8542 else if ([context isEqualToString:@"warning"]) {
8557 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8562 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8564 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8565 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8566 [list_ setRowHeight:56];
8567 [list_ setDataSource:self];
8568 [list_ setDelegate:self];
8569 [[self view] addSubview:list_];
8572 - (void) viewDidLoad {
8573 [super viewDidLoad];
8575 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8576 [self updateButtonsForEditingStatus:NO animated:NO];
8579 - (void) releaseSubviews {
8584 - (id) initWithDatabase:(Database *)database {
8585 if ((self = [super init]) != nil) {
8586 database_ = database;
8587 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8591 - (void) reloadData {
8595 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8598 [sources_ removeAllObjects];
8599 [sources_ addObjectsFromArray:[database_ sources]];
8601 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8604 int count([sources_ count]);
8606 for (int i = 0; i != count; i++) {
8607 if ([[sources_ objectAtIndex:i] record] == nil)
8612 [list_ setEditing:NO];
8613 [self updateButtonsForEditingStatus:NO animated:NO];
8617 - (void) showAddSourcePrompt {
8618 UIAlertView *alert = [[[UIAlertView alloc]
8619 initWithTitle:UCLocalize("ENTER_APT_URL")
8622 cancelButtonTitle:UCLocalize("CANCEL")
8624 UCLocalize("ADD_SOURCE"),
8628 [alert setContext:@"source"];
8629 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8631 [alert setNumberOfRows:1];
8632 [alert addTextFieldWithValue:@"http://" label:@""];
8634 UITextInputTraits *traits = [[alert textField] textInputTraits];
8635 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8636 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8637 [traits setKeyboardType:UIKeyboardTypeURL];
8638 // XXX: UIReturnKeyDone
8639 [traits setReturnKeyType:UIReturnKeyNext];
8644 - (void) addButtonClicked {
8645 [self showAddSourcePrompt];
8648 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8649 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8650 initWithTitle:UCLocalize("ADD")
8651 style:UIBarButtonItemStylePlain
8653 action:@selector(addButtonClicked)
8654 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8656 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8657 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8658 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8660 action:@selector(editButtonClicked)
8661 ] autorelease] animated:animated];
8663 if (IsWildcat_ && !editing)
8664 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8665 initWithTitle:UCLocalize("SETTINGS")
8666 style:UIBarButtonItemStylePlain
8668 action:@selector(settingsButtonClicked)
8672 - (void) settingsButtonClicked {
8673 [delegate_ showSettings];
8676 - (void) editButtonClicked {
8677 [list_ setEditing:![list_ isEditing] animated:YES];
8679 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8685 /* Settings Controller {{{ */
8686 @interface SettingsController : CYViewController <
8687 UITableViewDataSource,
8690 _transient Database *database_;
8691 // XXX: ok, "roledelegate_"?...
8692 _transient id roledelegate_;
8693 UITableView *table_;
8694 UISegmentedControl *segment_;
8698 - (void) showDoneButton;
8699 - (void) resizeSegmentedControl;
8703 @implementation SettingsController
8706 [self releaseSubviews];
8712 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8714 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8715 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8716 [table_ setDelegate:self];
8717 [table_ setDataSource:self];
8718 [[self view] addSubview:table_];
8720 NSArray *items = [NSArray arrayWithObjects:
8722 UCLocalize("HACKER"),
8723 UCLocalize("DEVELOPER"),
8725 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8726 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8727 [container_ addSubview:segment_];
8730 - (void) viewDidLoad {
8731 [super viewDidLoad];
8733 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8736 if ([Role_ isEqualToString:@"User"]) index = 0;
8737 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8738 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8740 [segment_ setSelectedSegmentIndex:index];
8741 [self showDoneButton];
8744 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8745 [self resizeSegmentedControl];
8748 - (void) releaseSubviews {
8755 [container_ release];
8759 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8760 if ((self = [super init]) != nil) {
8761 database_ = database;
8762 roledelegate_ = delegate;
8766 - (void) resizeSegmentedControl {
8767 CGFloat width = [[self view] frame].size.width;
8768 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8771 - (void) viewWillAppear:(BOOL)animated {
8772 [super viewWillAppear:animated];
8774 [self resizeSegmentedControl];
8777 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8778 [self resizeSegmentedControl];
8781 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8782 [self resizeSegmentedControl];
8786 NSString *role(nil);
8788 switch ([segment_ selectedSegmentIndex]) {
8789 case 0: role = @"User"; break;
8790 case 1: role = @"Hacker"; break;
8791 case 2: role = @"Developer"; break;
8796 if (![role isEqualToString:Role_]) {
8797 bool rolling(Role_ == nil);
8800 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8804 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8808 [roledelegate_ loadData];
8810 [roledelegate_ updateData];
8814 - (void) segmentChanged:(UISegmentedControl *)control {
8815 [self showDoneButton];
8818 - (void) saveAndClose {
8821 [[self navigationItem] setRightBarButtonItem:nil];
8822 [[self navigationController] dismissModalViewControllerAnimated:YES];
8825 - (void) doneButtonClicked {
8826 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8827 [spinner startAnimating];
8828 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8829 [[self navigationItem] setRightBarButtonItem:spinItem];
8831 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8834 - (void) showDoneButton {
8835 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8836 initWithTitle:UCLocalize("DONE")
8837 style:UIBarButtonItemStyleDone
8839 action:@selector(doneButtonClicked)
8840 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8843 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8844 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8848 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8852 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8853 return nil; // This method is required by the protocol.
8856 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8858 return UCLocalize("ROLE_EX");
8860 return [NSString stringWithFormat:
8861 @"%@: %@\n%@: %@\n%@: %@",
8862 UCLocalize("USER"), UCLocalize("USER_EX"),
8863 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8864 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8869 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8870 return section == 3 ? 44.0f : 0;
8873 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8874 return section == 3 ? container_ : nil;
8877 - (void) reloadData {
8880 [table_ reloadData];
8885 /* Stash Controller {{{ */
8886 @interface StashController : CYViewController {
8887 UIActivityIndicatorView *spinner_;
8894 @implementation StashController
8897 [self releaseSubviews];
8903 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8904 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8906 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8907 CGRect spinrect = [spinner_ frame];
8908 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8909 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8910 [spinner_ setFrame:spinrect];
8911 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8912 [[self view] addSubview:spinner_];
8913 [spinner_ startAnimating];
8916 captrect.size.width = [[self view] frame].size.width;
8917 captrect.size.height = 40.0f;
8918 captrect.origin.x = 0;
8919 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8920 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8921 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8922 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8923 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8924 [caption_ setTextColor:[UIColor whiteColor]];
8925 [caption_ setBackgroundColor:[UIColor clearColor]];
8926 [caption_ setShadowColor:[UIColor blackColor]];
8927 [caption_ setTextAlignment:UITextAlignmentCenter];
8928 [[self view] addSubview:caption_];
8931 statusrect.size.width = [[self view] frame].size.width;
8932 statusrect.size.height = 30.0f;
8933 statusrect.origin.x = 0;
8934 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8935 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8936 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8937 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8938 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8939 [status_ setTextColor:[UIColor whiteColor]];
8940 [status_ setBackgroundColor:[UIColor clearColor]];
8941 [status_ setShadowColor:[UIColor blackColor]];
8942 [status_ setTextAlignment:UITextAlignmentCenter];
8943 [[self view] addSubview:status_];
8946 - (void) releaseSubviews {
8960 @interface Cydia : UIApplication <
8961 ConfirmationControllerDelegate,
8964 UINavigationControllerDelegate,
8965 UITabBarControllerDelegate
8967 // XXX: evaluate all fields for _transient
8970 CYTabBarController *tabbar_;
8971 CYEmulatedLoadingController *emulated_;
8973 NSMutableArray *essential_;
8974 NSMutableArray *broken_;
8976 Database *database_;
8983 StashController *stash_;
8992 @implementation Cydia
8994 - (void) beginUpdate {
8995 [tabbar_ beginUpdate];
8999 return [tabbar_ updating];
9003 if ([broken_ count] != 0) {
9004 int count = [broken_ count];
9006 UIAlertView *alert = [[[UIAlertView alloc]
9007 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9008 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9010 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
9012 UCLocalize("TEMPORARY_IGNORE"),
9016 [alert setContext:@"fixhalf"];
9017 [alert setNumberOfRows:2];
9019 } else if (!Ignored_ && [essential_ count] != 0) {
9020 int count = [essential_ count];
9022 UIAlertView *alert = [[[UIAlertView alloc]
9023 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9024 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9026 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9028 UCLocalize("UPGRADE_ESSENTIAL"),
9029 UCLocalize("COMPLETE_UPGRADE"),
9033 [alert setContext:@"upgrade"];
9038 - (void) _saveConfig {
9044 NSString *error(nil);
9046 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9048 NSError *error(nil);
9049 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9050 NSLog(@"failure to save metadata data: %@", error);
9055 NSLog(@"failure to serialize metadata: %@", error);
9060 // Navigation controller for the queuing badge.
9061 - (UINavigationController *) queueNavigationController {
9062 NSArray *controllers = [tabbar_ viewControllers];
9063 return [controllers objectAtIndex:3];
9066 - (void) unloadData {
9067 [tabbar_ unloadData];
9070 - (void) _updateData {
9075 UINavigationController *navigation = [self queueNavigationController];
9077 id queuedelegate = nil;
9078 if ([[navigation viewControllers] count] > 0)
9079 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9081 [queuedelegate queueStatusDidChange];
9082 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9085 - (void) _refreshIfPossible:(NSDate *)update {
9086 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9088 bool recently = false;
9089 if (update != nil) {
9090 NSTimeInterval interval([update timeIntervalSinceNow]);
9091 if (interval <= 0 && interval > -(15*60))
9095 // Don't automatic refresh if:
9096 // - We already refreshed recently.
9097 // - We already auto-refreshed this launch.
9098 // - Auto-refresh is disabled.
9099 if (recently || loaded_ || ManualRefresh) {
9100 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9102 // If we are cancelling, we need to make sure it knows it's already loaded.
9106 // We are going to load, so remember that.
9110 SCNetworkReachabilityFlags flags; {
9111 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9112 SCNetworkReachabilityGetFlags(reachability, &flags);
9113 CFRelease(reachability);
9116 // XXX: this elaborate mess is what Apple is using to determine this? :(
9117 // XXX: do we care if the user has to intervene? maybe that's ok?
9119 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9120 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9121 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9122 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9123 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9124 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9128 // If we can reach the server, auto-refresh!
9130 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9135 - (void) refreshIfPossible {
9136 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9139 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
9140 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9141 [hud setText:UCLocalize("RELOADING_DATA")];
9143 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9146 [self removeProgressHUD:hud];
9150 [essential_ removeAllObjects];
9151 [broken_ removeAllObjects];
9153 NSArray *packages([database_ packages]);
9154 for (Package *package in packages) {
9156 [broken_ addObject:package];
9157 if ([package upgradableAndEssential:NO]) {
9158 if ([package essential])
9159 [essential_ addObject:package];
9164 NSLog(@"changes:#%u", changes);
9166 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9169 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9170 [changesItem setBadgeValue:badge];
9171 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9172 [self setApplicationIconBadgeNumber:changes];
9175 [changesItem setBadgeValue:nil];
9176 [changesItem setAnimatedBadge:NO];
9177 [self setApplicationIconBadgeNumber:0];
9182 [self refreshIfPossible];
9185 - (void) updateData {
9194 @synchronized (self) {
9195 [self _reloadDataWithInvocation:nil];
9199 - (void) disemulate {
9200 if (emulated_ == nil)
9203 [window_ addSubview:[tabbar_ view]];
9204 [[emulated_ view] removeFromSuperview];
9205 [emulated_ release];
9207 [window_ setUserInteractionEnabled:YES];
9210 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9211 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9213 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9215 UIViewController *parent;
9216 if (emulated_ == nil)
9225 [parent presentModalViewController:navigation animated:YES];
9228 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9229 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9231 if (navigation != nil)
9232 [navigation pushViewController:progress animated:YES];
9234 [self presentModalViewController:progress force:YES];
9236 [progress invoke:invocation withTitle:title];
9240 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9241 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9244 - (void) repairWithInvocation:(NSInvocation *)invocation {
9246 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9250 - (void) repairWithSelector:(SEL)selector {
9251 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9257 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9258 _assert(file != NULL);
9260 for (NSString *key in [Sources_ allKeys]) {
9261 NSDictionary *source([Sources_ objectForKey:key]);
9263 fprintf(file, "%s %s %s\n",
9264 [[source objectForKey:@"Type"] UTF8String],
9265 [[source objectForKey:@"URI"] UTF8String],
9266 [[source objectForKey:@"Distribution"] UTF8String]
9272 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9277 - (void) addTrivialSource:(NSString *)href {
9278 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9281 @"./", @"Distribution",
9282 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9287 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9288 @synchronized (self) {
9289 [self _reloadDataWithInvocation:invocation];
9293 - (void) reloadData {
9294 [self reloadDataWithInvocation:nil];
9298 pkgProblemResolver *resolver = [database_ resolver];
9300 resolver->InstallProtect();
9301 if (!resolver->Resolve(true))
9306 // XXX: this is a really crappy way of doing this.
9307 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9308 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9309 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9310 if ([tabbar_ updating])
9311 [tabbar_ cancelUpdate];
9313 if (![database_ prepare])
9316 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9317 [page setDelegate:self];
9318 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9321 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9322 [tabbar_ presentModalViewController:confirm_ animated:YES];
9328 @synchronized (self) {
9333 - (void) clearPackage:(Package *)package {
9334 @synchronized (self) {
9341 - (void) installPackages:(NSArray *)packages {
9342 @synchronized (self) {
9343 for (Package *package in packages)
9350 - (void) installPackage:(Package *)package {
9351 @synchronized (self) {
9358 - (void) removePackage:(Package *)package {
9359 @synchronized (self) {
9366 - (void) distUpgrade {
9367 @synchronized (self) {
9368 if (![database_ upgrade])
9374 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9377 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
9382 - (void) showSettings {
9383 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9386 - (void) retainNetworkActivityIndicator {
9387 if (activity_++ == 0)
9388 [self setNetworkActivityIndicatorVisible:YES];
9391 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9395 - (void) releaseNetworkActivityIndicator {
9396 if (--activity_ == 0)
9397 [self setNetworkActivityIndicatorVisible:NO];
9400 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9405 - (void) cancelAndClear:(bool)clear {
9406 @synchronized (self) {
9418 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9419 NSString *context([alert context]);
9421 if ([context isEqualToString:@"conffile"]) {
9422 FILE *input = [database_ input];
9423 if (button == [alert cancelButtonIndex])
9424 fprintf(input, "N\n");
9425 else if (button == [alert firstOtherButtonIndex])
9426 fprintf(input, "Y\n");
9429 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9430 } else if ([context isEqualToString:@"fixhalf"]) {
9431 if (button == [alert cancelButtonIndex]) {
9432 @synchronized (self) {
9433 for (Package *broken in broken_) {
9436 NSString *id = [broken id];
9437 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9438 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9439 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9440 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9446 } else if (button == [alert firstOtherButtonIndex]) {
9447 [broken_ removeAllObjects];
9451 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9452 } else if ([context isEqualToString:@"upgrade"]) {
9453 if (button == [alert firstOtherButtonIndex]) {
9454 @synchronized (self) {
9455 for (Package *essential in essential_)
9456 [essential install];
9461 } else if (button == [alert firstOtherButtonIndex] + 1) {
9463 } else if (button == [alert cancelButtonIndex]) {
9467 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9471 - (void) system:(NSString *)command { _pooled
9473 system([command UTF8String]);
9477 - (void) applicationWillSuspend {
9479 [super applicationWillSuspend];
9482 - (BOOL) isSafeToSuspend {
9485 NSLog(@"isSafeToSuspend: locked_ != 0");
9490 // Use external process status API internally.
9491 // This is probably a really bad idea.
9492 // XXX: what is the point of this? does this solve anything at all?
9493 uint64_t status = 0;
9495 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9496 notify_get_state(notify_token, &status);
9497 notify_cancel(notify_token);
9502 NSLog(@"isSafeToSuspend: status != 0");
9508 NSLog(@"isSafeToSuspend: -> true");
9513 - (void) applicationSuspend:(__GSEvent *)event {
9514 if ([self isSafeToSuspend])
9515 [super applicationSuspend:event];
9518 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9519 if ([self isSafeToSuspend])
9520 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9523 - (void) _setSuspended:(BOOL)value {
9524 if ([self isSafeToSuspend])
9525 [super _setSuspended:value];
9528 - (UIProgressHUD *) addProgressHUD {
9529 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9530 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9532 [window_ setUserInteractionEnabled:NO];
9534 UIViewController *target(tabbar_);
9535 if (UIViewController *modal = [target modalViewController])
9538 UIView *view([target view]);
9539 [view addSubview:hud];
9547 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9550 [hud removeFromSuperview];
9551 [window_ setUserInteractionEnabled:YES];
9554 - (CYViewController *) pageForPackage:(NSString *)name {
9555 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9558 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9559 NSString *scheme([[url scheme] lowercaseString]);
9560 if ([[url absoluteString] length] <= [scheme length] + 3)
9562 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9563 NSArray *components([path pathComponents]);
9565 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9566 return [self pageForPackage:[components objectAtIndex:1]];
9568 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9571 NSString *base([components objectAtIndex:0]);
9573 CYViewController *controller = nil;
9575 if ([base isEqualToString:@"url"]) {
9576 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9577 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9578 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9579 } else if (!external && [components count] == 1) {
9580 if ([base isEqualToString:@"manage"]) {
9581 controller = [[[ManageController alloc] init] autorelease];
9584 if ([base isEqualToString:@"sources"]) {
9585 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9588 if ([base isEqualToString:@"home"]) {
9589 controller = [[[HomeController alloc] init] autorelease];
9592 if ([base isEqualToString:@"sections"]) {
9593 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9596 if ([base isEqualToString:@"search"]) {
9597 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9600 if ([base isEqualToString:@"changes"]) {
9601 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9604 if ([base isEqualToString:@"installed"]) {
9605 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9607 } else if ([components count] == 2) {
9608 NSString *argument = [components objectAtIndex:1];
9610 if ([base isEqualToString:@"package"]) {
9611 controller = [self pageForPackage:argument];
9614 if (!external && [base isEqualToString:@"search"]) {
9615 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9616 [(SearchController *)controller setSearchTerm:argument];
9619 if (!external && [base isEqualToString:@"sections"]) {
9620 if ([argument isEqualToString:@"all"])
9622 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9625 if (!external && [base isEqualToString:@"sources"]) {
9626 if ([argument isEqualToString:@"add"]) {
9627 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9628 [(SourcesController *)controller showAddSourcePrompt];
9630 Source *source = [database_ sourceWithKey:argument];
9631 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9635 if (!external && [base isEqualToString:@"launch"]) {
9636 [self launchApplicationWithIdentifier:argument suspended:NO];
9639 } else if (!external && [components count] == 3) {
9640 NSString *arg1 = [components objectAtIndex:1];
9641 NSString *arg2 = [components objectAtIndex:2];
9643 if ([base isEqualToString:@"package"]) {
9644 if ([arg2 isEqualToString:@"settings"]) {
9645 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9646 } else if ([arg2 isEqualToString:@"files"]) {
9647 if (Package *package = [database_ packageWithName:arg1]) {
9648 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9649 [(FileTable *)controller setPackage:package];
9655 [controller setDelegate:self];
9659 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9660 CYViewController *page([self pageForURL:url forExternal:external]);
9663 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9664 [nav setViewControllers:[NSArray arrayWithObject:page]];
9665 [tabbar_ setUnselectedViewController:nav];
9671 - (void) applicationOpenURL:(NSURL *)url {
9672 [super applicationOpenURL:url];
9674 if (!loaded_) starturl_ = [url retain];
9675 else [self openCydiaURL:url forExternal:YES];
9678 - (void) applicationWillResignActive:(UIApplication *)application {
9679 // Stop refreshing if you get a phone call or lock the device.
9680 if ([tabbar_ updating])
9681 [tabbar_ cancelUpdate];
9683 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9684 [super applicationWillResignActive:application];
9687 - (void) applicationWillTerminate:(UIApplication *)application {
9689 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9690 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9691 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9696 - (void) setConfigurationData:(NSString *)data {
9697 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9699 if (!conffile_r(data)) {
9700 lprintf("E:invalid conffile\n");
9704 NSString *ofile = conffile_r[1];
9705 //NSString *nfile = conffile_r[2];
9707 UIAlertView *alert = [[[UIAlertView alloc]
9708 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9709 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9711 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9713 UCLocalize("ACCEPT_NEW_COPY"),
9714 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9718 [alert setContext:@"conffile"];
9719 [alert setNumberOfRows:2];
9723 - (void) addStashController {
9725 stash_ = [[StashController alloc] init];
9726 [window_ addSubview:[stash_ view]];
9729 - (void) removeStashController {
9730 [[stash_ view] removeFromSuperview];
9736 [self setIdleTimerDisabled:YES];
9738 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9739 UpdateExternalStatus(1);
9740 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9741 UpdateExternalStatus(0);
9743 [self removeStashController];
9745 if (ExecFork() == 0) {
9746 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9747 perror("launchctl stop");
9751 - (void) setupViewControllers {
9752 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9754 NSMutableArray *items([NSMutableArray arrayWithObjects:
9755 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9756 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9757 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9758 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9762 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9763 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9765 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9768 NSMutableArray *controllers([NSMutableArray array]);
9769 for (UITabBarItem *item in items) {
9770 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9771 [controller setTabBarItem:item];
9772 [controllers addObject:controller];
9774 [tabbar_ setViewControllers:controllers];
9776 [tabbar_ setUpdateDelegate:self];
9779 - (void) applicationDidFinishLaunching:(id)unused {
9781 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9782 [self setApplicationSupportsShakeToEdit:NO];
9784 @synchronized (HostConfig_) {
9785 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9788 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9789 initWithMemoryCapacity:524288
9790 diskCapacity:10485760
9791 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9794 [CYBrowserController _initialize];
9796 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9798 Font12_ = [[UIFont systemFontOfSize:12] retain];
9799 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9800 Font14_ = [[UIFont systemFontOfSize:14] retain];
9801 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9802 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9804 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9805 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9807 // XXX: I really need this thing... like, seriously... I'm sorry
9808 [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9810 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9811 [window_ orderFront:self];
9812 [window_ makeKey:self];
9813 [window_ setHidden:NO];
9816 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9817 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9818 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9819 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9820 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9821 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9822 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9823 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9824 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9827 [self addStashController];
9828 // XXX: this would be much cleaner as a yieldToSelector:
9829 // that way the removeStashController could happen right here inline
9830 // we also could no longer require the useless stash_ field anymore
9831 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9835 database_ = [Database sharedInstance];
9836 [database_ setDelegate:self];
9838 [window_ setUserInteractionEnabled:NO];
9839 [self setupViewControllers];
9841 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9842 [window_ addSubview:[emulated_ view]];
9844 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9848 - (NSArray *) defaultStartPages {
9849 NSMutableArray *standard = [NSMutableArray array];
9850 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9851 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9852 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9854 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9856 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9857 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9859 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9866 [window_ setUserInteractionEnabled:YES];
9867 [self showSettings];
9870 if ([emulated_ modalViewController] != nil)
9871 [emulated_ dismissModalViewControllerAnimated:YES];
9872 [window_ setUserInteractionEnabled:NO];
9880 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9881 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9882 int standardIndex = 0;
9883 NSArray *standard = [self defaultStartPages];
9890 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9891 if (valid && closed != nil) {
9892 NSTimeInterval interval([closed timeIntervalSinceNow]);
9893 // XXX: Is 15 minutes the optimal time here?
9894 if (interval > 0 && interval <= -(15*60))
9898 if (valid && [saved count] != [standard count])
9902 for (unsigned int i = 0; i < [standard count]; i++) {
9903 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9904 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9905 // but it's good enough for now.
9906 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9913 NSArray *items = nil;
9915 [tabbar_ setSelectedIndex:savedIndex];
9918 [tabbar_ setSelectedIndex:standardIndex];
9922 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9923 NSArray *stack = [items objectAtIndex:tab];
9924 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9925 NSMutableArray *current = [NSMutableArray array];
9927 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9928 NSString *addr = [stack objectAtIndex:nav];
9929 NSURL *url = [NSURL URLWithString:addr];
9930 CYViewController *page = [self pageForURL:url forExternal:NO];
9932 [current addObject:page];
9935 [navigation setViewControllers:current];
9938 // (Try to) show the startup URL.
9939 if (starturl_ != nil) {
9940 [self openCydiaURL:starturl_ forExternal:NO];
9941 [starturl_ release];
9946 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9947 if (item != nil && IsWildcat_) {
9948 [sheet showFromBarButtonItem:item animated:YES];
9950 [sheet showInView:window_];
9954 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9955 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9956 [progress setTitle:task];
9957 [progress addProgressEvent:event];
9960 - (void) addProgressEventForTask:(NSArray *)data {
9961 CydiaProgressEvent *event([data objectAtIndex:0]);
9962 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9963 [self addProgressEvent:event forTask:task];
9966 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9967 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9973 id Alloc_(id self, SEL selector) {
9974 id object = alloc_(self, selector);
9975 lprintf("[%s]A-%p\n", self->isa->name, object);
9980 id Dealloc_(id self, SEL selector) {
9981 id object = dealloc_(self, selector);
9982 lprintf("[%s]D-%p\n", self->isa->name, object);
9986 Class $WebDefaultUIKitDelegate;
9988 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9989 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9990 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9991 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9994 static NSSet *MobilizedFiles_;
9996 static NSURL *MobilizeURL(NSURL *url) {
9997 NSString *path([url path]);
9998 if ([path hasPrefix:@"/var/root/"]) {
9999 NSString *file([path substringFromIndex:10]);
10000 if ([MobilizedFiles_ containsObject:file])
10001 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10007 Class $CFXPreferencesPropertyListSource;
10008 @class CFXPreferencesPropertyListSource;
10010 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10011 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10012 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10013 url = MobilizeURL(url);
10014 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10015 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10021 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10022 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10023 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10024 url = MobilizeURL(url);
10025 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10026 //NSLog(@"%@ %@", [url absoluteString], value);
10032 Class $NSURLConnection;
10034 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10035 NSMutableURLRequest *copy([request mutableCopy]);
10037 NSURL *url([copy URL]);
10038 NSString *host([url host]);
10039 NSString *scheme([[url scheme] lowercaseString]);
10041 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10043 @synchronized (HostConfig_) {
10044 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10045 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10046 [copy setHTTPShouldUsePipelining:YES];
10049 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10053 int main(int argc, char *argv[]) { _pooled
10056 UpdateExternalStatus(0);
10058 if (Class $UIDevice = objc_getClass("UIDevice")) {
10059 UIDevice *device([$UIDevice currentDevice]);
10060 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10062 IsWildcat_ = false;
10064 UIScreen *screen([UIScreen mainScreen]);
10065 if ([screen respondsToSelector:@selector(scale)])
10066 ScreenScale_ = [screen scale];
10070 UIDevice *device([UIDevice currentDevice]);
10071 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10072 Idiom_ = @"iphone";
10074 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10075 if (idiom == UIUserInterfaceIdiomPhone)
10076 Idiom_ = @"iphone";
10077 else if (idiom == UIUserInterfaceIdiomPad)
10080 NSLog(@"unknown UIUserInterfaceIdiom!");
10083 SessionData_ = [[NSMutableDictionary alloc] initWithCapacity:4];
10085 HostConfig_ = [[NSObject alloc] init];
10086 @synchronized (HostConfig_) {
10087 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10088 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10091 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
10093 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10095 MobilizedFiles_ = [NSMutableSet setWithObjects:
10096 @"Library/Preferences/com.apple.Accessibility.plist",
10097 @"Library/Preferences/com.apple.preferences.sounds.plist",
10100 /* Library Hacks {{{ */
10101 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10103 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10105 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10106 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10107 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10108 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10111 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10112 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10113 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10114 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10117 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10118 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10119 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10120 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10121 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10124 $NSURLConnection = objc_getClass("NSURLConnection");
10125 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10126 if (NSURLConnection$init$ != NULL) {
10127 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10128 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10131 /* Set Locale {{{ */
10132 Locale_ = CFLocaleCopyCurrent();
10133 Languages_ = [NSLocale preferredLanguages];
10135 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10136 //NSLog(@"%@", [Languages_ description]);
10139 if (Locale_ != NULL)
10140 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10141 else if (Languages_ != nil && [Languages_ count] != 0)
10142 lang = [[Languages_ objectAtIndex:0] UTF8String];
10144 // XXX: consider just setting to C and then falling through?
10147 if (lang != NULL) {
10148 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10149 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10152 NSLog(@"Setting Language: %s", lang);
10154 if (lang != NULL) {
10155 setenv("LANG", lang, true);
10156 std::setlocale(LC_ALL, lang);
10160 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10162 /* Parse Arguments {{{ */
10163 bool substrate(false);
10169 for (int argi(1); argi != argc; ++argi)
10170 if (strcmp(argv[argi], "--") == 0) {
10172 argv[argi] = argv[0];
10178 for (int argi(1); argi != arge; ++argi)
10179 if (strcmp(args[argi], "--substrate") == 0)
10182 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10186 App_ = [[NSBundle mainBundle] bundlePath];
10192 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10193 alloc_ = alloc->method_imp;
10194 alloc->method_imp = (IMP) &Alloc_;*/
10196 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10197 dealloc_ = dealloc->method_imp;
10198 dealloc->method_imp = (IMP) &Dealloc_;*/
10200 /* System Information {{{ */
10204 size = sizeof(maxproc);
10205 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10206 perror("sysctlbyname(\"kern.maxproc\", ?)");
10207 else if (maxproc < 64) {
10209 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10210 perror("sysctlbyname(\"kern.maxproc\", #)");
10213 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10214 char *osversion = new char[size];
10215 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10216 perror("sysctlbyname(\"kern.osversion\", ?)");
10218 System_ = [NSString stringWithUTF8String:osversion];
10220 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10221 char *machine = new char[size];
10222 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10223 perror("sysctlbyname(\"hw.machine\", ?)");
10225 Machine_ = machine;
10227 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
10228 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
10229 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
10230 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
10234 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
10235 NSData *data((NSData *) ecid);
10236 size_t length([data length]);
10237 uint8_t bytes[length];
10238 [data getBytes:bytes];
10239 char string[length * 2 + 1];
10240 for (size_t i(0); i != length; ++i)
10241 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10242 ChipID_ = [NSString stringWithUTF8String:string];
10246 IOObjectRelease(service);
10250 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10252 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10253 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10254 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10256 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10257 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10258 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10260 if (mcc != NULL && mnc != NULL)
10261 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10268 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10269 Build_ = [system objectForKey:@"ProductBuildVersion"];
10270 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10271 Product_ = [info objectForKey:@"SafariProductVersion"];
10272 Safari_ = [info objectForKey:@"CFBundleVersion"];
10275 /* Load Database {{{ */
10277 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10279 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10281 if (Metadata_ == NULL)
10282 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10284 Settings_ = [Metadata_ objectForKey:@"Settings"];
10286 Packages_ = [Metadata_ objectForKey:@"Packages"];
10287 Sections_ = [Metadata_ objectForKey:@"Sections"];
10288 Sources_ = [Metadata_ objectForKey:@"Sources"];
10290 Token_ = [Metadata_ objectForKey:@"Token"];
10293 if (Settings_ != nil)
10294 Role_ = [Settings_ objectForKey:@"Role"];
10296 if (Sections_ == nil) {
10297 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10298 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10301 if (Sources_ == nil) {
10302 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10303 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10308 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10311 if (Packages_ != nil) {
10313 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10317 [Metadata_ removeObjectForKey:@"Packages"];
10323 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10325 #define MobileSubstrate_(name) \
10326 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10327 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10328 if (handle == NULL) \
10329 NSLog(@"%s", dlerror()); \
10332 MobileSubstrate_(Activator)
10333 MobileSubstrate_(libstatusbar)
10334 MobileSubstrate_(SimulatedKeyEvents)
10335 MobileSubstrate_(WinterBoard)
10337 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10338 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10340 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10342 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10343 unlink("/tmp/.cydia.fw");
10345 } else if (access("/User", F_OK) != 0 || version < 4) {
10348 system("/usr/libexec/cydia/firmware.sh");
10352 _assert([[NSFileManager defaultManager]
10353 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10354 withIntermediateDirectories:YES
10359 if (access("/tmp/cydia.chk", F_OK) == 0) {
10360 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10361 _assert(errno == ENOENT);
10362 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10363 _assert(errno == ENOENT);
10366 /* APT Initialization {{{ */
10367 _assert(pkgInitConfig(*_config));
10368 _assert(pkgInitSystem(*_config, _system));
10371 _config->Set("APT::Acquire::Translation", lang);
10373 // XXX: this timeout might be important :(
10374 //_config->Set("Acquire::http::Timeout", 15);
10376 _config->Set("Acquire::http::MaxParallel", 3);
10378 /* Color Choices {{{ */
10379 space_ = CGColorSpaceCreateDeviceRGB();
10381 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10382 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10383 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10384 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10385 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10386 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10387 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10388 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10389 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10391 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10392 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10394 /* UIKit Configuration {{{ */
10395 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10396 if ($GSFontSetUseLegacyFontMetrics != NULL)
10397 $GSFontSetUseLegacyFontMetrics(YES);
10399 // XXX: I have a feeling this was important
10400 //UIKeyboardDisableAutomaticAppearance();
10403 Colon_ = UCLocalize("COLON_DELIMITED");
10404 Elision_ = UCLocalize("ELISION");
10405 Error_ = UCLocalize("ERROR");
10406 Warning_ = UCLocalize("WARNING");
10409 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10411 CGColorSpaceRelease(space_);
10412 CFRelease(Locale_);