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 "CyteKit/UCPlatform.h"
45 #include "CyteKit/CyteLocalize.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 "CyteKit/CyteWebViewController.h"
124 #include "CyteKit/NSString-Cyte.h"
125 #include "CyteKit/PerlCompatibleRegEx.hpp"
126 #include "CyteKit/WebScriptObject-Cyte.h"
128 #include "SDURLCache/SDURLCache.h"
130 #include <CydiaSubstrate/CydiaSubstrate.h>
137 #define _timestamp ({ \
139 gettimeofday(&tv, NULL); \
140 tv.tv_sec * 1000000 + tv.tv_usec; \
143 typedef std::vector<class ProfileTime *> TimeList;
153 ProfileTime(const char *name) :
157 times_.push_back(this);
160 void AddTime(uint64_t time) {
167 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
179 ProfileTimer(ProfileTime &time) :
186 time_.AddTime(_timestamp - start_);
191 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
193 std::cerr << "========" << std::endl;
196 #define _profile(name) { \
197 static ProfileTime name(#name); \
198 ProfileTimer _ ## name(name);
203 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
205 #define CYPoolStart() \
206 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
208 #define CYPoolEnd() \
212 #define Cydia_ CYDIA_VERSION
214 #define lprintf(args...) fprintf(stderr, args)
217 #define TraceLogging (1 && !ForRelease)
218 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
219 #define ProfileTimes (0 && !ForRelease)
220 #define ForSaurik (0 && !ForRelease)
221 #define LogBrowser (0 && !ForRelease)
222 #define TrackResize (0 && !ForRelease)
223 #define ManualRefresh (1 && !ForRelease)
224 #define ShowInternals (0 && !ForRelease)
225 #define AlwaysReload (0 && !ForRelease)
226 #define TryIndexedCollation (0 && !ForRelease)
230 #define _trace(args...)
235 #define _profile(name) {
238 #define PrintTimes() do {} while (false)
241 // Hash Functions/Structures {{{
242 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
250 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
252 static _finline NSString *CydiaURL(NSString *path) {
254 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
255 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
256 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
257 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
258 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
260 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
263 static _finline void UpdateExternalStatus(uint64_t newStatus) {
265 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
266 notify_set_state(notify_token, newStatus);
267 notify_cancel(notify_token);
269 notify_post("com.saurik.Cydia.status");
272 /* [NSObject yieldToSelector:(withObject:)] {{{*/
273 @interface NSObject (Cydia)
274 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
275 - (id) yieldToSelector:(SEL)selector;
278 @implementation NSObject (Cydia)
283 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
284 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
285 id object([[context objectAtIndex:1] nonretainedObjectValue]);
286 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
288 /* XXX: deal with exceptions */
289 id value([self performSelector:selector withObject:object]);
291 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
292 [context removeAllObjects];
293 if ([signature methodReturnLength] != 0 && value != nil)
294 [context addObject:value];
299 performSelectorOnMainThread:@selector(doNothing)
305 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
306 volatile bool stopped(false);
308 NSMutableArray *context([NSMutableArray arrayWithObjects:
309 [NSValue valueWithPointer:selector],
310 [NSValue valueWithNonretainedObject:object],
311 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
314 NSThread *thread([[[NSThread alloc]
316 selector:@selector(_yieldToContext:)
322 NSRunLoop *loop([NSRunLoop currentRunLoop]);
323 NSDate *future([NSDate distantFuture]);
324 NSString *mode([loop currentMode] ?: NSDefaultRunLoopMode);
327 while (!stopped && [loop runMode:mode beforeDate:future]);
330 return [context count] == 0 ? nil : [context objectAtIndex:0];
333 - (id) yieldToSelector:(SEL)selector {
334 return [self yieldToSelector:selector withObject:nil];
340 /* Cydia Alert View {{{ */
341 @interface CYAlertView : UIAlertView {
345 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
349 @implementation CYAlertView
351 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
352 if ((self = [super init]) != nil) {
353 [self setTitle:title];
354 [self setDelegate:self];
355 for (NSString *button in buttons) [self addButtonWithTitle:button];
356 [self setCancelButtonIndex:index];
360 - (void) _updateFrameForDisplay {
361 [super _updateFrameForDisplay];
362 if ([self cancelButtonIndex] == -1) {
363 NSArray *buttons = [self buttons];
364 if ([buttons count]) {
365 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
366 for (UIThreePartButton *button in buttons)
367 [button setBackground:background forState:0];
372 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
373 button_ = buttonIndex + 1;
377 [self dismissWithClickedButtonIndex:-1 animated:YES];
380 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
381 [self setRunsModal:YES];
390 /* NSForcedOrderingSearch doesn't work on the iPhone */
391 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
392 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
393 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
396 typedef uint32_t (*SKRadixFunction)(id, void *);
398 @interface NSMutableArray (Radix)
399 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
407 @implementation NSMutableArray (Radix)
409 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
410 size_t count([self count]);
411 struct RadixItem_ *swap(new RadixItem_[count * 2]);
413 for (size_t i(0); i != count; ++i) {
414 RadixItem_ &item(swap[i]);
417 id object([self objectAtIndex:i]);
418 item.key = function(object, argument);
421 struct RadixItem_ *lhs(swap), *rhs(swap + count);
423 static const size_t width = 32;
424 static const size_t bits = 11;
425 static const size_t slots = 1 << bits;
426 static const size_t passes = (width + (bits - 1)) / bits;
428 size_t *hist(new size_t[slots]);
430 for (size_t pass(0); pass != passes; ++pass) {
431 memset(hist, 0, sizeof(size_t) * slots);
433 for (size_t i(0); i != count; ++i) {
434 uint32_t key(lhs[i].key);
436 key &= _not(uint32_t) >> width - bits;
441 for (size_t i(0); i != slots; ++i) {
442 size_t local(offset);
447 for (size_t i(0); i != count; ++i) {
448 uint32_t key(lhs[i].key);
450 key &= _not(uint32_t) >> width - bits;
451 rhs[hist[key]++] = lhs[i];
454 RadixItem_ *tmp(lhs);
461 const void **values(new const void *[count]);
462 for (size_t i(0); i != count; ++i)
463 values[i] = [self objectAtIndex:lhs[i].index];
464 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
472 /* Insertion Sort {{{ */
474 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
475 const char *ptr = (const char *)list;
477 CFIndex half = count / 2;
478 const char *probe = ptr + elementSize * half;
479 CFComparisonResult cr = comparator(element, probe, context);
480 if (0 == cr) return (probe - (const char *)list) / elementSize;
481 ptr = (cr < 0) ? ptr : probe + elementSize;
482 count = (cr < 0) ? half : (half + (count & 1) - 1);
484 return (ptr - (const char *)list) / elementSize;
487 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
488 const char *ptr = (const char *)list;
490 CFIndex half = count / 2;
491 const char *probe = ptr + elementSize * half;
492 CFComparisonResult cr = comparator(element, probe, context);
493 if (0 == cr) return (probe - (const char *)list) / elementSize;
494 ptr = (cr < 0) ? ptr : probe + elementSize;
495 count = (cr < 0) ? half : (half + (count & 1) - 1);
497 return (ptr - (const char *)list) / elementSize;
500 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
501 if (range.length == 0)
503 const void **values(new const void *[range.length]);
504 CFArrayGetValues(array, range, values);
506 #if HistogramInsertionSort > 0
507 uint32_t total(0), *offsets(new uint32_t[range.length]);
510 for (CFIndex index(1); index != range.length; ++index) {
511 const void *value(values[index]);
512 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
513 CFIndex correct(index);
514 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
515 #if HistogramInsertionSort > 1
516 NSLog(@"%@ < %@", value, values[correct - 1]);
521 if (correct != index) {
522 size_t offset(index - correct);
523 #if HistogramInsertionSort
527 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
529 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
530 values[correct] = value;
534 CFArrayReplaceValues(array, range, values, range.length);
537 #if HistogramInsertionSort > 0
538 for (CFIndex index(0); index != range.length; ++index)
539 if (offsets[index] != 0)
540 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
541 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
548 /* Apple Bug Fixes {{{ */
549 @implementation UIWebDocumentView (Cydia)
551 - (void) _setScrollerOffset:(CGPoint)offset {
552 UIScroller *scroller([self _scroller]);
554 CGSize size([scroller contentSize]);
555 CGSize bounds([scroller bounds].size);
558 max.x = size.width - bounds.width;
559 max.y = size.height - bounds.height;
567 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
568 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
570 [scroller setOffset:offset];
576 @interface NSInvocation (Cydia)
577 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target;
580 @implementation NSInvocation (Cydia)
582 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target {
583 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]]);
584 [invocation setTarget:target];
585 [invocation setSelector:selector];
591 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
592 size_t length([self length] - state->state);
595 else if (length > count)
597 for (size_t i(0); i != length; ++i)
598 objects[i] = [self item:state->state++];
599 state->itemsPtr = objects;
600 state->mutationsPtr = (unsigned long *) self;
604 /* Cydia NSString Additions {{{ */
605 @interface NSString (Cydia)
606 - (NSComparisonResult) compareByPath:(NSString *)other;
607 - (NSString *) stringByCachingURLWithCurrentCDN;
608 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
611 @implementation NSString (Cydia)
613 - (NSComparisonResult) compareByPath:(NSString *)other {
614 NSString *prefix = [self commonPrefixWithString:other options:0];
615 size_t length = [prefix length];
617 NSRange lrange = NSMakeRange(length, [self length] - length);
618 NSRange rrange = NSMakeRange(length, [other length] - length);
620 lrange = [self rangeOfString:@"/" options:0 range:lrange];
621 rrange = [other rangeOfString:@"/" options:0 range:rrange];
623 NSComparisonResult value;
625 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
626 value = NSOrderedSame;
627 else if (lrange.location == NSNotFound)
628 value = NSOrderedAscending;
629 else if (rrange.location == NSNotFound)
630 value = NSOrderedDescending;
632 value = NSOrderedSame;
634 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
635 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
636 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
637 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
639 NSComparisonResult result = [lpath compare:rpath];
640 return result == NSOrderedSame ? value : result;
643 - (NSString *) stringByCachingURLWithCurrentCDN {
645 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
646 withString:@"://cache.cydia.saurik.com/"
650 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
651 return [(id)CFURLCreateStringByAddingPercentEscapes(
656 kCFStringEncodingUTF8
663 /* C++ NSString Wrapper Cache {{{ */
664 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
665 return size == 0 ? NULL :
666 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
667 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
670 static _finline CFStringRef CYStringCreate(const char *data) {
671 return CYStringCreate(data, strlen(data));
680 _finline void clear_() {
681 if (cache_ != NULL) {
688 _finline bool empty() const {
692 _finline size_t size() const {
696 _finline char *data() const {
700 _finline void clear() {
705 _finline CYString() :
712 _finline ~CYString() {
716 void operator =(const CYString &rhs) {
720 if (rhs.cache_ == nil)
723 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
726 void copy(apr_pool_t *pool) {
727 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
728 memcpy(temp, data_, size_);
733 void set(apr_pool_t *pool, const char *data, size_t size) {
739 data_ = const_cast<char *>(data);
747 _finline void set(apr_pool_t *pool, const char *data) {
748 set(pool, data, data == NULL ? 0 : strlen(data));
751 _finline void set(apr_pool_t *pool, const std::string &rhs) {
752 set(pool, rhs.data(), rhs.size());
755 bool operator ==(const CYString &rhs) const {
756 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
759 _finline operator CFStringRef() {
761 cache_ = CYStringCreate(data_, size_);
765 _finline operator id() {
766 return (NSString *) static_cast<CFStringRef>(*this);
769 _finline operator const char *() {
770 return reinterpret_cast<const char *>(data_);
774 /* C++ NSString Algorithm Adapters {{{ */
776 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
779 struct NSStringMapHash :
780 std::unary_function<NSString *, size_t>
782 _finline size_t operator ()(NSString *value) const {
783 return CFStringHashNSString((CFStringRef) value);
787 struct NSStringMapLess :
788 std::binary_function<NSString *, NSString *, bool>
790 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
791 return [lhs compare:rhs] == NSOrderedAscending;
795 struct NSStringMapEqual :
796 std::binary_function<NSString *, NSString *, bool>
798 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
799 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
800 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
801 //[lhs isEqualToString:rhs];
806 /* Mime Addresses {{{ */
807 @interface Address : NSObject {
813 - (NSString *) address;
815 - (void) setAddress:(NSString *)address;
817 + (Address *) addressWithString:(NSString *)string;
818 - (Address *) initWithString:(NSString *)string;
822 @implementation Address
831 - (NSString *) name {
835 - (NSString *) address {
839 - (void) setAddress:(NSString *)address {
841 [address_ autorelease];
845 address_ = [address retain];
848 + (Address *) addressWithString:(NSString *)string {
849 return [[[Address alloc] initWithString:string] autorelease];
852 + (NSArray *) _attributeKeys {
853 return [NSArray arrayWithObjects:
859 - (NSArray *) attributeKeys {
860 return [[self class] _attributeKeys];
863 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
864 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
867 - (Address *) initWithString:(NSString *)string {
868 if ((self = [super init]) != nil) {
869 const char *data = [string UTF8String];
870 size_t size = [string length];
872 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
874 if (address_r(data, size)) {
875 name_ = [address_r[1] retain];
876 address_ = [address_r[2] retain];
878 name_ = [string retain];
886 /* CoreGraphics Primitives {{{ */
891 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
892 CGFloat color[] = {red, green, blue, alpha};
893 return CGColorCreate(space, color);
902 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
903 color_(Create_(space, red, green, blue, alpha))
905 Set(space, red, green, blue, alpha);
910 CGColorRelease(color_);
917 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
919 color_ = Create_(space, red, green, blue, alpha);
922 operator CGColorRef() {
928 /* Random Global Variables {{{ */
929 static const int PulseInterval_ = 50000;
931 static const NSString *UI_;
934 static bool RestartSubstrate_;
935 static NSArray *Finishes_;
937 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
938 #define NotifyConfig_ "/etc/notify.conf"
940 static bool Queuing_;
942 static CYColor Blue_;
943 static CYColor Blueish_;
944 static CYColor Black_;
946 static CYColor White_;
947 static CYColor Gray_;
948 static CYColor Green_;
949 static CYColor Purple_;
950 static CYColor Purplish_;
952 static UIColor *InstallingColor_;
953 static UIColor *RemovingColor_;
955 static NSString *App_;
957 static BOOL Advanced_;
958 static BOOL Ignored_;
960 static UIFont *Font12_;
961 static UIFont *Font12Bold_;
962 static UIFont *Font14_;
963 static UIFont *Font18Bold_;
964 static UIFont *Font22Bold_;
966 static const char *Machine_ = NULL;
967 static NSString *System_ = nil;
968 static NSString *SerialNumber_ = nil;
969 static NSString *ChipID_ = nil;
970 static _H<NSString> Token_;
971 static NSString *UniqueID_ = nil;
972 static NSString *PLMN_ = nil;
973 static NSString *Build_ = nil;
974 static NSString *Product_ = nil;
975 static NSString *Safari_ = nil;
977 static CFLocaleRef Locale_;
978 static NSArray *Languages_;
979 static CGColorSpaceRef space_;
981 static NSDictionary *SectionMap_;
982 static NSMutableDictionary *Metadata_;
983 static _transient NSMutableDictionary *Settings_;
984 static _transient NSString *Role_;
985 static _transient NSMutableDictionary *Packages_;
986 static _transient NSMutableDictionary *Sections_;
987 static _transient NSMutableDictionary *Sources_;
988 static bool Changed_;
992 static CGFloat ScreenScale_;
993 static NSString *Idiom_;
995 static NSMutableDictionary *SessionData_;
996 static NSObject *HostConfig_;
997 static NSMutableSet *BridgedHosts_;
998 static NSMutableSet *PipelinedHosts_;
1000 static NSString *kCydiaProgressEventTypeError = @"Error";
1001 static NSString *kCydiaProgressEventTypeInformation = @"Information";
1002 static NSString *kCydiaProgressEventTypeStatus = @"Status";
1003 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
1006 /* Display Helpers {{{ */
1007 inline float Interpolate(float begin, float end, float fraction) {
1008 return (end - begin) * fraction + begin;
1011 static _finline const char *StripVersion_(const char *version) {
1012 const char *colon(strchr(version, ':'));
1013 return colon == NULL ? version : colon + 1;
1016 NSString *LocalizeSection(NSString *section) {
1017 static Pcre title_r("^(.*?) \\((.*)\\)$");
1018 if (title_r(section)) {
1019 NSString *parent(title_r[1]);
1020 NSString *child(title_r[2]);
1022 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1023 LocalizeSection(parent),
1024 LocalizeSection(child)
1028 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1031 NSString *Simplify(NSString *title) {
1032 const char *data = [title UTF8String];
1033 size_t size = [title length];
1035 static Pcre square_r("^\\[(.*)\\]$");
1036 if (square_r(data, size))
1037 return Simplify(square_r[1]);
1039 static Pcre paren_r("^\\((.*)\\)$");
1040 if (paren_r(data, size))
1041 return Simplify(paren_r[1]);
1043 static Pcre title_r("^(.*?) \\((.*)\\)$");
1044 if (title_r(data, size))
1045 return Simplify(title_r[1]);
1051 NSString *GetLastUpdate() {
1052 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1055 return UCLocalize("NEVER_OR_UNKNOWN");
1057 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1058 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1060 CFRelease(formatter);
1062 return [(NSString *) formatted autorelease];
1065 bool isSectionVisible(NSString *section) {
1066 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1067 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1068 return hidden == nil || ![hidden boolValue];
1073 /* Delegate Prototypes {{{ */
1076 @class CydiaProgressEvent;
1078 @protocol DatabaseDelegate
1079 - (void) repairWithSelector:(SEL)selector;
1080 - (void) setConfigurationData:(NSString *)data;
1081 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
1084 @class CYPackageController;
1086 @protocol CydiaDelegate
1087 - (void) retainNetworkActivityIndicator;
1088 - (void) releaseNetworkActivityIndicator;
1089 - (void) clearPackage:(Package *)package;
1090 - (void) installPackage:(Package *)package;
1091 - (void) installPackages:(NSArray *)packages;
1092 - (void) removePackage:(Package *)package;
1093 - (void) beginUpdate;
1095 - (void) distUpgrade;
1097 - (void) updateData;
1099 - (void) addTrivialSource:(NSString *)href;
1100 - (void) showSettings;
1101 - (UIProgressHUD *) addProgressHUD;
1102 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1103 - (CYViewController *) pageForPackage:(NSString *)name;
1104 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1105 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1109 /* ProgressEvent Interface/Delegate {{{ */
1110 @interface CydiaProgressEvent : NSObject {
1111 _H<NSString> message_;
1115 _H<NSString> package_;
1117 _H<NSString> version_;
1120 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type;
1121 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package;
1122 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item;
1124 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type;
1126 - (NSString *) message;
1127 - (NSString *) type;
1130 - (NSString *) package;
1132 - (NSString *) version;
1134 - (void) setItem:(NSArray *)item;
1135 - (void) setPackage:(NSString *)package;
1136 - (void) setURL:(NSString *)url;
1137 - (void) setVersion:(NSString *)version;
1139 - (NSString *) compound:(NSString *)value;
1140 - (NSString *) compoundMessage;
1141 - (NSString *) compoundTitle;
1145 @protocol ProgressDelegate
1146 - (void) addProgressEvent:(CydiaProgressEvent *)event;
1147 - (void) setProgressPercent:(NSNumber *)percent;
1148 - (void) setProgressStatus:(NSDictionary *)status;
1149 - (void) setProgressCancellable:(NSNumber *)cancellable;
1150 - (bool) isProgressCancelled;
1151 - (void) setTitle:(NSString *)title;
1154 /* Status Delegation {{{ */
1156 public pkgAcquireStatus
1159 _transient NSObject<ProgressDelegate> *delegate_;
1169 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1170 delegate_ = delegate;
1173 NSObject<ProgressDelegate> *getDelegate() const {
1177 virtual bool MediaChange(std::string media, std::string drive) {
1181 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1184 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1185 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1186 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
1187 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1190 virtual void Done(pkgAcquire::ItemDesc &item) {
1193 virtual void Fail(pkgAcquire::ItemDesc &item) {
1195 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1196 item.Owner->Status == pkgAcquire::Item::StatDone
1200 std::string &error(item.Owner->ErrorText);
1204 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
1205 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1208 virtual bool Pulse(pkgAcquire *Owner) {
1209 bool value = pkgAcquireStatus::Pulse(Owner);
1212 double(CurrentBytes + CurrentItems) /
1213 double(TotalBytes + TotalItems)
1216 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1217 [NSNumber numberWithDouble:percent], @"Percent",
1219 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1220 [NSNumber numberWithDouble:TotalBytes], @"Total",
1221 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1222 nil] waitUntilDone:YES];
1224 if (value && ![delegate_ isProgressCancelled])
1232 _finline bool WasCancelled() const {
1236 virtual void Start() {
1237 pkgAcquireStatus::Start();
1238 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1241 virtual void Stop() {
1242 pkgAcquireStatus::Stop();
1243 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1244 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1248 /* Database Interface {{{ */
1249 typedef std::map< unsigned long, _H<Source> > SourceMap;
1251 @interface Database : NSObject {
1257 pkgCacheFile cache_;
1258 pkgDepCache::Policy *policy_;
1259 pkgRecords *records_;
1260 pkgProblemResolver *resolver_;
1261 pkgAcquire *fetcher_;
1263 SPtr<pkgPackageManager> manager_;
1264 pkgSourceList *list_;
1266 SourceMap sourceMap_;
1267 NSMutableArray *sourceList_;
1269 CFMutableArrayRef packages_;
1271 _transient NSObject<DatabaseDelegate> *delegate_;
1272 _transient NSObject<ProgressDelegate> *progress_;
1280 std::map<const char *, _H<NSString> > sections_;
1283 + (Database *) sharedInstance;
1286 - (void) _readCydia:(NSNumber *)fd;
1287 - (void) _readStatus:(NSNumber *)fd;
1288 - (void) _readOutput:(NSNumber *)fd;
1292 - (Package *) packageWithName:(NSString *)name;
1294 - (pkgCacheFile &) cache;
1295 - (pkgDepCache::Policy *) policy;
1296 - (pkgRecords *) records;
1297 - (pkgProblemResolver *) resolver;
1298 - (pkgAcquire &) fetcher;
1299 - (pkgSourceList &) list;
1300 - (NSArray *) packages;
1301 - (NSArray *) sources;
1302 - (Source *) sourceWithKey:(NSString *)key;
1303 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1311 - (void) updateWithStatus:(Status &)status;
1313 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1315 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1316 - (NSObject<ProgressDelegate> *) progressDelegate;
1318 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1320 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1324 /* ProgressEvent Implementation {{{ */
1325 @implementation CydiaProgressEvent
1327 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1328 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1331 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1332 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1333 [event setPackage:package];
1337 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1338 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1340 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1341 NSArray *fields([description componentsSeparatedByString:@" "]);
1342 [event setItem:fields];
1344 if ([fields count] > 3) {
1345 [event setPackage:[fields objectAtIndex:2]];
1346 [event setVersion:[fields objectAtIndex:3]];
1349 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1354 + (NSArray *) _attributeKeys {
1355 return [NSArray arrayWithObjects:
1365 - (NSArray *) attributeKeys {
1366 return [[self class] _attributeKeys];
1369 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1370 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1373 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1374 if ((self = [super init]) != nil) {
1380 - (NSString *) message {
1384 - (NSString *) type {
1388 - (NSArray *) item {
1389 return (id) item_ ?: [NSNull null];
1392 - (void) setItem:(NSArray *)item {
1396 - (NSString *) package {
1397 return (id) package_ ?: [NSNull null];
1400 - (void) setPackage:(NSString *)package {
1404 - (NSString *) url {
1405 return (id) url_ ?: [NSNull null];
1408 - (void) setURL:(NSString *)url {
1412 - (void) setVersion:(NSString *)version {
1416 - (NSString *) version {
1417 return (id) version_ ?: [NSNull null];
1420 - (NSString *) compound:(NSString *)value {
1422 NSString *mode(nil); {
1423 NSString *type([self type]);
1424 if ([type isEqualToString:kCydiaProgressEventTypeError])
1425 mode = UCLocalize("ERROR");
1426 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1427 mode = UCLocalize("WARNING");
1431 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1437 - (NSString *) compoundMessage {
1438 return [self compound:[self message]];
1441 - (NSString *) compoundTitle {
1444 if (package_ == nil)
1446 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1447 title = [package name];
1451 return [self compound:title];
1457 // Cytore Definitions {{{
1458 struct PackageValue :
1461 Cytore::Offset<PackageValue> next_;
1463 uint32_t index_ : 23;
1464 uint32_t subscribed_ : 1;
1481 Cytore::Offset<PackageValue> packages_[1 << 16];
1484 static Cytore::File<MetaValue> MetaFile_;
1486 // Cytore Helper Functions {{{
1487 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1488 SplitHash nhash = { hashlittle(name, length) };
1490 PackageValue *metadata;
1492 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1493 offset: if (offset->IsNull()) {
1494 *offset = MetaFile_.New<PackageValue>(length + 1);
1495 metadata = &MetaFile_.Get(*offset);
1497 if (metadata == NULL) {
1501 metadata = new PackageValue();
1502 memset(metadata, 0, sizeof(*metadata));
1505 memcpy(metadata->name_, name, length + 1);
1506 metadata->nhash_ = nhash.u16[1];
1508 metadata = &MetaFile_.Get(*offset);
1510 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1511 offset = &metadata->next_;
1519 static void PackageImport(const void *key, const void *value, void *context) {
1520 bool &fail(*reinterpret_cast<bool *>(context));
1523 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1524 NSLog(@"failed to import package %@", key);
1528 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1529 NSDictionary *package((NSDictionary *) value);
1531 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1532 if ([subscribed boolValue] && !metadata->subscribed_)
1533 metadata->subscribed_ = true;
1535 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1536 time_t time([date timeIntervalSince1970]);
1537 if (metadata->first_ > time || metadata->first_ == 0)
1538 metadata->first_ = time;
1541 NSDate *date([package objectForKey:@"LastSeen"]);
1542 NSString *version([package objectForKey:@"LastVersion"]);
1544 if (date != nil && version != nil) {
1545 time_t time([date timeIntervalSince1970]);
1546 if (metadata->last_ < time || metadata->last_ == 0)
1547 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1548 size_t length(strlen(buffer));
1549 uint16_t vhash(hashlittle(buffer, length));
1551 size_t capped(std::min<size_t>(8, length));
1552 char *latest(buffer + length - capped);
1554 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1555 metadata->vhash_ = vhash;
1557 metadata->last_ = time;
1563 /* Source Class {{{ */
1564 @interface Source : NSObject {
1565 CYString depiction_;
1566 CYString description_;
1572 CYString distribution_;
1577 _H<NSString> authority_;
1579 CYString defaultIcon_;
1581 _H<NSDictionary> record_;
1585 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1587 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1589 - (NSString *) depictionForPackage:(NSString *)package;
1590 - (NSString *) supportForPackage:(NSString *)package;
1592 - (NSDictionary *) record;
1596 - (NSString *) distribution;
1597 - (NSString *) type;
1599 - (NSString *) host;
1601 - (NSString *) name;
1602 - (NSString *) shortDescription;
1603 - (NSString *) label;
1604 - (NSString *) origin;
1605 - (NSString *) version;
1607 - (NSString *) defaultIcon;
1611 @implementation Source
1615 distribution_.clear();
1618 description_.clear();
1624 defaultIcon_.clear();
1632 // XXX: this is a very inefficient way to call these deconstructors
1637 + (NSArray *) _attributeKeys {
1638 return [NSArray arrayWithObjects:
1645 @"shortDescription",
1653 - (NSArray *) attributeKeys {
1654 return [[self class] _attributeKeys];
1657 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1658 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1661 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1664 trusted_ = index->IsTrusted();
1666 uri_.set(pool, index->GetURI());
1667 distribution_.set(pool, index->GetDist());
1668 type_.set(pool, index->GetType());
1670 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1671 if (dindex != NULL) {
1673 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1676 pkgTagFile tags(&fd);
1678 pkgTagSection section;
1685 {"default-icon", &defaultIcon_},
1686 {"depiction", &depiction_},
1687 {"description", &description_},
1689 {"origin", &origin_},
1690 {"support", &support_},
1691 {"version", &version_},
1694 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1695 const char *start, *end;
1697 if (section.Find(names[i].name_, start, end)) {
1698 CYString &value(*names[i].value_);
1699 value.set(pool, start, end - start);
1705 record_ = [Sources_ objectForKey:[self key]];
1707 NSURL *url([NSURL URLWithString:uri_]);
1711 host_ = [host_ lowercaseString];
1714 // XXX: this is due to a bug in _H<>
1715 authority_ = (id) host_;
1717 authority_ = [url path];
1720 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1721 if ((self = [super init]) != nil) {
1722 [self setMetaIndex:index inPool:pool];
1726 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1727 NSDictionary *lhr = [self record];
1728 NSDictionary *rhr = [source record];
1731 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1733 NSString *lhs = [self name];
1734 NSString *rhs = [source name];
1736 if ([lhs length] != 0 && [rhs length] != 0) {
1737 unichar lhc = [lhs characterAtIndex:0];
1738 unichar rhc = [rhs characterAtIndex:0];
1740 if (isalpha(lhc) && !isalpha(rhc))
1741 return NSOrderedAscending;
1742 else if (!isalpha(lhc) && isalpha(rhc))
1743 return NSOrderedDescending;
1746 return [lhs compare:rhs options:LaxCompareOptions_];
1749 - (NSString *) depictionForPackage:(NSString *)package {
1750 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1753 - (NSString *) supportForPackage:(NSString *)package {
1754 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1757 - (NSDictionary *) record {
1765 - (NSString *) uri {
1769 - (NSString *) distribution {
1770 return distribution_;
1773 - (NSString *) type {
1777 - (NSString *) key {
1778 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1781 - (NSString *) host {
1785 - (NSString *) name {
1786 return origin_.empty() ? (id) authority_ : origin_;
1789 - (NSString *) shortDescription {
1790 return description_;
1793 - (NSString *) label {
1794 return label_.empty() ? (id) authority_ : label_;
1797 - (NSString *) origin {
1801 - (NSString *) version {
1805 - (NSString *) defaultIcon {
1806 return defaultIcon_;
1811 /* CydiaOperation Class {{{ */
1812 @interface CydiaOperation : NSObject {
1813 NSString *operator_;
1817 - (NSString *) operator;
1818 - (NSString *) value;
1822 @implementation CydiaOperation
1825 [operator_ release];
1830 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1831 if ((self = [super init]) != nil) {
1832 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1833 value_ = [[NSString alloc] initWithUTF8String:value];
1837 + (NSArray *) _attributeKeys {
1838 return [NSArray arrayWithObjects:
1844 - (NSArray *) attributeKeys {
1845 return [[self class] _attributeKeys];
1848 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1849 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1852 - (NSString *) operator {
1856 - (NSString *) value {
1862 /* CydiaClause Class {{{ */
1863 @interface CydiaClause : NSObject {
1865 CydiaOperation *version_;
1868 - (NSString *) package;
1869 - (CydiaOperation *) version;
1873 @implementation CydiaClause
1881 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1882 if ((self = [super init]) != nil) {
1883 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1885 if (const char *version = dep.TargetVer())
1886 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1888 version_ = [[NSNull null] retain];
1892 + (NSArray *) _attributeKeys {
1893 return [NSArray arrayWithObjects:
1899 - (NSArray *) attributeKeys {
1900 return [[self class] _attributeKeys];
1903 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1904 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1907 - (NSString *) package {
1911 - (CydiaOperation *) version {
1917 /* CydiaRelation Class {{{ */
1918 @interface CydiaRelation : NSObject {
1919 NSString *relationship_;
1920 NSMutableArray *clauses_;
1923 - (NSString *) relationship;
1924 - (NSArray *) clauses;
1928 @implementation CydiaRelation
1931 [relationship_ release];
1936 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1937 if ((self = [super init]) != nil) {
1938 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
1939 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
1941 pkgCache::DepIterator start;
1942 pkgCache::DepIterator end;
1943 dep.GlobOr(start, end); // ++dep
1946 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1948 // yes, seriously. (wtf?)
1956 + (NSArray *) _attributeKeys {
1957 return [NSArray arrayWithObjects:
1963 - (NSArray *) attributeKeys {
1964 return [[self class] _attributeKeys];
1967 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1968 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1971 - (NSString *) relationship {
1972 return relationship_;
1975 - (NSArray *) clauses {
1979 - (void) addClause:(CydiaClause *)clause {
1980 [clauses_ addObject:clause];
1985 /* Package Class {{{ */
1986 struct ParsedPackage {
1991 CYString depiction_;
2001 @interface Package : NSObject {
2004 uint32_t essential_ : 1;
2005 uint32_t obsolete_ : 1;
2006 uint32_t ignored_ : 1;
2010 _transient Database *database_;
2012 pkgCache::VerIterator version_;
2013 pkgCache::PkgIterator iterator_;
2014 pkgCache::VerFileIterator file_;
2020 CYString installed_;
2022 const char *section_;
2023 _transient NSString *section$_;
2027 PackageValue *metadata_;
2028 ParsedPackage *parsed_;
2030 NSMutableArray *tags_;
2033 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2034 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2036 - (pkgCache::PkgIterator) iterator;
2039 - (NSString *) section;
2040 - (NSString *) simpleSection;
2042 - (NSString *) longSection;
2043 - (NSString *) shortSection;
2047 - (Address *) maintainer;
2049 - (NSString *) longDescription;
2050 - (NSString *) shortDescription;
2053 - (PackageValue *) metadata;
2056 - (bool) subscribed;
2057 - (bool) setSubscribed:(bool)subscribed;
2061 - (NSString *) latest;
2062 - (NSString *) installed;
2063 - (BOOL) uninstalled;
2066 - (BOOL) upgradableAndEssential:(BOOL)essential;
2069 - (BOOL) unfiltered;
2073 - (BOOL) halfConfigured;
2074 - (BOOL) halfInstalled;
2076 - (NSString *) mode;
2079 - (NSString *) name;
2081 - (NSString *) homepage;
2082 - (NSString *) depiction;
2083 - (Address *) author;
2085 - (NSString *) support;
2087 - (NSArray *) files;
2088 - (NSArray *) warnings;
2089 - (NSArray *) applications;
2091 - (Source *) source;
2093 - (BOOL) matches:(NSString *)text;
2095 - (bool) hasSupportingRole;
2096 - (BOOL) hasTag:(NSString *)tag;
2097 - (NSString *) primaryPurpose;
2098 - (NSArray *) purposes;
2099 - (bool) isCommercial;
2101 - (void) setIndex:(size_t)index;
2103 - (CYString &) cyname;
2105 - (uint32_t) compareBySection:(NSArray *)sections;
2110 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2111 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2112 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2113 - (bool) isVisibleInSection:(NSString *)section;
2114 - (bool) isVisibleInSource:(Source *)source;
2118 uint32_t PackageChangesRadix(Package *self, void *) {
2123 uint32_t timestamp : 30;
2124 uint32_t ignored : 1;
2125 uint32_t upgradable : 1;
2129 bool upgradable([self upgradableAndEssential:YES]);
2130 value.bits.upgradable = upgradable ? 1 : 0;
2133 value.bits.timestamp = 0;
2134 value.bits.ignored = [self ignored] ? 0 : 1;
2135 value.bits.upgradable = 1;
2137 value.bits.timestamp = [self seen] >> 2;
2138 value.bits.ignored = 0;
2139 value.bits.upgradable = 0;
2142 return _not(uint32_t) - value.key;
2145 uint32_t PackagePrefixRadix(Package *self, void *context) {
2146 size_t offset(reinterpret_cast<size_t>(context));
2147 CYString &name([self cyname]);
2149 size_t size(name.size());
2152 char *text(name.data());
2155 if (!isdigit(text[0]))
2159 while (size != digits && isdigit(text[digits]))
2167 if (offset == 0 && zeros != 0) {
2168 memset(data, '0', zeros);
2169 memcpy(data + zeros, text, 4 - zeros);
2171 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2172 if (size <= offset - zeros)
2175 text += offset - zeros;
2176 size -= offset - zeros;
2179 memcpy(data, text, 4);
2181 memcpy(data, text, size);
2182 memset(data + size, 0, 4 - size);
2185 for (size_t i(0); i != 4; ++i)
2186 if (isalpha(data[i]))
2194 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2196 /* XXX: ntohl may be more honest */
2197 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2200 CYString &(*PackageName)(Package *self, SEL sel);
2202 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2203 _profile(PackageNameCompare)
2204 CYString &lhi(PackageName(lhs, @selector(cyname)));
2205 CYString &rhi(PackageName(rhs, @selector(cyname)));
2206 CFStringRef lhn(lhi), rhn(rhi);
2209 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2210 else if (rhn == NULL)
2211 return NSOrderedDescending;
2213 _profile(PackageNameCompare$NumbersLast)
2214 if (!lhi.empty() && !rhi.empty()) {
2215 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2216 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2217 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2218 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2219 return lha ? NSOrderedAscending : NSOrderedDescending;
2223 CFIndex length = CFStringGetLength(lhn);
2225 _profile(PackageNameCompare$Compare)
2226 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2231 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2232 return PackageNameCompare(*lhs, *rhs, context);
2235 struct PackageNameOrdering :
2236 std::binary_function<Package *, Package *, bool>
2238 _finline bool operator ()(Package *lhs, Package *rhs) const {
2239 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2243 @implementation Package
2245 - (NSString *) description {
2246 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2250 if (parsed_ != NULL)
2259 + (NSString *) webScriptNameForSelector:(SEL)selector {
2261 else if (selector == @selector(clear))
2263 else if (selector == @selector(getField:))
2265 else if (selector == @selector(hasTag:))
2267 else if (selector == @selector(install))
2269 else if (selector == @selector(remove))
2275 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2276 return [self webScriptNameForSelector:selector] == nil;
2279 + (NSArray *) _attributeKeys {
2280 return [NSArray arrayWithObjects:
2299 @"shortDescription",
2312 - (NSArray *) attributeKeys {
2313 return [[self class] _attributeKeys];
2316 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2317 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2320 - (NSArray *) relations {
2321 @synchronized (database_) {
2322 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2323 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2324 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2328 - (NSString *) getField:(NSString *)name {
2329 @synchronized (database_) {
2330 if ([database_ era] != era_ || file_.end())
2333 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2335 const char *start, *end;
2336 if (!parser.Find([name UTF8String], start, end))
2337 return (NSString *) [NSNull null];
2339 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2343 if (parsed_ != NULL)
2345 @synchronized (database_) {
2346 if ([database_ era] != era_ || file_.end())
2349 ParsedPackage *parsed(new ParsedPackage);
2352 _profile(Package$parse)
2353 pkgRecords::Parser *parser;
2355 _profile(Package$parse$Lookup)
2356 parser = &[database_ records]->Lookup(file_);
2361 _profile(Package$parse$Find)
2366 {"icon", &parsed->icon_},
2367 {"depiction", &parsed->depiction_},
2368 {"homepage", &parsed->homepage_},
2369 {"website", &website},
2370 {"bugs", &parsed->bugs_},
2371 {"support", &parsed->support_},
2372 {"sponsor", &parsed->sponsor_},
2373 {"author", &parsed->author_},
2376 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2377 const char *start, *end;
2379 if (parser->Find(names[i].name_, start, end)) {
2380 CYString &value(*names[i].value_);
2381 _profile(Package$parse$Value)
2382 value.set(pool_, start, end - start);
2388 _profile(Package$parse$Tagline)
2389 const char *start, *end;
2390 if (parser->ShortDesc(start, end)) {
2391 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2394 while (stop != start && stop[-1] == '\r')
2396 parsed->tagline_.set(pool_, start, stop - start);
2400 _profile(Package$parse$Retain)
2401 if (parsed->homepage_.empty())
2402 parsed->homepage_ = website;
2403 if (parsed->homepage_ == parsed->depiction_)
2404 parsed->homepage_.clear();
2409 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2410 if ((self = [super init]) != nil) {
2411 _profile(Package$initWithVersion)
2414 database_ = database;
2415 era_ = [database era];
2419 pkgCache::PkgIterator iterator(version.ParentPkg());
2420 iterator_ = iterator;
2422 _profile(Package$initWithVersion$Version)
2423 if (!version_.end())
2424 file_ = version_.FileList();
2426 pkgCache &cache([database_ cache]);
2427 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2431 _profile(Package$initWithVersion$Cache)
2432 name_.set(NULL, iterator.Display());
2434 latest_.set(NULL, StripVersion_(version_.VerStr()));
2436 pkgCache::VerIterator current(iterator.CurrentVer());
2438 installed_.set(NULL, StripVersion_(current.VerStr()));
2441 _profile(Package$initWithVersion$Tags)
2442 pkgCache::TagIterator tag(iterator.TagList());
2444 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2446 const char *name(tag.Name());
2447 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2449 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2450 if (strcmp(name + 6, "enduser") == 0)
2452 else if (strcmp(name + 6, "hacker") == 0)
2454 else if (strcmp(name + 6, "developer") == 0)
2456 else if (strcmp(name + 6, "cydia") == 0)
2462 if (strncmp(name, "cydia::", 7) == 0) {
2463 if (strcmp(name + 7, "essential") == 0)
2465 else if (strcmp(name + 7, "obsolete") == 0)
2470 } while (!tag.end());
2474 _profile(Package$initWithVersion$Metadata)
2475 const char *mixed(iterator.Name());
2476 size_t size(strlen(mixed));
2477 char lower[size + 1];
2479 for (size_t i(0); i != size; ++i)
2480 lower[i] = mixed[i] | 0x20;
2483 PackageValue *metadata(PackageFind(lower, size));
2484 metadata_ = metadata;
2486 id_.set(NULL, metadata->name_, size);
2488 const char *latest(version_.VerStr());
2489 size_t length(strlen(latest));
2491 uint16_t vhash(hashlittle(latest, length));
2493 size_t capped(std::min<size_t>(8, length));
2494 latest = latest + length - capped;
2496 if (metadata->first_ == 0)
2497 metadata->first_ = now_;
2499 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2500 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2501 metadata->vhash_ = vhash;
2502 metadata->last_ = now_;
2503 } else if (metadata->last_ == 0)
2504 metadata->last_ = metadata->first_;
2507 _profile(Package$initWithVersion$Section)
2508 section_ = iterator.Section();
2511 _profile(Package$initWithVersion$Flags)
2512 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2513 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2518 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2519 pkgCache::VerIterator version;
2521 _profile(Package$packageWithIterator$GetCandidateVer)
2522 version = [database policy]->GetCandidateVer(iterator);
2530 _profile(Package$packageWithIterator$Allocate)
2531 package = [Package allocWithZone:zone];
2534 _profile(Package$packageWithIterator$Initialize)
2536 initWithVersion:version
2543 _profile(Package$packageWithIterator$Autorelease)
2544 package = [package autorelease];
2550 - (pkgCache::PkgIterator) iterator {
2554 - (NSString *) section {
2555 if (section$_ == nil) {
2556 if (section_ == NULL)
2559 _profile(Package$section$mappedSectionForPointer)
2560 section$_ = [database_ mappedSectionForPointer:section_];
2565 - (NSString *) simpleSection {
2566 if (NSString *section = [self section])
2567 return Simplify(section);
2572 - (NSString *) longSection {
2573 return LocalizeSection([self section]);
2576 - (NSString *) shortSection {
2577 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2580 - (NSString *) uri {
2583 pkgIndexFile *index;
2584 pkgCache::PkgFileIterator file(file_.File());
2585 if (![database_ list].FindIndex(file, index))
2587 return [NSString stringWithUTF8String:iterator_->Path];
2588 //return [NSString stringWithUTF8String:file.Site()];
2589 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2593 - (Address *) maintainer {
2594 @synchronized (database_) {
2595 if ([database_ era] != era_ || file_.end())
2598 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2599 const std::string &maintainer(parser->Maintainer());
2600 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2604 @synchronized (database_) {
2605 if ([database_ era] != era_ || version_.end())
2608 return version_->InstalledSize;
2611 - (NSString *) longDescription {
2612 @synchronized (database_) {
2613 if ([database_ era] != era_ || file_.end())
2616 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2617 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2619 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2620 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2621 if ([lines count] < 2)
2624 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2625 for (size_t i(1), e([lines count]); i != e; ++i) {
2626 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2627 [trimmed addObject:trim];
2630 return [trimmed componentsJoinedByString:@"\n"];
2633 - (NSString *) shortDescription {
2634 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2638 _profile(Package$index)
2639 CFStringRef name((CFStringRef) [self name]);
2640 if (CFStringGetLength(name) == 0)
2642 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2643 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2645 return toupper(character);
2649 - (PackageValue *) metadata {
2654 PackageValue *metadata([self metadata]);
2655 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2658 - (bool) subscribed {
2659 return [self metadata]->subscribed_;
2662 - (bool) setSubscribed:(bool)subscribed {
2663 PackageValue *metadata([self metadata]);
2664 if (metadata->subscribed_ == subscribed)
2666 metadata->subscribed_ = subscribed;
2674 - (NSString *) latest {
2678 - (NSString *) installed {
2682 - (BOOL) uninstalled {
2683 return installed_.empty();
2687 return !version_.end();
2690 - (BOOL) upgradableAndEssential:(BOOL)essential {
2691 _profile(Package$upgradableAndEssential)
2692 pkgCache::VerIterator current(iterator_.CurrentVer());
2694 return essential && essential_;
2696 return !version_.end() && version_ != current;
2700 - (BOOL) essential {
2705 return [database_ cache][iterator_].InstBroken();
2708 - (BOOL) unfiltered {
2709 _profile(Package$unfiltered$obsolete)
2710 if (_unlikely(obsolete_))
2714 _profile(Package$unfiltered$hasSupportingRole)
2715 if (_unlikely(![self hasSupportingRole]))
2723 if (![self unfiltered])
2728 _profile(Package$visible$section)
2729 section = [self section];
2732 _profile(Package$visible$isSectionVisible)
2733 if (!isSectionVisible(section))
2741 unsigned char current(iterator_->CurrentState);
2742 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2745 - (BOOL) halfConfigured {
2746 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2749 - (BOOL) halfInstalled {
2750 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2754 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2755 return state.Mode != pkgDepCache::ModeKeep;
2758 - (NSString *) mode {
2759 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2761 switch (state.Mode) {
2762 case pkgDepCache::ModeDelete:
2763 if ((state.iFlags & pkgDepCache::Purge) != 0)
2767 case pkgDepCache::ModeKeep:
2768 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2769 return @"REINSTALL";
2770 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2774 case pkgDepCache::ModeInstall:
2775 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2776 return @"REINSTALL";
2777 else*/ switch (state.Status) {
2779 return @"DOWNGRADE";
2785 return @"NEW_INSTALL";
2796 - (NSString *) name {
2797 return name_.empty() ? id_ : name_;
2800 - (UIImage *) icon {
2801 NSString *section = [self simpleSection];
2804 if (parsed_ != NULL)
2805 if (NSString *href = parsed_->icon_)
2806 if ([href hasPrefix:@"file:///"])
2807 // XXX: correct escaping
2808 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2809 if (icon == nil) if (section != nil)
2810 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2811 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2812 if ([dicon hasPrefix:@"file:///"])
2813 // XXX: correct escaping
2814 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2816 icon = [UIImage applicationImageNamed:@"unknown.png"];
2820 - (NSString *) homepage {
2821 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2824 - (NSString *) depiction {
2825 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2828 - (Address *) sponsor {
2829 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2832 - (Address *) author {
2833 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2836 - (NSString *) support {
2837 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2840 - (NSArray *) files {
2841 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2842 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2845 fin.open([path UTF8String]);
2850 while (std::getline(fin, line))
2851 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2856 - (NSString *) state {
2857 @synchronized (database_) {
2858 if ([database_ era] != era_ || file_.end())
2861 switch (iterator_->CurrentState) {
2862 case pkgCache::State::NotInstalled:
2863 return @"NotInstalled";
2864 case pkgCache::State::UnPacked:
2866 case pkgCache::State::HalfConfigured:
2867 return @"HalfConfigured";
2868 case pkgCache::State::HalfInstalled:
2869 return @"HalfInstalled";
2870 case pkgCache::State::ConfigFiles:
2871 return @"ConfigFiles";
2872 case pkgCache::State::Installed:
2873 return @"Installed";
2874 case pkgCache::State::TriggersAwaited:
2875 return @"TriggersAwaited";
2876 case pkgCache::State::TriggersPending:
2877 return @"TriggersPending";
2880 return (NSString *) [NSNull null];
2883 - (NSString *) selection {
2884 @synchronized (database_) {
2885 if ([database_ era] != era_ || file_.end())
2888 switch (iterator_->SelectedState) {
2889 case pkgCache::State::Unknown:
2891 case pkgCache::State::Install:
2893 case pkgCache::State::Hold:
2895 case pkgCache::State::DeInstall:
2896 return @"DeInstall";
2897 case pkgCache::State::Purge:
2901 return (NSString *) [NSNull null];
2904 - (NSArray *) warnings {
2905 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2906 const char *name(iterator_.Name());
2908 size_t length(strlen(name));
2909 if (length < 2) invalid:
2910 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2911 else for (size_t i(0); i != length; ++i)
2913 /* XXX: technically this is not allowed */
2914 (name[i] < 'A' || name[i] > 'Z') &&
2915 (name[i] < 'a' || name[i] > 'z') &&
2916 (name[i] < '0' || name[i] > '9') &&
2917 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2920 if (strcmp(name, "cydia") != 0) {
2923 bool _private = false;
2926 bool repository = [[self section] isEqualToString:@"Repositories"];
2928 if (NSArray *files = [self files])
2929 for (NSString *file in files)
2930 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2932 else if (!user && [file isEqualToString:@"/User"])
2934 else if (!_private && [file isEqualToString:@"/private"])
2936 else if (!stash && [file isEqualToString:@"/var/stash"])
2939 /* XXX: this is not sensitive enough. only some folders are valid. */
2940 if (cydia && !repository)
2941 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2943 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2945 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2947 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2950 return [warnings count] == 0 ? nil : warnings;
2953 - (NSArray *) applications {
2954 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2956 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2958 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2959 if (NSArray *files = [self files])
2960 for (NSString *file in files)
2961 if (application_r(file)) {
2962 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2963 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2964 if ([id isEqualToString:me])
2967 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2969 display = application_r[1];
2971 NSString *bundle([file stringByDeletingLastPathComponent]);
2972 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2973 if (icon == nil || [icon length] == 0)
2975 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2977 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2978 [applications addObject:application];
2980 [application addObject:id];
2981 [application addObject:display];
2982 [application addObject:url];
2985 return [applications count] == 0 ? nil : applications;
2988 - (Source *) source {
2989 if (source_ == nil) {
2990 @synchronized (database_) {
2991 if ([database_ era] != era_ || file_.end())
2992 source_ = (Source *) [NSNull null];
2994 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2998 return source_ == (Source *) [NSNull null] ? nil : source_;
3001 - (BOOL) matches:(NSString *)text {
3007 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
3008 if (range.location != NSNotFound)
3011 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
3012 if (range.location != NSNotFound)
3017 NSString *description([self shortDescription]);
3018 NSUInteger length([description length]);
3020 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_ range:NSMakeRange(0, std::min<NSUInteger>(length, 100))];
3021 if (range.location != NSNotFound)
3027 - (bool) hasSupportingRole {
3032 if ([Role_ isEqualToString:@"User"])
3036 if ([Role_ isEqualToString:@"Hacker"])
3040 if ([Role_ isEqualToString:@"Developer"])
3045 - (NSArray *) tags {
3049 - (BOOL) hasTag:(NSString *)tag {
3050 return tags_ == nil ? NO : [tags_ containsObject:tag];
3053 - (NSString *) primaryPurpose {
3054 for (NSString *tag in tags_)
3055 if ([tag hasPrefix:@"purpose::"])
3056 return [tag substringFromIndex:9];
3060 - (NSArray *) purposes {
3061 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3062 for (NSString *tag in tags_)
3063 if ([tag hasPrefix:@"purpose::"])
3064 [purposes addObject:[tag substringFromIndex:9]];
3065 return [purposes count] == 0 ? nil : purposes;
3068 - (bool) isCommercial {
3069 return [self hasTag:@"cydia::commercial"];
3072 - (void) setIndex:(size_t)index {
3073 if (metadata_->index_ != index)
3074 metadata_->index_ = index;
3077 - (CYString &) cyname {
3078 return name_.empty() ? id_ : name_;
3081 - (uint32_t) compareBySection:(NSArray *)sections {
3082 NSString *section([self section]);
3083 for (size_t i(0), e([sections count]); i != e; ++i) {
3084 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3088 return _not(uint32_t);
3092 @synchronized (database_) {
3093 pkgProblemResolver *resolver = [database_ resolver];
3094 resolver->Clear(iterator_);
3096 pkgCacheFile &cache([database_ cache]);
3097 cache->SetReInstall(iterator_, false);
3098 cache->MarkKeep(iterator_, false);
3102 @synchronized (database_) {
3103 pkgProblemResolver *resolver = [database_ resolver];
3104 resolver->Clear(iterator_);
3105 resolver->Protect(iterator_);
3107 pkgCacheFile &cache([database_ cache]);
3108 cache->SetReInstall(iterator_, false);
3109 cache->MarkInstall(iterator_, false);
3111 pkgDepCache::StateCache &state((*cache)[iterator_]);
3112 if (!state.Install())
3113 cache->SetReInstall(iterator_, true);
3117 @synchronized (database_) {
3118 pkgProblemResolver *resolver = [database_ resolver];
3119 resolver->Clear(iterator_);
3120 resolver->Remove(iterator_);
3121 resolver->Protect(iterator_);
3123 pkgCacheFile &cache([database_ cache]);
3124 cache->SetReInstall(iterator_, false);
3125 cache->MarkDelete(iterator_, true);
3128 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3129 _profile(Package$isUnfilteredAndSearchedForBy)
3132 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3133 value &= [self unfiltered];
3136 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3137 value &= [self matches:search];
3144 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3145 if ([search length] == 0)
3148 _profile(Package$isUnfilteredAndSelectedForBy)
3151 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3152 value &= [self unfiltered];
3155 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3156 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3163 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3164 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3167 - (bool) isVisibleInSection:(NSString *)name {
3168 NSString *section([self section]);
3172 section == nil && [name length] == 0 ||
3173 [name isEqualToString:section]
3174 ) && [self visible];
3177 - (bool) isVisibleInSource:(Source *)source {
3178 return [self source] == source && [self visible];
3183 /* Section Class {{{ */
3184 @interface Section : NSObject {
3189 NSString *localized_;
3192 - (NSComparisonResult) compareByLocalized:(Section *)section;
3193 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3194 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3195 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3196 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3197 - (NSString *) name;
3204 - (void) addToCount;
3206 - (void) setCount:(size_t)count;
3207 - (NSString *) localized;
3211 @implementation Section
3215 if (localized_ != nil)
3216 [localized_ release];
3220 - (NSComparisonResult) compareByLocalized:(Section *)section {
3221 NSString *lhs(localized_);
3222 NSString *rhs([section localized]);
3224 /*if ([lhs length] != 0 && [rhs length] != 0) {
3225 unichar lhc = [lhs characterAtIndex:0];
3226 unichar rhc = [rhs characterAtIndex:0];
3228 if (isalpha(lhc) && !isalpha(rhc))
3229 return NSOrderedAscending;
3230 else if (!isalpha(lhc) && isalpha(rhc))
3231 return NSOrderedDescending;
3234 return [lhs compare:rhs options:LaxCompareOptions_];
3237 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3238 if ((self = [self initWithName:name localize:NO]) != nil) {
3239 if (localized != nil)
3240 localized_ = [localized retain];
3244 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3245 return [self initWithName:name row:0 localize:localize];
3248 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3249 if ((self = [super init]) != nil) {
3250 name_ = [name retain];
3254 localized_ = [LocalizeSection(name_) retain];
3258 /* XXX: localize the index thingees */
3259 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3260 if ((self = [super init]) != nil) {
3261 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3267 - (NSString *) name {
3287 - (void) addToCount {
3291 - (void) setCount:(size_t)count {
3295 - (NSString *) localized {
3302 static NSString *Colon_;
3303 static NSString *Elision_;
3304 static NSString *Error_;
3305 static NSString *Warning_;
3307 /* Database Implementation {{{ */
3308 @implementation Database
3310 + (Database *) sharedInstance {
3311 static Database *instance;
3312 if (instance == nil)
3313 instance = [[Database alloc] init];
3321 - (void) releasePackages {
3322 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3323 CFArrayRemoveAllValues(packages_);
3327 // XXX: actually implement this thing
3329 [sourceList_ release];
3330 [self releasePackages];
3331 apr_pool_destroy(pool_);
3332 NSRecycleZone(zone_);
3336 - (void) _readCydia:(NSNumber *)fd { _pooled
3337 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3338 std::istream is(&ib);
3341 static Pcre finish_r("^finish:([^:]*)$");
3343 while (std::getline(is, line)) {
3344 const char *data(line.c_str());
3345 size_t size = line.size();
3346 lprintf("C:%s\n", data);
3348 if (finish_r(data, size)) {
3349 NSString *finish = finish_r[1];
3350 int index = [Finishes_ indexOfObject:finish];
3351 if (index != INT_MAX && index > Finish_)
3359 - (void) _readStatus:(NSNumber *)fd { _pooled
3360 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3361 std::istream is(&ib);
3364 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3365 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3367 while (std::getline(is, line)) {
3368 const char *data(line.c_str());
3369 size_t size(line.size());
3370 lprintf("S:%s\n", data);
3372 if (conffile_r(data, size)) {
3373 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3374 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3375 } else if (strncmp(data, "status: ", 8) == 0) {
3376 // status: <package>: {unpacked,half-configured,installed}
3377 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3378 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3379 } else if (strncmp(data, "processing: ", 12) == 0) {
3380 // processing: configure: config-test
3381 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3382 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3383 } else if (pmstatus_r(data, size)) {
3384 std::string type([pmstatus_r[1] UTF8String]);
3386 NSString *package = pmstatus_r[2];
3387 if ([package isEqualToString:@"dpkg-exec"])
3390 float percent([pmstatus_r[3] floatValue]);
3391 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3393 NSString *string = pmstatus_r[4];
3395 if (type == "pmerror") {
3396 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3397 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3398 } else if (type == "pmstatus") {
3399 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3400 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3401 } else if (type == "pmconffile")
3402 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3404 lprintf("E:unknown pmstatus\n");
3406 lprintf("E:unknown status\n");
3412 - (void) _readOutput:(NSNumber *)fd { _pooled
3413 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3414 std::istream is(&ib);
3417 while (std::getline(is, line)) {
3418 lprintf("O:%s\n", line.c_str());
3420 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3421 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3431 - (Package *) packageWithName:(NSString *)name {
3432 @synchronized (self) {
3433 if (static_cast<pkgDepCache *>(cache_) == NULL)
3435 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3436 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3440 if ((self = [super init]) != nil) {
3447 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3448 apr_pool_create(&pool_, NULL);
3450 size_t capacity(MetaFile_->active_);
3456 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3457 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3461 _assert(pipe(fds) != -1);
3464 _config->Set("APT::Keep-Fds::", cydiafd_);
3465 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3468 detachNewThreadSelector:@selector(_readCydia:)
3470 withObject:[NSNumber numberWithInt:fds[0]]
3473 _assert(pipe(fds) != -1);
3477 detachNewThreadSelector:@selector(_readStatus:)
3479 withObject:[NSNumber numberWithInt:fds[0]]
3482 _assert(pipe(fds) != -1);
3483 _assert(dup2(fds[0], 0) != -1);
3484 _assert(close(fds[0]) != -1);
3486 input_ = fdopen(fds[1], "a");
3488 _assert(pipe(fds) != -1);
3489 _assert(dup2(fds[1], 1) != -1);
3490 _assert(close(fds[1]) != -1);
3493 detachNewThreadSelector:@selector(_readOutput:)
3495 withObject:[NSNumber numberWithInt:fds[0]]
3500 - (pkgCacheFile &) cache {
3504 - (pkgDepCache::Policy *) policy {
3508 - (pkgRecords *) records {
3512 - (pkgProblemResolver *) resolver {
3516 - (pkgAcquire &) fetcher {
3520 - (pkgSourceList &) list {
3524 - (NSArray *) packages {
3525 return (NSArray *) packages_;
3528 - (NSArray *) sources {
3532 - (Source *) sourceWithKey:(NSString *)key {
3533 for (Source *source in [self sources]) {
3534 if ([[source key] isEqualToString:key])
3539 - (bool) popErrorWithTitle:(NSString *)title {
3542 while (!_error->empty()) {
3544 bool warning(!_error->PopMessage(error));
3549 size_t size(error.size());
3550 if (size == 0 || error[size - 1] != '\n')
3552 error.resize(size - 1);
3555 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3557 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3563 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3564 return [self popErrorWithTitle:title] || !success;
3567 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3568 @synchronized (self) {
3571 [self releasePackages];
3574 [sourceList_ removeAllObjects];
3594 apr_pool_clear(pool_);
3596 NSRecycleZone(zone_);
3597 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3599 int chk(creat("/tmp/cydia.chk", 0644));
3603 if (invocation != nil)
3604 [invocation invoke];
3606 NSString *title(UCLocalize("DATABASE"));
3609 OpProgress progress;
3610 while (!cache_.Open(progress, true)) { pop:
3612 bool warning(!_error->PopMessage(error));
3613 lprintf("cache_.Open():[%s]\n", error.c_str());
3615 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3616 [delegate_ repairWithSelector:@selector(configure)];
3617 else if (error == "The package lists or status file could not be parsed or opened.")
3618 [delegate_ repairWithSelector:@selector(update)];
3619 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3620 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3621 // else if (error == "Malformed Status line")
3622 // else if (error == "The list of sources could not be read.")
3624 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3634 unlink("/tmp/cydia.chk");
3636 now_ = [[NSDate date] timeIntervalSince1970];
3638 policy_ = new pkgDepCache::Policy();
3639 records_ = new pkgRecords(cache_);
3640 resolver_ = new pkgProblemResolver(cache_);
3641 fetcher_ = new pkgAcquire(&status_);
3644 list_ = new pkgSourceList();
3645 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3648 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3649 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3653 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3656 if (cache_->BrokenCount() != 0) {
3657 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3660 if (cache_->BrokenCount() != 0) {
3661 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3665 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3669 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3670 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3671 [sourceList_ addObject:object];
3673 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3674 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3675 // XXX: this could be more intelligent
3676 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3677 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3679 sourceMap_[cached->ID] = object;
3684 /*std::vector<Package *> packages;
3685 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3686 [packages_ release];
3691 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3692 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3693 //packages.push_back(package);
3694 CFArrayAppendValue(packages_, [package retain]);
3698 /*if (packages.empty())
3699 packages_ = [[NSArray alloc] init];
3701 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3704 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3705 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3706 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3714 /*if (!packages.empty())
3715 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3716 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3718 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3720 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3722 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3726 size_t count(CFArrayGetCount(packages_));
3727 MetaFile_->active_ = count;
3729 for (size_t index(0); index != count; ++index)
3730 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3734 } } CYPoolEnd() _trace(); }
3737 @synchronized (self) {
3739 resolver_ = new pkgProblemResolver(cache_);
3741 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3742 if (!cache_[iterator].Keep())
3743 cache_->MarkKeep(iterator, false);
3744 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3745 cache_->SetReInstall(iterator, false);
3748 - (void) configure {
3749 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3751 system([dpkg UTF8String]);
3756 // XXX: I don't remember this condition
3761 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3763 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3765 if ([self popErrorWithTitle:title])
3769 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3772 public pkgArchiveCleaner
3775 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3780 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3787 fetcher_->Shutdown();
3789 pkgRecords records(cache_);
3791 lock_ = new FileFd();
3792 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3794 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3796 if ([self popErrorWithTitle:title])
3800 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3803 manager_ = (_system->CreatePM(cache_));
3804 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3811 bool substrate(RestartSubstrate_);
3812 RestartSubstrate_ = false;
3814 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3816 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3818 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3820 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3821 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3824 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3826 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3828 [self popErrorWithTitle:title];
3832 bool failed = false;
3833 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3834 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3836 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3842 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3850 RestartSubstrate_ = true;
3853 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3855 if (_error->PendingError()) {
3860 if (result == pkgPackageManager::Failed) {
3865 if (result != pkgPackageManager::Completed) {
3870 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3872 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3874 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3875 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3878 if (![before isEqualToArray:after])
3883 NSString *title(UCLocalize("UPGRADE"));
3884 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3890 [self updateWithStatus:status_];
3893 - (void) updateWithStatus:(Status &)status {
3894 NSString *title(UCLocalize("REFRESHING_DATA"));
3897 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3901 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3902 if ([self popErrorWithTitle:title])
3905 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3907 bool success(ListUpdate(status, list, PulseInterval_));
3908 if (status.WasCancelled())
3911 [self popErrorWithTitle:title forOperation:success];
3913 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3915 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3919 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3920 delegate_ = delegate;
3923 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3924 progress_ = delegate;
3925 status_.setDelegate(delegate);
3928 - (NSObject<ProgressDelegate> *) progressDelegate {
3932 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3933 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3934 return i == sourceMap_.end() ? nil : i->second;
3937 - (NSString *) mappedSectionForPointer:(const char *)section {
3938 _H<NSString> *mapped;
3940 _profile(Database$mappedSectionForPointer$Cache)
3941 mapped = §ions_[section];
3944 if (*mapped == NULL) {
3945 size_t length(strlen(section));
3946 char spaced[length + 1];
3948 _profile(Database$mappedSectionForPointer$Replace)
3949 for (size_t index(0); index != length; ++index)
3950 spaced[index] = section[index] == '_' ? ' ' : section[index];
3951 spaced[length] = '\0';
3956 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3957 string = [NSString stringWithUTF8String:spaced];
3960 _profile(Database$mappedSectionForPointer$Map)
3961 string = [SectionMap_ objectForKey:string] ?: string;
3971 static NSMutableSet *Diversions_;
3973 @interface Diversion : NSObject {
3976 _H<NSString> format_;
3981 @implementation Diversion
3983 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3984 if ((self = [super init]) != nil) {
3985 pattern_ = [from UTF8String];
3991 - (NSString *) divert:(NSString *)url {
3992 return !pattern_(url) ? nil : pattern_->*format_;
3995 + (NSURL *) divertURL:(NSURL *)url {
3997 NSString *href([url absoluteString]);
3999 for (Diversion *diversion in Diversions_)
4000 if (NSString *diverted = [diversion divert:href]) {
4002 NSLog(@"div: %@", diverted);
4004 url = [NSURL URLWithString:diverted];
4011 - (NSString *) key {
4015 - (NSUInteger) hash {
4019 - (BOOL) isEqual:(Diversion *)object {
4020 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4025 @interface CydiaObject : NSObject {
4027 _transient id delegate_;
4030 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4034 @interface CydiaWebViewController : BrowserController {
4035 CydiaObject *cydia_;
4038 + (void) addDiversion:(Diversion *)diversion;
4042 /* Web Scripting {{{ */
4043 @implementation CydiaObject
4046 [indirect_ release];
4050 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4051 if ((self = [super init]) != nil) {
4052 indirect_ = [indirect retain];
4056 - (void) setDelegate:(id)delegate {
4057 delegate_ = delegate;
4060 + (NSArray *) _attributeKeys {
4061 return [NSArray arrayWithObjects:
4076 - (NSArray *) attributeKeys {
4077 return [[self class] _attributeKeys];
4080 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4081 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4084 - (NSString *) version {
4088 - (NSString *) device {
4089 return [[UIDevice currentDevice] uniqueIdentifier];
4092 - (NSString *) firmware {
4093 return [[UIDevice currentDevice] systemVersion];
4096 - (NSString *) hostname {
4097 return [[UIDevice currentDevice] name];
4100 - (NSString *) idiom {
4101 return (id) Idiom_ ?: [NSNull null];
4104 - (NSString *) plmn {
4105 return (id) PLMN_ ?: [NSNull null];
4108 - (NSString *) ecid {
4109 return (id) ChipID_ ?: [NSNull null];
4112 - (NSString *) serial {
4113 return SerialNumber_;
4116 - (NSString *) role {
4117 return (id) Role_ ?: [NSNull null];
4120 - (NSString *) model {
4121 return [NSString stringWithUTF8String:Machine_];
4124 - (NSString *) token {
4125 return (id) Token_ ?: [NSNull null];
4128 + (NSString *) webScriptNameForSelector:(SEL)selector {
4130 else if (selector == @selector(addBridgedHost:))
4131 return @"addBridgedHost";
4132 else if (selector == @selector(addPipelinedHost:scheme:))
4133 return @"addPipelinedHost";
4134 else if (selector == @selector(addTrivialSource:))
4135 return @"addTrivialSource";
4136 else if (selector == @selector(close))
4138 else if (selector == @selector(divert::))
4140 else if (selector == @selector(du:))
4142 else if (selector == @selector(stringWithFormat:arguments:))
4144 else if (selector == @selector(getAllSources))
4145 return @"getAllSourcs";
4146 else if (selector == @selector(getKernelNumber:))
4147 return @"getKernelNumber";
4148 else if (selector == @selector(getKernelString:))
4149 return @"getKernelString";
4150 else if (selector == @selector(getInstalledPackages))
4151 return @"getInstalledPackages";
4152 else if (selector == @selector(getLocaleIdentifier))
4153 return @"getLocaleIdentifier";
4154 else if (selector == @selector(getPreferredLanguages))
4155 return @"getPreferredLanguages";
4156 else if (selector == @selector(getPackageById:))
4157 return @"getPackageById";
4158 else if (selector == @selector(getSessionValue:))
4159 return @"getSessionValue";
4160 else if (selector == @selector(installPackages:))
4161 return @"installPackages";
4162 else if (selector == @selector(localizedStringForKey:value:table:))
4164 else if (selector == @selector(popViewController:))
4165 return @"popViewController";
4166 else if (selector == @selector(refreshSources))
4167 return @"refreshSources";
4168 else if (selector == @selector(removeButton))
4169 return @"removeButton";
4170 else if (selector == @selector(setSessionValue::))
4171 return @"setSessionValue";
4172 else if (selector == @selector(substitutePackageNames:))
4173 return @"substitutePackageNames";
4174 else if (selector == @selector(scrollToBottom:))
4175 return @"scrollToBottom";
4176 else if (selector == @selector(setAllowsNavigationAction:))
4177 return @"setAllowsNavigationAction";
4178 else if (selector == @selector(setBadgeValue:))
4179 return @"setBadgeValue";
4180 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4181 return @"setButtonImage";
4182 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4183 return @"setButtonTitle";
4184 else if (selector == @selector(setHidesBackButton:))
4185 return @"setHidesBackButton";
4186 else if (selector == @selector(setHidesNavigationBar:))
4187 return @"setHidesNavigationBar";
4188 else if (selector == @selector(setNavigationBarStyle:))
4189 return @"setNavigationBarStyle";
4190 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4191 return @"setNavigationBarTintColor";
4192 else if (selector == @selector(setPasteboardString:))
4193 return @"setPasteboardString";
4194 else if (selector == @selector(setPasteboardURL:))
4195 return @"setPasteboardURL";
4196 else if (selector == @selector(setToken:))
4198 else if (selector == @selector(setViewportWidth:))
4199 return @"setViewportWidth";
4200 else if (selector == @selector(statfs:))
4202 else if (selector == @selector(supports:))
4208 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4209 return [self webScriptNameForSelector:selector] == nil;
4212 - (BOOL) supports:(NSString *)feature {
4213 return [feature isEqualToString:@"window.open"];
4216 - (void) divert:(NSString *)from :(NSString *)to {
4217 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4220 - (NSNumber *) getKernelNumber:(NSString *)name {
4221 const char *string([name UTF8String]);
4224 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4225 return (id) [NSNull null];
4227 if (size != sizeof(int))
4228 return (id) [NSNull null];
4231 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4232 return (id) [NSNull null];
4234 return [NSNumber numberWithInt:value];
4237 - (NSString *) getKernelString:(NSString *)name {
4238 const char *string([name UTF8String]);
4241 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4242 return (id) [NSNull null];
4244 char value[size + 1];
4245 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4246 return (id) [NSNull null];
4248 // XXX: just in case you request something ludicrous
4251 return [NSString stringWithCString:value];
4254 - (id) getSessionValue:(NSString *)key {
4255 @synchronized (SessionData_) {
4256 return [SessionData_ objectForKey:key];
4259 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4260 @synchronized (SessionData_) {
4261 if (value == (id) [WebUndefined undefined])
4262 [SessionData_ removeObjectForKey:key];
4264 [SessionData_ setObject:value forKey:key];
4267 - (void) addBridgedHost:(NSString *)host {
4268 @synchronized (HostConfig_) {
4269 [BridgedHosts_ addObject:host];
4272 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4273 @synchronized (HostConfig_) {
4274 if (scheme != (id) [WebUndefined undefined])
4275 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4277 [PipelinedHosts_ addObject:host];
4280 - (void) popViewController:(NSNumber *)value {
4281 if (value == (id) [WebUndefined undefined])
4282 value = [NSNumber numberWithBool:YES];
4283 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4286 - (void) addTrivialSource:(NSString *)href {
4287 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4290 - (void) refreshSources {
4291 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4294 - (NSArray *) getAllSources {
4295 return [[Database sharedInstance] sources];
4298 - (NSArray *) getInstalledPackages {
4299 Database *database([Database sharedInstance]);
4300 @synchronized (database) {
4301 NSArray *packages([database packages]);
4302 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4303 for (Package *package in packages)
4304 if (![package uninstalled])
4305 [installed addObject:package];
4309 - (Package *) getPackageById:(NSString *)id {
4310 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4314 return (Package *) [NSNull null];
4317 - (NSString *) getLocaleIdentifier {
4318 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4321 - (NSArray *) getPreferredLanguages {
4325 - (NSArray *) statfs:(NSString *)path {
4328 if (path == nil || statfs([path UTF8String], &stat) == -1)
4331 return [NSArray arrayWithObjects:
4332 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4333 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4334 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4338 - (NSNumber *) du:(NSString *)path {
4339 NSNumber *value(nil);
4342 _assert(pipe(fds) != -1);
4344 pid_t pid(ExecFork());
4346 _assert(dup2(fds[1], 1) != -1);
4347 _assert(close(fds[0]) != -1);
4348 _assert(close(fds[1]) != -1);
4349 /* XXX: this should probably not use du */
4350 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4355 _assert(close(fds[1]) != -1);
4357 if (FILE *du = fdopen(fds[0], "r")) {
4359 while (fgets(line, sizeof(line), du) != NULL) {
4360 size_t length(strlen(line));
4361 while (length != 0 && line[length - 1] == '\n')
4362 line[--length] = '\0';
4363 if (char *tab = strchr(line, '\t')) {
4365 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4370 } else _assert(close(fds[0]));
4374 if (waitpid(pid, &status, 0) == -1)
4377 else _assert(false);
4383 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4386 - (void) installPackages:(NSArray *)packages {
4387 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4390 - (NSString *) substitutePackageNames:(NSString *)message {
4391 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4392 for (size_t i(0), e([words count]); i != e; ++i) {
4393 NSString *word([words objectAtIndex:i]);
4394 if (Package *package = [[Database sharedInstance] packageWithName:word])
4395 [words replaceObjectAtIndex:i withObject:[package name]];
4398 return [words componentsJoinedByString:@" "];
4401 - (void) removeButton {
4402 [indirect_ removeButton];
4405 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4406 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4409 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4410 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4413 - (void) setBadgeValue:(id)value {
4414 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4417 - (void) setAllowsNavigationAction:(NSString *)value {
4418 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4421 - (void) setHidesBackButton:(NSString *)value {
4422 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4425 - (void) setHidesNavigationBar:(NSString *)value {
4426 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4429 - (void) setNavigationBarStyle:(NSString *)value {
4430 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4433 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4434 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4435 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4436 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4439 - (void) setPasteboardString:(NSString *)value {
4440 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4443 - (void) setPasteboardURL:(NSString *)value {
4444 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4447 - (void) _setToken:(NSString *)token {
4451 [Metadata_ removeObjectForKey:@"Token"];
4453 [Metadata_ setObject:Token_ forKey:@"Token"];
4458 - (void) setToken:(NSString *)token {
4459 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4462 - (void) scrollToBottom:(NSNumber *)animated {
4463 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4466 - (void) setViewportWidth:(float)width {
4467 [indirect_ setViewportWidthOnMainThread:width];
4470 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4471 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4472 unsigned count([arguments count]);
4474 for (unsigned i(0); i != count; ++i)
4475 values[i] = [arguments objectAtIndex:i];
4476 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4479 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4480 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4482 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4484 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4490 /* @ Loading... Indicator {{{ */
4491 @interface CYLoadingIndicator : UIView {
4492 _H<UIActivityIndicatorView> spinner_;
4494 _H<UIView> container_;
4497 @property (readonly, nonatomic) UILabel *label;
4498 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4502 @implementation CYLoadingIndicator
4504 - (id) initWithFrame:(CGRect)frame {
4505 if ((self = [super initWithFrame:frame]) != nil) {
4506 container_ = [[[UIView alloc] init] autorelease];
4507 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4509 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4510 [spinner_ startAnimating];
4511 [container_ addSubview:spinner_];
4513 label_ = [[[UILabel alloc] init] autorelease];
4514 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4515 [label_ setBackgroundColor:[UIColor clearColor]];
4516 [label_ setTextColor:[UIColor blackColor]];
4517 [label_ setShadowColor:[UIColor whiteColor]];
4518 [label_ setShadowOffset:CGSizeMake(0, 1)];
4519 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4520 [container_ addSubview:label_];
4522 CGSize viewsize = frame.size;
4523 CGSize spinnersize = [spinner_ bounds].size;
4524 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4525 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4527 CGRect containrect = {
4528 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4529 CGSizeMake(bothwidth, spinnersize.height)
4532 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4540 [container_ setFrame:containrect];
4541 [spinner_ setFrame:spinrect];
4542 [label_ setFrame:textrect];
4543 [self addSubview:container_];
4547 - (UILabel *) label {
4551 - (UIActivityIndicatorView *) activityIndicatorView {
4557 /* Emulated Loading Controller {{{ */
4558 @interface CYEmulatedLoadingController : CYViewController {
4559 _transient Database *database_;
4560 _H<CYLoadingIndicator> indicator_;
4561 _H<UITabBar> tabbar_;
4562 _H<UINavigationBar> navbar_;
4567 @implementation CYEmulatedLoadingController
4569 - (id) initWithDatabase:(Database *)database {
4570 if ((self = [super init]) != nil) {
4571 database_ = database;
4576 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4578 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4579 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4580 [[self view] addSubview:table];
4582 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4583 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4584 [[self view] addSubview:indicator_];
4586 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4587 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4588 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4589 [[self view] addSubview:tabbar_];
4591 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4592 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4593 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4594 [[self view] addSubview:navbar_];
4597 - (void) releaseSubviews {
4606 /* Cydia Browser Controller {{{ */
4607 @implementation CydiaWebViewController
4614 - (NSURL *) navigationURL {
4615 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4618 + (void) initialize {
4619 Diversions_ = [[NSMutableSet alloc] initWithCapacity:0];
4622 + (void) addDiversion:(Diversion *)diversion {
4623 [Diversions_ addObject:diversion];
4626 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4627 [super webView:view didClearWindowObject:window forFrame:frame];
4629 WebDataSource *source([frame dataSource]);
4630 NSURLResponse *response([source response]);
4631 NSURL *url([response URL]);
4632 NSString *scheme([[url scheme] lowercaseString]);
4634 bool bridged(false);
4636 @synchronized (HostConfig_) {
4637 if ([scheme isEqualToString:@"file"])
4639 else if ([scheme isEqualToString:@"https"])
4640 if ([BridgedHosts_ containsObject:[url host]])
4645 [window setValue:cydia_ forKey:@"cydia"];
4648 - (NSURL *) URLWithURL:(NSURL *)url {
4649 return [Diversion divertURL:url];
4652 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4653 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4655 if (System_ != NULL)
4656 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4657 if (Machine_ != NULL)
4658 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4660 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4665 - (void) setDelegate:(id)delegate {
4666 [super setDelegate:delegate];
4667 [cydia_ setDelegate:delegate];
4671 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4672 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4674 WebView *webview([[webview_ _documentView] webView]);
4676 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4679 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4681 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4682 if (Product_ != nil)
4683 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4685 [webview setApplicationNameForUserAgent:application];
4693 @interface NSObject (CydiaScript)
4694 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4697 @implementation NSObject (CydiaScript)
4699 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4705 @implementation NSArray (CydiaScript)
4707 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4708 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4709 for (size_t i(0), e([self count]); i != e; ++i)
4710 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4716 @implementation NSDictionary (CydiaScript)
4718 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4719 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4721 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4728 /* Confirmation Controller {{{ */
4729 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4730 if (!iterator.end())
4731 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4732 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4734 pkgCache::PkgIterator package(dep.TargetPkg());
4737 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4744 @protocol ConfirmationControllerDelegate
4745 - (void) cancelAndClear:(bool)clear;
4746 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4750 @interface ConfirmationController : CydiaWebViewController {
4751 _transient Database *database_;
4753 UIAlertView *essential_;
4755 NSDictionary *changes_;
4756 NSMutableArray *issues_;
4757 NSDictionary *sizes_;
4762 - (id) initWithDatabase:(Database *)database;
4766 @implementation ConfirmationController
4773 if (essential_ != nil)
4774 [essential_ release];
4781 RestartSubstrate_ = true;
4782 [delegate_ confirmWithNavigationController:[self navigationController]];
4785 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4786 NSString *context([alert context]);
4788 if ([context isEqualToString:@"remove"]) {
4789 if (button == [alert cancelButtonIndex])
4790 [self dismissModalViewControllerAnimated:YES];
4791 else if (button == [alert firstOtherButtonIndex]) {
4795 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4796 } else if ([context isEqualToString:@"unable"]) {
4797 [self dismissModalViewControllerAnimated:YES];
4798 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4800 [super alertView:alert clickedButtonAtIndex:button];
4804 - (void) _doContinue {
4805 [self dismissModalViewControllerAnimated:YES];
4806 [delegate_ cancelAndClear:NO];
4809 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4810 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4814 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4815 [super webView:view didClearWindowObject:window forFrame:frame];
4817 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4818 changes_, @"changes",
4822 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4825 - (id) initWithDatabase:(Database *)database {
4826 if ((self = [super init]) != nil) {
4827 database_ = database;
4829 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4830 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4831 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4832 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4833 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4837 pkgCacheFile &cache([database_ cache]);
4838 NSArray *packages([database_ packages]);
4839 pkgDepCache::Policy *policy([database_ policy]);
4841 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4843 for (Package *package in packages) {
4844 pkgCache::PkgIterator iterator([package iterator]);
4845 NSString *name([package id]);
4847 if ([package broken]) {
4848 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4850 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4852 reasons, @"reasons",
4855 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4859 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4860 pkgCache::DepIterator start;
4861 pkgCache::DepIterator end;
4862 dep.GlobOr(start, end); // ++dep
4864 if (!cache->IsImportantDep(end))
4866 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4869 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4871 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4872 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4873 clauses, @"clauses",
4877 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4879 pkgCache::PkgIterator target(start.TargetPkg());
4880 if (target->ProvidesList != 0)
4881 reason = @"missing";
4883 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4885 reason = @"installed";
4886 installed = [NSString stringWithUTF8String:ver.VerStr()];
4887 } else if (!cache[target].CandidateVerIter(cache).end())
4888 reason = @"uninstalled";
4889 else if (target->ProvidesList == 0)
4890 reason = @"uninstallable";
4892 reason = @"virtual";
4895 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4896 [NSString stringWithUTF8String:start.CompType()], @"operator",
4897 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4900 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4901 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4902 version, @"version",
4904 installed, @"installed",
4907 // yes, seriously. (wtf?)
4915 pkgDepCache::StateCache &state(cache[iterator]);
4917 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4919 if (state.NewInstall())
4920 [installs addObject:name];
4921 // XXX: else if (state.Install())
4922 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4923 [reinstalls addObject:name];
4924 // XXX: move before previous if
4925 else if (state.Upgrade())
4926 [upgrades addObject:name];
4927 else if (state.Downgrade())
4928 [downgrades addObject:name];
4929 else if (!state.Delete())
4930 // XXX: _assert(state.Keep());
4932 else if (special_r(name))
4933 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4934 [NSNull null], @"package",
4935 [NSArray arrayWithObjects:
4936 [NSDictionary dictionaryWithObjectsAndKeys:
4937 @"Conflicts", @"relationship",
4938 [NSArray arrayWithObjects:
4939 [NSDictionary dictionaryWithObjectsAndKeys:
4941 [NSNull null], @"version",
4942 @"installed", @"reason",
4949 if ([package essential])
4951 [removes addObject:name];
4954 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4955 substrate_ |= DepSubstrate(iterator.CurrentVer());
4960 else if (Advanced_) {
4961 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4963 essential_ = [[UIAlertView alloc]
4964 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4965 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4967 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4969 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4973 [essential_ setContext:@"remove"];
4975 essential_ = [[UIAlertView alloc]
4976 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4977 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4979 cancelButtonTitle:UCLocalize("OKAY")
4980 otherButtonTitles:nil
4983 [essential_ setContext:@"unable"];
4986 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4987 installs, @"installs",
4988 reinstalls, @"reinstalls",
4989 upgrades, @"upgrades",
4990 downgrades, @"downgrades",
4991 removes, @"removes",
4994 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4995 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4996 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4999 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5001 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
5002 initWithTitle:UCLocalize("CANCEL")
5003 style:UIBarButtonItemStylePlain
5005 action:@selector(cancelButtonClicked)
5011 - (void) applyRightButton {
5012 if ([issues_ count] == 0 && ![self isLoading])
5013 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5014 initWithTitle:UCLocalize("CONFIRM")
5015 style:UIBarButtonItemStyleDone
5017 action:@selector(confirmButtonClicked)
5020 [[self navigationItem] setRightBarButtonItem:nil];
5024 - (void) cancelButtonClicked {
5025 [self dismissModalViewControllerAnimated:YES];
5026 [delegate_ cancelAndClear:YES];
5030 - (void) confirmButtonClicked {
5031 if (essential_ != nil)
5041 /* Progress Data {{{ */
5042 @interface CydiaProgressData : NSObject {
5043 _transient id delegate_;
5052 _H<NSMutableArray> events_;
5053 _H<NSString> title_;
5055 _H<NSString> status_;
5056 _H<NSString> finish_;
5061 @implementation CydiaProgressData
5063 + (NSArray *) _attributeKeys {
5064 return [NSArray arrayWithObjects:
5076 - (NSArray *) attributeKeys {
5077 return [[self class] _attributeKeys];
5080 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5081 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5085 if ((self = [super init]) != nil) {
5086 events_ = [NSMutableArray arrayWithCapacity:32];
5090 - (void) setDelegate:(id)delegate {
5091 delegate_ = delegate;
5094 - (void) setPercent:(float)value {
5098 - (NSNumber *) percent {
5099 return [NSNumber numberWithFloat:percent_];
5102 - (void) setCurrent:(float)value {
5106 - (NSNumber *) current {
5107 return [NSNumber numberWithFloat:current_];
5110 - (void) setTotal:(float)value {
5114 - (NSNumber *) total {
5115 return [NSNumber numberWithFloat:total_];
5118 - (void) setSpeed:(float)value {
5122 - (NSNumber *) speed {
5123 return [NSNumber numberWithFloat:speed_];
5126 - (NSArray *) events {
5130 - (void) removeAllEvents {
5131 [events_ removeAllObjects];
5134 - (void) addEvent:(CydiaProgressEvent *)event {
5135 [events_ addObject:event];
5138 - (void) setTitle:(NSString *)text {
5142 - (NSString *) title {
5146 - (void) setFinish:(NSString *)text {
5150 - (NSString *) finish {
5151 return (id) finish_ ?: [NSNull null];
5154 - (void) setRunning:(bool)running {
5158 - (NSNumber *) running {
5159 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5164 /* Progress Controller {{{ */
5165 @interface ProgressController : CydiaWebViewController <
5168 _transient Database *database_;
5169 _H<CydiaProgressData> progress_;
5173 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5175 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5177 - (void) setTitle:(NSString *)title;
5178 - (void) setCancellable:(bool)cancellable;
5182 @implementation ProgressController
5185 [database_ setProgressDelegate:nil];
5186 [progress_ setDelegate:nil];
5190 - (void) updateCancel {
5191 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5192 initWithTitle:UCLocalize("CANCEL")
5193 style:UIBarButtonItemStylePlain
5195 action:@selector(cancel)
5196 ] autorelease] : nil)];
5199 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5200 if ((self = [super init]) != nil) {
5201 database_ = database;
5202 delegate_ = delegate;
5204 [database_ setProgressDelegate:self];
5206 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5207 [progress_ setDelegate:self];
5209 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5211 [scroller_ setBackgroundColor:[UIColor blackColor]];
5213 [[self navigationItem] setHidesBackButton:YES];
5215 [self updateCancel];
5219 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5220 [super webView:view didClearWindowObject:window forFrame:frame];
5221 [window setValue:progress_ forKey:@"cydiaProgress"];
5224 - (void) updateProgress {
5225 [self dispatchEvent:@"CydiaProgressUpdate"];
5228 - (void) viewWillAppear:(BOOL)animated {
5229 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5230 [super viewWillAppear:animated];
5234 UpdateExternalStatus(0);
5241 [delegate_ terminateWithSuccess];
5242 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5243 [delegate_ suspendWithAnimation:YES];
5245 [delegate_ suspend];*/
5257 system("/usr/bin/sbreload");
5263 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5264 SBReboot(SBSSpringBoardServerPort());
5266 reboot2(RB_AUTOBOOT);
5273 - (void) setTitle:(NSString *)title {
5274 [progress_ setTitle:title];
5275 [self updateProgress];
5278 - (UIBarButtonItem *) rightButton {
5279 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5280 initWithTitle:UCLocalize("CLOSE")
5281 style:UIBarButtonItemStylePlain
5283 action:@selector(close)
5287 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5288 UpdateExternalStatus(1);
5290 [progress_ setRunning:true];
5291 [self setTitle:title];
5292 // implicit updateProgress
5294 SHA1SumValue notifyconf; {
5296 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5299 MMap mmap(file, MMap::ReadOnly);
5301 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5302 notifyconf = sha1.Result();
5306 SHA1SumValue springlist; {
5308 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5311 MMap mmap(file, MMap::ReadOnly);
5313 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5314 springlist = sha1.Result();
5318 if (invocation != nil) {
5319 [invocation yieldToSelector:@selector(invoke)];
5320 [self setTitle:@"COMPLETE"];
5325 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5328 MMap mmap(file, MMap::ReadOnly);
5330 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5331 if (!(notifyconf == sha1.Result()))
5338 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5341 MMap mmap(file, MMap::ReadOnly);
5343 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5344 if (!(springlist == sha1.Result()))
5350 if (RestartSubstrate_)
5354 RestartSubstrate_ = false;
5357 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5358 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5359 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5360 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5361 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5365 system("su -c /usr/bin/uicache mobile");
5368 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5370 [progress_ setRunning:false];
5371 [self updateProgress];
5373 [self applyRightButton];
5376 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5377 [progress_ addEvent:event];
5378 [self updateProgress];
5381 - (bool) isProgressCancelled {
5382 return cancel_ == 2;
5387 [self updateCancel];
5390 - (void) setCancellable:(bool)cancellable {
5391 unsigned cancel(cancel_);
5395 else if (cancel_ == 0)
5398 if (cancel != cancel_)
5399 [self updateCancel];
5402 - (void) setProgressCancellable:(NSNumber *)cancellable {
5403 [self setCancellable:[cancellable boolValue]];
5406 - (void) setProgressPercent:(NSNumber *)percent {
5407 [progress_ setPercent:[percent floatValue]];
5408 [self updateProgress];
5411 - (void) setProgressStatus:(NSDictionary *)status {
5412 if (status == nil) {
5413 [progress_ setCurrent:0];
5414 [progress_ setTotal:0];
5415 [progress_ setSpeed:0];
5417 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5419 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5420 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5421 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5424 [self updateProgress];
5430 /* Cell Content View {{{ */
5431 @protocol ContentDelegate
5432 - (void) drawContentRect:(CGRect)rect;
5435 @interface ContentView : UIView {
5436 _transient id<ContentDelegate> delegate_;
5441 @implementation ContentView
5443 - (id) initWithFrame:(CGRect)frame {
5444 if ((self = [super initWithFrame:frame]) != nil) {
5445 [self setNeedsDisplayOnBoundsChange:YES];
5449 - (void) setDelegate:(id<ContentDelegate>)delegate {
5450 delegate_ = delegate;
5453 - (void) drawRect:(CGRect)rect {
5454 [super drawRect:rect];
5455 [delegate_ drawContentRect:rect];
5460 /* Cydia TableView Cell {{{ */
5461 @interface CYTableViewCell : UITableViewCell {
5462 ContentView *content_;
5468 @implementation CYTableViewCell
5475 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5476 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5478 if (view == content_) {
5479 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5480 highlighted_ = highlighted;
5483 [super _updateHighlightColorsForView:view highlighted:highlighted];
5486 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5487 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5488 highlighted_ = selected;
5490 [super setSelected:selected animated:animated];
5491 [content_ setNeedsDisplay];
5497 /* Package Cell {{{ */
5498 @interface PackageCell : CYTableViewCell <
5503 NSString *description_;
5511 - (PackageCell *) init;
5512 - (void) setPackage:(Package *)package;
5514 - (void) drawContentRect:(CGRect)rect;
5518 @implementation PackageCell
5520 - (void) clearPackage {
5531 if (description_ != nil) {
5532 [description_ release];
5536 if (source_ != nil) {
5541 if (badge_ != nil) {
5546 if (placard_ != nil) {
5556 [self clearPackage];
5560 - (PackageCell *) init {
5561 CGRect frame(CGRectMake(0, 0, 320, 74));
5562 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5563 UIView *content([self contentView]);
5564 CGRect bounds([content bounds]);
5566 content_ = [[ContentView alloc] initWithFrame:bounds];
5567 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5568 [content addSubview:content_];
5570 [content_ setDelegate:self];
5571 [content_ setOpaque:YES];
5575 - (NSString *) accessibilityLabel {
5576 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5579 - (void) setPackage:(Package *)package {
5580 [self clearPackage];
5583 Source *source = [package source];
5585 icon_ = [[package icon] retain];
5586 name_ = [[package name] retain];
5589 description_ = [package longDescription];
5590 if (description_ == nil)
5591 description_ = [package shortDescription];
5592 if (description_ != nil)
5593 description_ = [description_ retain];
5595 commercial_ = [package isCommercial];
5597 package_ = [package retain];
5599 NSString *label = nil;
5600 bool trusted = false;
5602 if (source != nil) {
5603 label = [source label];
5604 trusted = [source trusted];
5605 } else if ([[package id] isEqualToString:@"firmware"])
5606 label = UCLocalize("APPLE");
5608 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5610 NSString *from(label);
5612 NSString *section = [package simpleSection];
5613 if (section != nil && ![section isEqualToString:label]) {
5614 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5615 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5618 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5619 source_ = [from retain];
5621 if (NSString *purpose = [package primaryPurpose])
5622 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5623 badge_ = [badge_ retain];
5628 if (NSString *mode = [package_ mode]) {
5629 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5630 color = RemovingColor_;
5631 //placard = @"removing";
5633 color = InstallingColor_;
5634 //placard = @"installing";
5637 // XXX: the removing/installing placards are not @2x
5640 color = [UIColor whiteColor];
5642 if ([package installed] != nil)
5643 placard = @"installed";
5648 [content_ setBackgroundColor:color];
5651 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5652 placard_ = [placard_ retain];
5654 [self setNeedsDisplay];
5655 [content_ setNeedsDisplay];
5658 - (void) drawContentRect:(CGRect)rect {
5659 bool highlighted(highlighted_);
5660 float width([self bounds].size.width);
5663 CGContextRef context(UIGraphicsGetCurrentContext());
5664 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5665 CGContextFillRect(context, rect);
5670 rect.size = [icon_ size];
5672 rect.size.width /= 2;
5673 rect.size.height /= 2;
5675 rect.origin.x = 25 - rect.size.width / 2;
5676 rect.origin.y = 25 - rect.size.height / 2;
5678 [icon_ drawInRect:rect];
5681 if (badge_ != nil) {
5683 rect.size = [badge_ size];
5685 rect.size.width /= 2;
5686 rect.size.height /= 2;
5688 rect.origin.x = 36 - rect.size.width / 2;
5689 rect.origin.y = 36 - rect.size.height / 2;
5691 [badge_ drawInRect:rect];
5698 UISetColor(commercial_ ? Purple_ : Black_);
5699 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5700 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5703 UISetColor(commercial_ ? Purplish_ : Gray_);
5704 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5706 if (placard_ != nil)
5707 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5712 /* Section Cell {{{ */
5713 @interface SectionCell : CYTableViewCell <
5725 - (void) setSection:(Section *)section editing:(BOOL)editing;
5729 @implementation SectionCell
5731 - (void) clearSection {
5732 if (basic_ != nil) {
5737 if (section_ != nil) {
5747 if (count_ != nil) {
5754 [self clearSection];
5760 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5761 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5762 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5763 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5764 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5766 UIView *content([self contentView]);
5767 CGRect bounds([content bounds]);
5769 content_ = [[ContentView alloc] initWithFrame:bounds];
5770 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5771 [content addSubview:content_];
5772 [content_ setBackgroundColor:[UIColor whiteColor]];
5774 [content_ setDelegate:self];
5778 - (void) onSwitch:(id)sender {
5779 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5780 if (metadata == nil) {
5781 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5782 [Sections_ setObject:metadata forKey:basic_];
5785 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5789 - (void) setSection:(Section *)section editing:(BOOL)editing {
5790 if (editing != editing_) {
5792 [switch_ removeFromSuperview];
5794 [self addSubview:switch_];
5798 [self clearSection];
5800 if (section == nil) {
5801 name_ = [UCLocalize("ALL_PACKAGES") retain];
5804 basic_ = [section name];
5806 basic_ = [basic_ retain];
5808 section_ = [section localized];
5809 if (section_ != nil)
5810 section_ = [section_ retain];
5812 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5813 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5816 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5819 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5820 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5822 [content_ setNeedsDisplay];
5825 - (void) setFrame:(CGRect)frame {
5826 [super setFrame:frame];
5828 CGRect rect([switch_ frame]);
5829 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5832 - (NSString *) accessibilityLabel {
5836 - (void) drawContentRect:(CGRect)rect {
5837 bool highlighted(highlighted_ && !editing_);
5839 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5844 float width(rect.size.width);
5850 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5852 CGSize size = [count_ sizeWithFont:Font14_];
5856 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5862 /* File Table {{{ */
5863 @interface FileTable : CYViewController <
5864 UITableViewDataSource,
5867 _transient Database *database_;
5870 NSMutableArray *files_;
5874 - (id) initWithDatabase:(Database *)database;
5875 - (void) setPackage:(Package *)package;
5879 @implementation FileTable
5882 [self releaseSubviews];
5891 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5892 return files_ == nil ? 0 : [files_ count];
5895 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5899 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5900 static NSString *reuseIdentifier = @"Cell";
5902 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5904 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5905 [cell setFont:[UIFont systemFontOfSize:16]];
5907 [cell setText:[files_ objectAtIndex:indexPath.row]];
5908 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5913 - (NSURL *) navigationURL {
5914 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5918 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5920 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5921 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5922 [list_ setRowHeight:24.0f];
5923 [list_ setDataSource:self];
5924 [list_ setDelegate:self];
5925 [[self view] addSubview:list_];
5928 - (void) viewDidLoad {
5929 [super viewDidLoad];
5931 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5934 - (void) releaseSubviews {
5939 - (id) initWithDatabase:(Database *)database {
5940 if ((self = [super init]) != nil) {
5941 database_ = database;
5943 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5947 - (void) setPackage:(Package *)package {
5948 if (package_ != nil) {
5949 [package_ autorelease];
5958 [files_ removeAllObjects];
5960 if (package != nil) {
5961 package_ = [package retain];
5962 name_ = [[package id] retain];
5964 if (NSArray *files = [package files])
5965 [files_ addObjectsFromArray:files];
5967 if ([files_ count] != 0) {
5968 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5969 [files_ removeObjectAtIndex:0];
5970 [files_ sortUsingSelector:@selector(compareByPath:)];
5972 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5973 [stack addObject:@"/"];
5975 for (int i(0), e([files_ count]); i != e; ++i) {
5976 NSString *file = [files_ objectAtIndex:i];
5977 while (![file hasPrefix:[stack lastObject]])
5978 [stack removeLastObject];
5979 NSString *directory = [stack lastObject];
5980 [stack addObject:[file stringByAppendingString:@"/"]];
5981 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5982 ([stack count] - 2) * 3, "",
5983 [file substringFromIndex:[directory length]]
5992 - (void) reloadData {
5995 [self setPackage:[database_ packageWithName:name_]];
6000 /* Package Controller {{{ */
6001 @interface CYPackageController : CydiaWebViewController <
6002 UIActionSheetDelegate
6004 _transient Database *database_;
6005 _H<Package> package_;
6008 _H<NSMutableArray> buttons_;
6009 _H<UIBarButtonItem> button_;
6012 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
6016 @implementation CYPackageController
6018 - (NSURL *) navigationURL {
6019 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6022 /* XXX: this is not safe at all... localization of /fail/ */
6023 - (void) _clickButtonWithName:(NSString *)name {
6024 if ([name isEqualToString:UCLocalize("CLEAR")])
6025 [delegate_ clearPackage:package_];
6026 else if ([name isEqualToString:UCLocalize("INSTALL")])
6027 [delegate_ installPackage:package_];
6028 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6029 [delegate_ installPackage:package_];
6030 else if ([name isEqualToString:UCLocalize("REMOVE")])
6031 [delegate_ removePackage:package_];
6032 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6033 [delegate_ installPackage:package_];
6034 else _assert(false);
6037 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6038 NSString *context([sheet context]);
6040 if ([context isEqualToString:@"modify"]) {
6041 if (button != [sheet cancelButtonIndex]) {
6042 NSString *buttonName = [buttons_ objectAtIndex:button];
6043 [self _clickButtonWithName:buttonName];
6046 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6050 - (bool) _allowJavaScriptPanel {
6055 - (void) _customButtonClicked {
6056 int count([buttons_ count]);
6061 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6063 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6064 [buttons addObjectsFromArray:buttons_];
6066 UIActionSheet *sheet = [[[UIActionSheet alloc]
6069 cancelButtonTitle:nil
6070 destructiveButtonTitle:nil
6071 otherButtonTitles:nil
6074 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6076 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6077 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6079 [sheet setContext:@"modify"];
6081 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6085 // We don't want to allow non-commercial packages to do custom things to the install button,
6086 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6087 - (void) customButtonClicked {
6089 [super customButtonClicked];
6091 [self _customButtonClicked];
6094 - (void) reloadButtonClicked {
6095 // Don't reload a commerical package by tapping the loading button,
6096 // but if it's not an Install button, we should forward it on.
6097 if (![package_ uninstalled])
6098 [self _customButtonClicked];
6101 - (void) applyLoadingTitle {
6102 // Don't show "Loading" as the title. Ever.
6105 - (UIBarButtonItem *) rightButton {
6110 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
6111 if ((self = [super init]) != nil) {
6112 database_ = database;
6113 buttons_ = [NSMutableArray arrayWithCapacity:4];
6114 name_ = [NSString stringWithString:name];
6115 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
6119 - (void) reloadData {
6122 package_ = [database_ packageWithName:name_];
6124 [buttons_ removeAllObjects];
6126 if (package_ != nil) {
6127 [(Package *) package_ parse];
6129 commercial_ = [package_ isCommercial];
6131 if ([package_ mode] != nil)
6132 [buttons_ addObject:UCLocalize("CLEAR")];
6133 if ([package_ source] == nil);
6134 else if ([package_ upgradableAndEssential:NO])
6135 [buttons_ addObject:UCLocalize("UPGRADE")];
6136 else if ([package_ uninstalled])
6137 [buttons_ addObject:UCLocalize("INSTALL")];
6139 [buttons_ addObject:UCLocalize("REINSTALL")];
6140 if (![package_ uninstalled])
6141 [buttons_ addObject:UCLocalize("REMOVE")];
6145 switch ([buttons_ count]) {
6146 case 0: title = nil; break;
6147 case 1: title = [buttons_ objectAtIndex:0]; break;
6148 default: title = UCLocalize("MODIFY"); break;
6151 button_ = [[[UIBarButtonItem alloc]
6153 style:UIBarButtonItemStylePlain
6155 action:@selector(customButtonClicked)
6159 - (bool) isLoading {
6160 return commercial_ ? [super isLoading] : false;
6166 /* Package List Controller {{{ */
6167 @interface PackageListController : CYViewController <
6168 UITableViewDataSource,
6171 _transient Database *database_;
6173 NSMutableArray *packages_;
6174 NSMutableArray *sections_;
6176 NSMutableArray *index_;
6177 NSMutableDictionary *indices_;
6181 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6182 - (void) setDelegate:(id)delegate;
6183 - (void) resetCursor;
6187 @implementation PackageListController
6190 [packages_ release];
6191 [sections_ release];
6200 - (void) deselectWithAnimation:(BOOL)animated {
6201 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6204 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6205 CGRect base = [[self view] bounds];
6206 base.size.height -= bounds.size.height;
6207 base.origin = [list_ frame].origin;
6209 [UIView beginAnimations:nil context:NULL];
6210 [UIView setAnimationBeginsFromCurrentState:YES];
6211 [UIView setAnimationCurve:curve];
6212 [UIView setAnimationDuration:duration];
6213 [list_ setFrame:base];
6214 [UIView commitAnimations];
6217 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6218 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6221 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6222 [self resizeForKeyboardBounds:bounds duration:0];
6225 - (void) keyboardWillShow:(NSNotification *)notification {
6228 NSTimeInterval duration;
6229 UIViewAnimationCurve curve;
6230 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6231 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6232 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6233 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6235 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);
6236 UIViewController *base = self;
6237 while ([base parentViewController] != nil)
6238 base = [base parentViewController];
6239 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6240 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6242 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6245 - (void) keyboardWillHide:(NSNotification *)notification {
6246 NSTimeInterval duration;
6247 UIViewAnimationCurve curve;
6248 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6249 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6251 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6254 - (void) viewWillAppear:(BOOL)animated {
6255 [super viewWillAppear:animated];
6257 [self resizeForKeyboardBounds:CGRectZero];
6258 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6259 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6262 - (void) viewWillDisappear:(BOOL)animated {
6263 [super viewWillDisappear:animated];
6265 [self resizeForKeyboardBounds:CGRectZero];
6266 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6267 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6270 - (void) viewDidAppear:(BOOL)animated {
6271 [super viewDidAppear:animated];
6272 [self deselectWithAnimation:animated];
6275 - (void) didSelectPackage:(Package *)package {
6276 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6277 [view setDelegate:delegate_];
6278 [[self navigationController] pushViewController:view animated:YES];
6281 #if TryIndexedCollation
6282 + (BOOL) hasIndexedCollation {
6283 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6287 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6288 NSInteger count([sections_ count]);
6289 return count == 0 ? 1 : count;
6292 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6293 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6295 return [[sections_ objectAtIndex:section] name];
6298 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6299 if ([sections_ count] == 0)
6301 return [[sections_ objectAtIndex:section] count];
6304 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6305 @synchronized (database_) {
6306 if ([database_ era] != era_)
6309 Section *section([sections_ objectAtIndex:[path section]]);
6310 NSInteger row([path row]);
6311 Package *package([packages_ objectAtIndex:([section row] + row)]);
6312 return [[package retain] autorelease];
6315 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6316 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6318 cell = [[[PackageCell alloc] init] autorelease];
6319 [cell setPackage:[self packageAtIndexPath:path]];
6323 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6324 Package *package([self packageAtIndexPath:path]);
6325 package = [database_ packageWithName:[package id]];
6326 [self didSelectPackage:package];
6329 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6330 // XXX: is 20 the most optimal number here?
6331 return [packages_ count] > 20 ? index_ : nil;
6334 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6335 #if TryIndexedCollation
6336 if ([[self class] hasIndexedCollation]) {
6337 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6344 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6345 if ((self = [super init]) != nil) {
6346 database_ = database;
6347 title_ = [title copy];
6348 [[self navigationItem] setTitle:title_];
6350 #if TryIndexedCollation
6351 if ([[self class] hasIndexedCollation])
6352 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6355 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6357 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6359 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6360 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6362 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6363 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6364 [list_ setRowHeight:73];
6365 [[self view] addSubview:list_];
6367 [list_ setDataSource:self];
6368 [list_ setDelegate:self];
6372 - (void) setDelegate:(id)delegate {
6373 delegate_ = delegate;
6376 - (bool) hasPackage:(Package *)package {
6380 - (void) reloadData {
6383 era_ = [database_ era];
6384 NSArray *packages = [database_ packages];
6386 [packages_ removeAllObjects];
6387 [sections_ removeAllObjects];
6389 _profile(PackageTable$reloadData$Filter)
6390 for (Package *package in packages)
6391 if ([self hasPackage:package])
6392 [packages_ addObject:package];
6395 [indices_ removeAllObjects];
6397 Section *section = nil;
6399 #if TryIndexedCollation
6400 if ([[self class] hasIndexedCollation]) {
6401 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6402 NSArray *titles = [collation sectionIndexTitles];
6405 _profile(PackageTable$reloadData$Section)
6406 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6410 _profile(PackageTable$reloadData$Section$Package)
6411 package = [packages_ objectAtIndex:offset];
6412 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6415 while (secidx < index) {
6418 _profile(PackageTable$reloadData$Section$Allocate)
6419 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6422 _profile(PackageTable$reloadData$Section$Add)
6423 [sections_ addObject:section];
6427 [section addToCount];
6433 [index_ removeAllObjects];
6435 _profile(PackageTable$reloadData$Section)
6436 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6440 _profile(PackageTable$reloadData$Section$Package)
6441 package = [packages_ objectAtIndex:offset];
6442 index = [package index];
6445 if (section == nil || [section index] != index) {
6446 _profile(PackageTable$reloadData$Section$Allocate)
6447 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6450 [index_ addObject:[section name]];
6451 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6453 _profile(PackageTable$reloadData$Section$Add)
6454 [sections_ addObject:section];
6458 [section addToCount];
6463 _profile(PackageTable$reloadData$List)
6468 - (void) resetCursor {
6469 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6474 /* Filtered Package List Controller {{{ */
6475 @interface FilteredPackageListController : PackageListController {
6481 - (void) setObject:(id)object;
6482 - (void) setObject:(id)object forFilter:(SEL)filter;
6484 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6488 @implementation FilteredPackageListController
6496 - (void) setFilter:(SEL)filter {
6499 /* XXX: this is an unsafe optimization of doomy hell */
6500 Method method(class_getInstanceMethod([Package class], filter));
6501 _assert(method != NULL);
6502 imp_ = method_getImplementation(method);
6503 _assert(imp_ != NULL);
6506 - (void) setObject:(id)object {
6512 object_ = [object retain];
6515 - (void) setObject:(id)object forFilter:(SEL)filter {
6516 [self setFilter:filter];
6517 [self setObject:object];
6520 - (bool) hasPackage:(Package *)package {
6521 _profile(FilteredPackageTable$hasPackage)
6522 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6526 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6527 if ((self = [super initWithDatabase:database title:title]) != nil) {
6528 [self setFilter:filter];
6529 [self setObject:object];
6536 /* Home Controller {{{ */
6537 @interface HomeController : CydiaWebViewController {
6542 @implementation HomeController
6545 if ((self = [super init]) != nil) {
6546 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6551 - (NSURL *) navigationURL {
6552 return [NSURL URLWithString:@"cydia://home"];
6555 - (void) aboutButtonClicked {
6556 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6558 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6559 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6560 [alert setCancelButtonIndex:0];
6563 @"Copyright (C) 2008-2011\n"
6564 "Jay Freeman (saurik)\n"
6565 "saurik@saurik.com\n"
6566 "http://www.saurik.com/"
6572 - (void) viewDidLoad {
6573 [super viewDidLoad];
6575 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6576 initWithTitle:UCLocalize("ABOUT")
6577 style:UIBarButtonItemStylePlain
6579 action:@selector(aboutButtonClicked)
6583 - (void) unloadData {
6590 /* Manage Controller {{{ */
6591 @interface ManageController : CydiaWebViewController {
6594 - (void) queueStatusDidChange;
6598 @implementation ManageController
6601 if ((self = [super init]) != nil) {
6602 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6606 - (NSURL *) navigationURL {
6607 return [NSURL URLWithString:@"cydia://manage"];
6610 - (void) viewDidLoad {
6611 [super viewDidLoad];
6613 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6614 initWithTitle:UCLocalize("SETTINGS")
6615 style:UIBarButtonItemStylePlain
6617 action:@selector(settingsButtonClicked)
6620 [self queueStatusDidChange];
6623 - (void) settingsButtonClicked {
6624 [delegate_ showSettings];
6628 - (void) queueButtonClicked {
6632 - (void) applyLoadingTitle {
6633 // Disable "Loading" title.
6636 - (void) applyRightButton {
6637 // Disable right button.
6641 - (void) queueStatusDidChange {
6643 if (!IsWildcat_ && Queuing_) {
6644 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6645 initWithTitle:UCLocalize("QUEUE")
6646 style:UIBarButtonItemStyleDone
6648 action:@selector(queueButtonClicked)
6651 [[self navigationItem] setRightBarButtonItem:nil];
6656 - (bool) isLoading {
6657 // Never show as loading.
6664 /* Refresh Bar {{{ */
6665 @interface RefreshBar : UINavigationBar {
6666 UIProgressIndicator *indicator_;
6667 UITextLabel *prompt_;
6668 UIProgressBar *progress_;
6669 UINavigationButton *cancel_;
6674 @implementation RefreshBar
6677 [indicator_ release];
6679 [progress_ release];
6684 - (void) positionViews {
6685 CGRect frame = [cancel_ frame];
6686 frame.size = [cancel_ sizeThatFits:frame.size];
6687 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6688 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6689 [cancel_ setFrame:frame];
6691 CGSize prgsize = {75, 100};
6693 [self frame].size.width - prgsize.width - 10,
6694 ([self frame].size.height - prgsize.height) / 2
6696 [progress_ setFrame:prgrect];
6698 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6699 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6700 CGRect indrect = {{indoffset, indoffset}, indsize};
6701 [indicator_ setFrame:indrect];
6703 CGSize prmsize = {215, indsize.height + 4};
6705 indoffset * 2 + indsize.width,
6706 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6708 [prompt_ setFrame:prmrect];
6711 - (void) setFrame:(CGRect)frame {
6712 [super setFrame:frame];
6713 [self positionViews];
6716 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6717 if ((self = [super initWithFrame:frame]) != nil) {
6718 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6720 [self setBarStyle:UIBarStyleBlack];
6722 UIBarStyle barstyle([self _barStyle:NO]);
6723 bool ugly(barstyle == UIBarStyleDefault);
6725 UIProgressIndicatorStyle style = ugly ?
6726 UIProgressIndicatorStyleMediumBrown :
6727 UIProgressIndicatorStyleMediumWhite;
6729 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6730 [indicator_ setStyle:style];
6731 [indicator_ startAnimation];
6732 [self addSubview:indicator_];
6734 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6735 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6736 [prompt_ setBackgroundColor:[UIColor clearColor]];
6737 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6738 [self addSubview:prompt_];
6740 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6741 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6742 [progress_ setStyle:0];
6743 [self addSubview:progress_];
6745 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6746 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6747 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6748 [cancel_ setBarStyle:barstyle];
6750 [self positionViews];
6754 - (void) setCancellable:(bool)cancellable {
6756 [self addSubview:cancel_];
6758 [cancel_ removeFromSuperview];
6762 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6763 [progress_ setProgress:0];
6767 [self setCancellable:NO];
6770 - (void) setPrompt:(NSString *)prompt {
6771 [prompt_ setText:prompt];
6774 - (void) setProgress:(float)progress {
6775 [progress_ setProgress:progress];
6781 /* Cydia Navigation Controller Interface {{{ */
6782 @interface UINavigationController (Cydia)
6784 - (NSArray *) navigationURLCollection;
6785 - (void) unloadData;
6790 /* Cydia Tab Bar Controller {{{ */
6791 @interface CYTabBarController : UITabBarController <
6792 UITabBarControllerDelegate,
6795 _transient Database *database_;
6796 RefreshBar *refreshbar_;
6800 // XXX: ok, "updatedelegate_"?...
6801 _transient NSObject<CydiaDelegate> *updatedelegate_;
6804 UIViewController *remembered_;
6805 _transient UIViewController *transient_;
6808 - (NSArray *) navigationURLCollection;
6809 - (void) dropBar:(BOOL)animated;
6810 - (void) beginUpdate;
6811 - (void) raiseBar:(BOOL)animated;
6813 - (void) unloadData;
6817 @implementation CYTabBarController
6819 - (void) setUnselectedViewController:(UIViewController *)transient {
6820 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6821 if (transient != nil) {
6822 if (transient_ == nil)
6823 remembered_ = [[controllers objectAtIndex:0] retain];
6824 transient_ = transient;
6825 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6826 [controllers replaceObjectAtIndex:0 withObject:transient_];
6827 [self setSelectedIndex:0];
6828 [self setViewControllers:controllers];
6829 [self concealTabBarSelection];
6830 } else if (remembered_ != nil) {
6831 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6832 transient_ = transient;
6833 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6834 [remembered_ release];
6836 [self setViewControllers:controllers];
6837 [self revealTabBarSelection];
6841 - (UIViewController *) unselectedViewController {
6845 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6846 if ([self unselectedViewController])
6847 [self setUnselectedViewController:nil];
6850 - (NSArray *) navigationURLCollection {
6851 NSMutableArray *items([NSMutableArray array]);
6853 // XXX: Should this deal with transient view controllers?
6854 for (id navigation in [self viewControllers]) {
6855 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6857 [items addObject:stack];
6863 - (void) unloadData {
6864 UIViewController *selected([self selectedViewController]);
6865 for (UINavigationController *controller in [self viewControllers])
6866 [controller unloadData];
6868 [selected reloadData];
6870 if (UIViewController *unselected = [self unselectedViewController])
6871 [unselected reloadData];
6877 [refreshbar_ release];
6878 [[NSNotificationCenter defaultCenter] removeObserver:self];
6883 - (id) initWithDatabase:(Database *)database {
6884 if ((self = [super init]) != nil) {
6885 database_ = database;
6886 [self setDelegate:self];
6888 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6889 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6891 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6895 - (void) setUpdate:(NSDate *)date {
6899 - (void) beginUpdate {
6900 [refreshbar_ start];
6903 [updatedelegate_ retainNetworkActivityIndicator];
6907 detachNewThreadSelector:@selector(performUpdate)
6913 - (void) performUpdate { _pooled
6915 status.setDelegate(self);
6916 [database_ updateWithStatus:status];
6919 performSelectorOnMainThread:@selector(completeUpdate)
6925 - (void) stopUpdateWithSelector:(SEL)selector {
6927 [updatedelegate_ releaseNetworkActivityIndicator];
6929 [self raiseBar:YES];
6932 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6935 - (void) completeUpdate {
6938 [self stopUpdateWithSelector:@selector(reloadData)];
6941 - (void) cancelUpdate {
6942 [self stopUpdateWithSelector:@selector(updateData)];
6945 - (void) cancelPressed {
6946 [self cancelUpdate];
6953 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6954 [refreshbar_ setPrompt:[event compoundMessage]];
6957 - (bool) isProgressCancelled {
6961 - (void) setProgressCancellable:(NSNumber *)cancellable {
6962 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6965 - (void) setProgressPercent:(NSNumber *)percent {
6966 [refreshbar_ setProgress:[percent floatValue]];
6969 - (void) setProgressStatus:(NSDictionary *)status {
6971 [self setProgressPercent:[status objectForKey:@"Percent"]];
6974 - (void) setUpdateDelegate:(id)delegate {
6975 updatedelegate_ = delegate;
6978 - (CGFloat) statusBarHeight {
6979 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6980 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6982 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6986 - (UIView *) transitionView {
6987 if ([self respondsToSelector:@selector(_transitionView)])
6988 return [self _transitionView];
6990 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6993 - (void) dropBar:(BOOL)animated {
6998 UIView *transition([self transitionView]);
6999 [[self view] addSubview:refreshbar_];
7001 CGRect barframe([refreshbar_ frame]);
7003 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7004 barframe.origin.y = [self statusBarHeight];
7006 barframe.origin.y = 0;
7008 [refreshbar_ setFrame:barframe];
7011 [UIView beginAnimations:nil context:NULL];
7013 CGRect viewframe = [transition frame];
7014 viewframe.origin.y += barframe.size.height;
7015 viewframe.size.height -= barframe.size.height;
7016 [transition setFrame:viewframe];
7019 [UIView commitAnimations];
7021 // Ensure bar has the proper width for our view, it might have changed
7022 barframe.size.width = viewframe.size.width;
7023 [refreshbar_ setFrame:barframe];
7025 // XXX: fix Apple's layout bug
7026 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7029 - (void) raiseBar:(BOOL)animated {
7034 UIView *transition([self transitionView]);
7035 [refreshbar_ removeFromSuperview];
7037 CGRect barframe([refreshbar_ frame]);
7040 [UIView beginAnimations:nil context:NULL];
7042 CGRect viewframe = [transition frame];
7043 viewframe.origin.y -= barframe.size.height;
7044 viewframe.size.height += barframe.size.height;
7045 [transition setFrame:viewframe];
7048 [UIView commitAnimations];
7050 // XXX: fix Apple's layout bug
7051 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7055 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7056 // XXX: fix Apple's layout bug
7057 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7061 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7062 bool dropped(dropped_);
7067 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7072 // XXX: fix Apple's layout bug
7073 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7076 - (void) statusBarFrameChanged:(NSNotification *)notification {
7086 /* Cydia Navigation Controller Implementation {{{ */
7087 @implementation UINavigationController (Cydia)
7089 - (NSArray *) navigationURLCollection {
7090 NSMutableArray *stack([NSMutableArray array]);
7092 for (CYViewController *controller in [self viewControllers]) {
7093 NSString *url = [[controller navigationURL] absoluteString];
7095 [stack addObject:url];
7101 - (void) reloadData {
7104 if (UIViewController *visible = [self visibleViewController])
7105 [visible reloadData];
7108 - (void) unloadData {
7109 for (CYViewController *page in [self viewControllers])
7118 /* Cydia:// Protocol {{{ */
7119 @interface CydiaURLProtocol : NSURLProtocol {
7124 @implementation CydiaURLProtocol
7126 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7127 NSURL *url([request URL]);
7131 NSString *scheme([[url scheme] lowercaseString]);
7132 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7134 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7140 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7144 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7145 id<NSURLProtocolClient> client([self client]);
7147 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7149 NSData *data(UIImagePNGRepresentation(icon));
7151 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7152 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7153 [client URLProtocol:self didLoadData:data];
7154 [client URLProtocolDidFinishLoading:self];
7158 - (void) startLoading {
7159 id<NSURLProtocolClient> client([self client]);
7160 NSURLRequest *request([self request]);
7162 NSURL *url([request URL]);
7163 NSString *href([url absoluteString]);
7164 NSString *scheme([[url scheme] lowercaseString]);
7168 if ([scheme isEqualToString:@"cydia"])
7169 path = [href substringFromIndex:8];
7170 else if ([scheme isEqualToString:@"about"])
7171 path = [href substringFromIndex:12];
7172 else _assert(false);
7174 NSRange slash([path rangeOfString:@"/"]);
7177 if (slash.location == NSNotFound) {
7181 command = [path substringToIndex:slash.location];
7182 path = [path substringFromIndex:(slash.location + 1)];
7185 Database *database([Database sharedInstance]);
7187 if ([command isEqualToString:@"package-icon"]) {
7190 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7191 Package *package([database packageWithName:path]);
7194 UIImage *icon([package icon]);
7195 [self _returnPNGWithImage:icon forRequest:request];
7196 } else if ([command isEqualToString:@"source-icon"]) {
7199 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7200 NSString *source(Simplify(path));
7201 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7203 icon = [UIImage applicationImageNamed:@"unknown.png"];
7204 [self _returnPNGWithImage:icon forRequest:request];
7205 } else if ([command isEqualToString:@"uikit-image"]) {
7208 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7209 UIImage *icon(_UIImageWithName(path));
7210 [self _returnPNGWithImage:icon forRequest:request];
7211 } else if ([command isEqualToString:@"section-icon"]) {
7214 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7215 NSString *section(Simplify(path));
7216 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7218 icon = [UIImage applicationImageNamed:@"unknown.png"];
7219 [self _returnPNGWithImage:icon forRequest:request];
7221 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7225 - (void) stopLoading {
7231 /* Section Controller {{{ */
7232 @interface SectionController : FilteredPackageListController {
7233 _H<NSString> section_;
7236 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7240 @implementation SectionController
7242 - (NSURL *) navigationURL {
7243 NSString *name = section_;
7247 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7250 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7253 title = UCLocalize("ALL_PACKAGES");
7254 else if (![name isEqual:@""])
7255 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7257 title = UCLocalize("NO_SECTION");
7259 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7266 /* Sections Controller {{{ */
7267 @interface SectionsController : CYViewController <
7268 UITableViewDataSource,
7271 _transient Database *database_;
7272 NSMutableArray *sections_;
7273 NSMutableArray *filtered_;
7277 - (id) initWithDatabase:(Database *)database;
7278 - (void) editButtonClicked;
7282 @implementation SectionsController
7285 [self releaseSubviews];
7286 [sections_ release];
7287 [filtered_ release];
7292 - (NSURL *) navigationURL {
7293 return [NSURL URLWithString:@"cydia://sections"];
7296 - (void) updateNavigationItem {
7297 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7298 if ([sections_ count] == 0) {
7299 [[self navigationItem] setRightBarButtonItem:nil];
7301 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7302 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7304 action:@selector(editButtonClicked)
7305 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7309 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7310 [super setEditing:editing animated:animated];
7315 [delegate_ updateData];
7317 [self updateNavigationItem];
7320 - (void) viewDidAppear:(BOOL)animated {
7321 [super viewDidAppear:animated];
7322 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7325 - (void) viewWillDisappear:(BOOL)animated {
7326 [super viewWillDisappear:animated];
7327 if ([self isEditing]) [self setEditing:NO];
7330 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7331 Section *section = nil;
7332 int index = [indexPath row];
7333 if (![self isEditing]) {
7336 section = [filtered_ objectAtIndex:index];
7338 section = [sections_ objectAtIndex:index];
7343 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7344 if ([self isEditing])
7345 return [sections_ count];
7347 return [filtered_ count] + 1;
7350 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7354 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7355 static NSString *reuseIdentifier = @"SectionCell";
7357 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7359 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7361 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7366 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7367 if ([self isEditing])
7370 Section *section = [self sectionAtIndexPath:indexPath];
7372 SectionController *controller = [[[SectionController alloc]
7373 initWithDatabase:database_
7374 section:[section name]
7376 [controller setDelegate:delegate_];
7378 [[self navigationController] pushViewController:controller animated:YES];
7382 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7384 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7385 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7386 [list_ setRowHeight:45.0f];
7387 [list_ setDataSource:self];
7388 [list_ setDelegate:self];
7389 [[self view] addSubview:list_];
7392 - (void) viewDidLoad {
7393 [super viewDidLoad];
7395 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7398 - (void) releaseSubviews {
7403 - (id) initWithDatabase:(Database *)database {
7404 if ((self = [super init]) != nil) {
7405 database_ = database;
7407 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7408 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7412 - (void) reloadData {
7415 NSArray *packages = [database_ packages];
7417 [sections_ removeAllObjects];
7418 [filtered_ removeAllObjects];
7420 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7423 for (Package *package in packages) {
7424 NSString *name([package section]);
7425 NSString *key(name == nil ? @"" : name);
7429 _profile(SectionsView$reloadData$Section)
7430 section = [sections objectForKey:key];
7431 if (section == nil) {
7432 _profile(SectionsView$reloadData$Section$Allocate)
7433 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7434 [sections setObject:section forKey:key];
7439 [section addToCount];
7441 _profile(SectionsView$reloadData$Filter)
7442 if (![package valid] || ![package visible])
7450 [sections_ addObjectsFromArray:[sections allValues]];
7452 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7454 for (Section *section in sections_) {
7455 size_t count([section row]);
7459 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7460 [section setCount:count];
7461 [filtered_ addObject:section];
7464 [self updateNavigationItem];
7469 - (void) editButtonClicked {
7470 [self setEditing:![self isEditing] animated:YES];
7476 /* Changes Controller {{{ */
7477 @interface ChangesController : CYViewController <
7478 UITableViewDataSource,
7481 _transient Database *database_;
7483 CFMutableArrayRef packages_;
7484 NSMutableArray *sections_;
7489 - (id) initWithDatabase:(Database *)database;
7493 @implementation ChangesController
7496 [self releaseSubviews];
7497 CFRelease(packages_);
7498 [sections_ release];
7503 - (NSURL *) navigationURL {
7504 return [NSURL URLWithString:@"cydia://changes"];
7507 - (void) viewDidAppear:(BOOL)animated {
7508 [super viewDidAppear:animated];
7509 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7512 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7513 NSInteger count([sections_ count]);
7514 return count == 0 ? 1 : count;
7517 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7518 if ([sections_ count] == 0)
7520 return [[sections_ objectAtIndex:section] name];
7523 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7524 if ([sections_ count] == 0)
7526 return [[sections_ objectAtIndex:section] count];
7529 - (Package *) packageAtIndex:(NSUInteger)index {
7530 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7533 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7534 @synchronized (database_) {
7535 if ([database_ era] != era_)
7538 NSUInteger sectionIndex([path section]);
7539 if (sectionIndex >= [sections_ count])
7541 Section *section([sections_ objectAtIndex:sectionIndex]);
7542 NSInteger row([path row]);
7543 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7546 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7547 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7549 cell = [[[PackageCell alloc] init] autorelease];
7550 [cell setPackage:[self packageAtIndexPath:path]];
7554 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7555 Package *package([self packageAtIndexPath:path]);
7556 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7557 [view setDelegate:delegate_];
7558 [[self navigationController] pushViewController:view animated:YES];
7562 - (void) refreshButtonClicked {
7563 [delegate_ beginUpdate];
7564 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7567 - (void) upgradeButtonClicked {
7568 [delegate_ distUpgrade];
7572 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7574 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7575 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7576 [list_ setRowHeight:73];
7577 [list_ setDataSource:self];
7578 [list_ setDelegate:self];
7579 [[self view] addSubview:list_];
7582 - (void) viewDidLoad {
7583 [super viewDidLoad];
7585 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7588 - (void) releaseSubviews {
7593 - (id) initWithDatabase:(Database *)database {
7594 if ((self = [super init]) != nil) {
7595 database_ = database;
7597 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7598 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7602 // this mostly works because reloadData (below) is @synchronized (database_)
7603 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7604 - (void) _reloadPackages:(NSArray *)packages {
7605 CFRelease(packages_);
7606 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7609 _profile(ChangesController$_reloadPackages$Filter)
7610 for (Package *package in packages)
7611 if ([package upgradableAndEssential:YES] || [package visible])
7612 CFArrayAppendValue(packages_, package);
7615 _profile(ChangesController$_reloadPackages$radixSort)
7616 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7621 - (void) _reloadData {
7622 @synchronized (database_) {
7623 era_ = [database_ era];
7624 NSArray *packages = [database_ packages];
7626 [sections_ removeAllObjects];
7629 UIProgressHUD *hud([delegate_ addProgressHUD]);
7630 [hud setText:UCLocalize("LOADING")];
7631 //NSLog(@"HUD:%@::%@", delegate_, hud);
7632 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7633 [delegate_ removeProgressHUD:hud];
7635 [self _reloadPackages:packages];
7638 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7639 Section *ignored = nil;
7640 Section *section = nil;
7644 bool unseens = false;
7646 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7648 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7649 Package *package = [self packageAtIndex:offset];
7651 BOOL uae = [package upgradableAndEssential:YES];
7655 time_t seen([package seen]);
7657 if (section == nil || last != seen) {
7661 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7664 _profile(ChangesController$reloadData$Allocate)
7665 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7666 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7667 [sections_ addObject:section];
7671 [section addToCount];
7672 } else if ([package ignored]) {
7673 if (ignored == nil) {
7674 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7676 [ignored addToCount];
7679 [upgradable addToCount];
7684 CFRelease(formatter);
7687 Section *last = [sections_ lastObject];
7688 size_t count = [last count];
7689 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7690 [sections_ removeLastObject];
7693 if ([ignored count] != 0)
7694 [sections_ insertObject:ignored atIndex:0];
7696 [sections_ insertObject:upgradable atIndex:0];
7701 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7702 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7703 style:UIBarButtonItemStylePlain
7705 action:@selector(upgradeButtonClicked)
7708 if (![delegate_ updating])
7709 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7710 initWithTitle:UCLocalize("REFRESH")
7711 style:UIBarButtonItemStylePlain
7713 action:@selector(refreshButtonClicked)
7719 - (void) reloadData {
7721 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7726 /* Search Controller {{{ */
7727 @interface SearchController : FilteredPackageListController <
7730 _H<UISearchBar> search_;
7734 - (id) initWithDatabase:(Database *)database;
7735 - (void) setSearchTerm:(NSString *)term;
7736 - (void) reloadData;
7740 @implementation SearchController
7743 [search_ setDelegate:nil];
7747 - (NSURL *) navigationURL {
7748 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7749 return [NSURL URLWithString:@"cydia://search"];
7751 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7754 - (void) setSearchTerm:(NSString *)searchTerm {
7755 [search_ setText:searchTerm];
7759 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7760 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7761 [search_ resignFirstResponder];
7765 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7766 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7770 - (id) initWithDatabase:(Database *)database {
7771 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7772 search_ = [[[UISearchBar alloc] init] autorelease];
7773 [search_ setDelegate:self];
7777 - (void) viewDidAppear:(BOOL)animated {
7778 [super viewDidAppear:animated];
7780 if (!searchloaded_) {
7781 searchloaded_ = YES;
7782 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7783 [search_ layoutSubviews];
7784 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7786 UITextField *textField;
7787 if ([search_ respondsToSelector:@selector(searchField)])
7788 textField = [search_ searchField];
7790 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7792 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7793 [textField setEnablesReturnKeyAutomatically:NO];
7794 [[self navigationItem] setTitleView:textField];
7798 - (void) reloadData {
7799 [self setObject:[search_ text]];
7805 - (void) didSelectPackage:(Package *)package {
7806 [search_ resignFirstResponder];
7807 [super didSelectPackage:package];
7812 /* Package Settings Controller {{{ */
7813 @interface PackageSettingsController : CYViewController <
7814 UITableViewDataSource,
7817 _transient Database *database_;
7820 UITableView *table_;
7821 UISwitch *subscribedSwitch_;
7822 UISwitch *ignoredSwitch_;
7823 UITableViewCell *subscribedCell_;
7824 UITableViewCell *ignoredCell_;
7827 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7831 @implementation PackageSettingsController
7834 [self releaseSubviews];
7841 - (NSURL *) navigationURL {
7842 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7845 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7846 if (package_ == nil)
7849 if ([package_ installed] == nil)
7855 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7856 if (package_ == nil)
7859 // both sections contain just one item right now.
7863 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7867 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7869 return UCLocalize("SHOW_ALL_CHANGES_EX");
7871 return UCLocalize("IGNORE_UPGRADES_EX");
7874 - (void) onSubscribed:(id)control {
7875 bool value([control isOn]);
7876 if (package_ == nil)
7878 if ([package_ setSubscribed:value])
7879 [delegate_ updateData];
7882 - (void) _updateIgnored {
7883 const char *package([name_ UTF8String]);
7884 bool on([ignoredSwitch_ isOn]);
7886 pid_t pid(ExecFork());
7888 FILE *dpkg(popen("dpkg --set-selections", "w"));
7889 fwrite(package, strlen(package), 1, dpkg);
7892 fwrite(" hold\n", 6, 1, dpkg);
7894 fwrite(" install\n", 9, 1, dpkg);
7904 int result(waitpid(pid, &status, 0));
7907 _assert(result == pid);
7913 - (void) onIgnored:(id)control {
7914 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7915 [invocation setTarget:self];
7916 [invocation setSelector:@selector(_updateIgnored)];
7918 [delegate_ reloadDataWithInvocation:invocation];
7921 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7922 if (package_ == nil)
7925 switch ([indexPath section]) {
7926 case 0: return subscribedCell_;
7927 case 1: return ignoredCell_;
7936 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7938 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7939 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7940 [table_ setDataSource:self];
7941 [table_ setDelegate:self];
7942 [[self view] addSubview:table_];
7944 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7945 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7946 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7948 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7949 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7950 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7952 subscribedCell_ = [[UITableViewCell alloc] init];
7953 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7954 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7955 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7957 ignoredCell_ = [[UITableViewCell alloc] init];
7958 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7959 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7960 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7963 - (void) viewDidLoad {
7964 [super viewDidLoad];
7966 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7969 - (void) releaseSubviews {
7970 [ignoredCell_ release];
7973 [subscribedCell_ release];
7974 subscribedCell_ = nil;
7979 [ignoredSwitch_ release];
7980 ignoredSwitch_ = nil;
7982 [subscribedSwitch_ release];
7983 subscribedSwitch_ = nil;
7986 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7987 if ((self = [super init]) != nil) {
7988 database_ = database;
7989 name_ = [package retain];
7993 - (void) reloadData {
7996 if (package_ != nil)
7997 [package_ autorelease];
7998 package_ = [database_ packageWithName:name_];
8000 if (package_ != nil) {
8001 package_ = [package_ retain];
8002 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8003 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8004 } // XXX: what now, G?
8006 [table_ reloadData];
8012 /* Installed Controller {{{ */
8013 @interface InstalledController : FilteredPackageListController {
8017 - (id) initWithDatabase:(Database *)database;
8019 - (void) updateRoleButton;
8020 - (void) queueStatusDidChange;
8024 @implementation InstalledController
8030 - (NSURL *) navigationURL {
8031 return [NSURL URLWithString:@"cydia://installed"];
8034 - (id) initWithDatabase:(Database *)database {
8035 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8036 [self updateRoleButton];
8037 [self queueStatusDidChange];
8042 - (void) queueButtonClicked {
8047 - (void) queueStatusDidChange {
8051 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8052 initWithTitle:UCLocalize("QUEUE")
8053 style:UIBarButtonItemStyleDone
8055 action:@selector(queueButtonClicked)
8058 [[self navigationItem] setLeftBarButtonItem:nil];
8064 - (void) updateRoleButton {
8065 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8066 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8067 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8068 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8070 action:@selector(roleButtonClicked)
8074 - (void) roleButtonClicked {
8075 [self setObject:[NSNumber numberWithBool:expert_]];
8079 [self updateRoleButton];
8085 /* Source Cell {{{ */
8086 @interface SourceCell : CYTableViewCell <
8094 - (void) setSource:(Source *)source;
8098 @implementation SourceCell
8100 - (void) clearSource {
8110 - (void) setSource:(Source *)source {
8114 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
8116 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8117 icon_ = [icon_ retain];
8119 origin_ = [[source name] retain];
8120 label_ = [[source uri] retain];
8122 [content_ setNeedsDisplay];
8130 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8131 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8132 UIView *content([self contentView]);
8133 CGRect bounds([content bounds]);
8135 content_ = [[ContentView alloc] initWithFrame:bounds];
8136 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8137 [content_ setBackgroundColor:[UIColor whiteColor]];
8138 [content addSubview:content_];
8140 [content_ setDelegate:self];
8141 [content_ setOpaque:YES];
8145 - (NSString *) accessibilityLabel {
8149 - (void) drawContentRect:(CGRect)rect {
8150 bool highlighted(highlighted_);
8151 float width(rect.size.width);
8154 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8161 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8165 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8170 /* Source Controller {{{ */
8171 @interface SourceController : FilteredPackageListController {
8172 _transient Source *source_;
8176 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8180 @implementation SourceController
8182 - (NSURL *) navigationURL {
8183 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8186 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8187 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8189 key_ = [[source key] retain];
8193 - (void) reloadData {
8194 source_ = [database_ sourceWithKey:key_];
8196 key_ = [[source_ key] retain];
8197 [self setObject:source_];
8199 [[self navigationItem] setTitle:[source_ label]];
8206 /* Sources Controller {{{ */
8207 @interface SourcesController : CYViewController <
8208 UITableViewDataSource,
8211 _transient Database *database_;
8213 NSMutableArray *sources_;
8217 UIProgressHUD *hud_;
8220 //NSURLConnection *installer_;
8221 NSURLConnection *trivial_;
8222 NSURLConnection *trivial_bz2_;
8223 NSURLConnection *trivial_gz_;
8224 //NSURLConnection *automatic_;
8229 - (id) initWithDatabase:(Database *)database;
8230 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8234 @implementation SourcesController
8236 - (void) _releaseConnection:(NSURLConnection *)connection {
8237 if (connection != nil) {
8238 [connection cancel];
8239 //[connection setDelegate:nil];
8240 [connection release];
8245 [self releaseSubviews];
8251 //[self _releaseConnection:installer_];
8252 [self _releaseConnection:trivial_];
8253 [self _releaseConnection:trivial_gz_];
8254 [self _releaseConnection:trivial_bz2_];
8255 //[self _releaseConnection:automatic_];
8261 - (NSURL *) navigationURL {
8262 return [NSURL URLWithString:@"cydia://sources"];
8265 - (void) viewDidAppear:(BOOL)animated {
8266 [super viewDidAppear:animated];
8267 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8270 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8271 return offset_ == 0 ? 1 : 2;
8274 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8275 switch (section + (offset_ == 0 ? 1 : 0)) {
8276 case 0: return UCLocalize("ENTERED_BY_USER");
8277 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8283 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8284 int count = [sources_ count];
8286 case 0: return (offset_ == 0 ? count : offset_);
8287 case 1: return count - offset_;
8293 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8295 switch (indexPath.section) {
8296 case 0: idx = indexPath.row; break;
8297 case 1: idx = indexPath.row + offset_; break;
8301 return [sources_ objectAtIndex:idx];
8304 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8305 static NSString *cellIdentifier = @"SourceCell";
8307 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8308 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8309 [cell setSource:[self sourceAtIndexPath:indexPath]];
8310 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8315 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8316 Source *source = [self sourceAtIndexPath:indexPath];
8318 SourceController *controller = [[[SourceController alloc]
8319 initWithDatabase:database_
8323 [controller setDelegate:delegate_];
8325 [[self navigationController] pushViewController:controller animated:YES];
8328 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8329 Source *source = [self sourceAtIndexPath:indexPath];
8330 return [source record] != nil;
8333 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8334 Source *source = [self sourceAtIndexPath:indexPath];
8335 [Sources_ removeObjectForKey:[source key]];
8336 [delegate_ syncData];
8340 [delegate_ addTrivialSource:href_];
8341 [delegate_ syncData];
8344 - (NSString *) getWarning {
8345 NSString *href(href_);
8346 NSRange colon([href rangeOfString:@"://"]);
8347 if (colon.location != NSNotFound)
8348 href = [href substringFromIndex:(colon.location + 3)];
8349 href = [href stringByAddingPercentEscapes];
8350 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8351 href = [href stringByCachingURLWithCurrentCDN];
8353 NSURL *url([NSURL URLWithString:href]);
8355 NSStringEncoding encoding;
8356 NSError *error(nil);
8358 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8359 return [warning length] == 0 ? nil : warning;
8363 - (void) _endConnection:(NSURLConnection *)connection {
8364 // XXX: the memory management in this method is horribly awkward
8366 NSURLConnection **field = NULL;
8367 if (connection == trivial_)
8369 else if (connection == trivial_bz2_)
8370 field = &trivial_bz2_;
8371 else if (connection == trivial_gz_)
8372 field = &trivial_gz_;
8373 _assert(field != NULL);
8374 [connection release];
8379 trivial_bz2_ == nil &&
8385 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8388 UIAlertView *alert = [[[UIAlertView alloc]
8389 initWithTitle:UCLocalize("SOURCE_WARNING")
8392 cancelButtonTitle:UCLocalize("CANCEL")
8394 UCLocalize("ADD_ANYWAY"),
8398 [alert setContext:@"warning"];
8399 [alert setNumberOfRows:1];
8403 } else if (error_ != nil) {
8404 UIAlertView *alert = [[[UIAlertView alloc]
8405 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8406 message:[error_ localizedDescription]
8408 cancelButtonTitle:UCLocalize("OK")
8409 otherButtonTitles:nil
8412 [alert setContext:@"urlerror"];
8415 UIAlertView *alert = [[[UIAlertView alloc]
8416 initWithTitle:UCLocalize("NOT_REPOSITORY")
8417 message:UCLocalize("NOT_REPOSITORY_EX")
8419 cancelButtonTitle:UCLocalize("OK")
8420 otherButtonTitles:nil
8423 [alert setContext:@"trivial"];
8427 [delegate_ releaseNetworkActivityIndicator];
8429 [delegate_ removeProgressHUD:hud_];
8438 if (error_ != nil) {
8445 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8446 switch ([response statusCode]) {
8452 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8453 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8455 error_ = [error retain];
8456 [self _endConnection:connection];
8459 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8460 [self _endConnection:connection];
8463 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8464 NSMutableURLRequest *request = [NSMutableURLRequest
8465 requestWithURL:[NSURL URLWithString:href]
8466 cachePolicy:NSURLRequestUseProtocolCachePolicy
8467 timeoutInterval:120.0
8470 [request setHTTPMethod:method];
8472 if (Machine_ != NULL)
8473 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8474 if (UniqueID_ != nil)
8475 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8477 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8480 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8481 NSString *context([alert context]);
8483 if ([context isEqualToString:@"source"]) {
8486 NSString *href = [[alert textField] text];
8488 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8490 if (![href hasSuffix:@"/"])
8491 href_ = [href stringByAppendingString:@"/"];
8494 href_ = [href_ retain];
8496 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8497 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8498 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8499 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8503 // XXX: this is stupid
8504 hud_ = [[delegate_ addProgressHUD] retain];
8505 [hud_ setText:UCLocalize("VERIFYING_URL")];
8506 [delegate_ retainNetworkActivityIndicator];
8515 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8516 } else if ([context isEqualToString:@"trivial"])
8517 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8518 else if ([context isEqualToString:@"urlerror"])
8519 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8520 else if ([context isEqualToString:@"warning"]) {
8535 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8540 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8542 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8543 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8544 [list_ setRowHeight:56];
8545 [list_ setDataSource:self];
8546 [list_ setDelegate:self];
8547 [[self view] addSubview:list_];
8550 - (void) viewDidLoad {
8551 [super viewDidLoad];
8553 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8554 [self updateButtonsForEditingStatus:NO animated:NO];
8557 - (void) releaseSubviews {
8562 - (id) initWithDatabase:(Database *)database {
8563 if ((self = [super init]) != nil) {
8564 database_ = database;
8565 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8569 - (void) reloadData {
8573 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8576 [sources_ removeAllObjects];
8577 [sources_ addObjectsFromArray:[database_ sources]];
8579 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8582 int count([sources_ count]);
8584 for (int i = 0; i != count; i++) {
8585 if ([[sources_ objectAtIndex:i] record] == nil)
8590 [list_ setEditing:NO];
8591 [self updateButtonsForEditingStatus:NO animated:NO];
8595 - (void) showAddSourcePrompt {
8596 UIAlertView *alert = [[[UIAlertView alloc]
8597 initWithTitle:UCLocalize("ENTER_APT_URL")
8600 cancelButtonTitle:UCLocalize("CANCEL")
8602 UCLocalize("ADD_SOURCE"),
8606 [alert setContext:@"source"];
8607 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8609 [alert setNumberOfRows:1];
8610 [alert addTextFieldWithValue:@"http://" label:@""];
8612 UITextInputTraits *traits = [[alert textField] textInputTraits];
8613 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8614 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8615 [traits setKeyboardType:UIKeyboardTypeURL];
8616 // XXX: UIReturnKeyDone
8617 [traits setReturnKeyType:UIReturnKeyNext];
8622 - (void) addButtonClicked {
8623 [self showAddSourcePrompt];
8626 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8627 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8628 initWithTitle:UCLocalize("ADD")
8629 style:UIBarButtonItemStylePlain
8631 action:@selector(addButtonClicked)
8632 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8634 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8635 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8636 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8638 action:@selector(editButtonClicked)
8639 ] autorelease] animated:animated];
8641 if (IsWildcat_ && !editing)
8642 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8643 initWithTitle:UCLocalize("SETTINGS")
8644 style:UIBarButtonItemStylePlain
8646 action:@selector(settingsButtonClicked)
8650 - (void) settingsButtonClicked {
8651 [delegate_ showSettings];
8654 - (void) editButtonClicked {
8655 [list_ setEditing:![list_ isEditing] animated:YES];
8657 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8663 /* Settings Controller {{{ */
8664 @interface SettingsController : CYViewController <
8665 UITableViewDataSource,
8668 _transient Database *database_;
8669 // XXX: ok, "roledelegate_"?...
8670 _transient id roledelegate_;
8671 UITableView *table_;
8672 UISegmentedControl *segment_;
8676 - (void) showDoneButton;
8677 - (void) resizeSegmentedControl;
8681 @implementation SettingsController
8684 [self releaseSubviews];
8690 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8692 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8693 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8694 [table_ setDelegate:self];
8695 [table_ setDataSource:self];
8696 [[self view] addSubview:table_];
8698 NSArray *items = [NSArray arrayWithObjects:
8700 UCLocalize("HACKER"),
8701 UCLocalize("DEVELOPER"),
8703 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8704 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8705 [container_ addSubview:segment_];
8708 - (void) viewDidLoad {
8709 [super viewDidLoad];
8711 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8714 if ([Role_ isEqualToString:@"User"]) index = 0;
8715 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8716 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8718 [segment_ setSelectedSegmentIndex:index];
8719 [self showDoneButton];
8722 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8723 [self resizeSegmentedControl];
8726 - (void) releaseSubviews {
8733 [container_ release];
8737 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8738 if ((self = [super init]) != nil) {
8739 database_ = database;
8740 roledelegate_ = delegate;
8744 - (void) resizeSegmentedControl {
8745 CGFloat width = [[self view] frame].size.width;
8746 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8749 - (void) viewWillAppear:(BOOL)animated {
8750 [super viewWillAppear:animated];
8752 [self resizeSegmentedControl];
8755 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8756 [self resizeSegmentedControl];
8759 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8760 [self resizeSegmentedControl];
8764 NSString *role(nil);
8766 switch ([segment_ selectedSegmentIndex]) {
8767 case 0: role = @"User"; break;
8768 case 1: role = @"Hacker"; break;
8769 case 2: role = @"Developer"; break;
8774 if (![role isEqualToString:Role_]) {
8775 bool rolling(Role_ == nil);
8778 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8782 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8786 [roledelegate_ loadData];
8788 [roledelegate_ updateData];
8792 - (void) segmentChanged:(UISegmentedControl *)control {
8793 [self showDoneButton];
8796 - (void) saveAndClose {
8799 [[self navigationItem] setRightBarButtonItem:nil];
8800 [[self navigationController] dismissModalViewControllerAnimated:YES];
8803 - (void) doneButtonClicked {
8804 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8805 [spinner startAnimating];
8806 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8807 [[self navigationItem] setRightBarButtonItem:spinItem];
8809 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8812 - (void) showDoneButton {
8813 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8814 initWithTitle:UCLocalize("DONE")
8815 style:UIBarButtonItemStyleDone
8817 action:@selector(doneButtonClicked)
8818 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8821 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8822 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8826 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8830 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8831 return nil; // This method is required by the protocol.
8834 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8836 return UCLocalize("ROLE_EX");
8838 return [NSString stringWithFormat:
8839 @"%@: %@\n%@: %@\n%@: %@",
8840 UCLocalize("USER"), UCLocalize("USER_EX"),
8841 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8842 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8847 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8848 return section == 3 ? 44.0f : 0;
8851 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8852 return section == 3 ? container_ : nil;
8855 - (void) reloadData {
8858 [table_ reloadData];
8863 /* Stash Controller {{{ */
8864 @interface StashController : CYViewController {
8865 UIActivityIndicatorView *spinner_;
8872 @implementation StashController
8875 [self releaseSubviews];
8881 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8882 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8884 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8885 CGRect spinrect = [spinner_ frame];
8886 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8887 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8888 [spinner_ setFrame:spinrect];
8889 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8890 [[self view] addSubview:spinner_];
8891 [spinner_ startAnimating];
8894 captrect.size.width = [[self view] frame].size.width;
8895 captrect.size.height = 40.0f;
8896 captrect.origin.x = 0;
8897 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8898 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8899 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8900 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8901 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8902 [caption_ setTextColor:[UIColor whiteColor]];
8903 [caption_ setBackgroundColor:[UIColor clearColor]];
8904 [caption_ setShadowColor:[UIColor blackColor]];
8905 [caption_ setTextAlignment:UITextAlignmentCenter];
8906 [[self view] addSubview:caption_];
8909 statusrect.size.width = [[self view] frame].size.width;
8910 statusrect.size.height = 30.0f;
8911 statusrect.origin.x = 0;
8912 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8913 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8914 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8915 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8916 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8917 [status_ setTextColor:[UIColor whiteColor]];
8918 [status_ setBackgroundColor:[UIColor clearColor]];
8919 [status_ setShadowColor:[UIColor blackColor]];
8920 [status_ setTextAlignment:UITextAlignmentCenter];
8921 [[self view] addSubview:status_];
8924 - (void) releaseSubviews {
8938 @interface Cydia : UIApplication <
8939 ConfirmationControllerDelegate,
8942 UINavigationControllerDelegate,
8943 UITabBarControllerDelegate
8945 // XXX: evaluate all fields for _transient
8948 CYTabBarController *tabbar_;
8949 CYEmulatedLoadingController *emulated_;
8951 NSMutableArray *essential_;
8952 NSMutableArray *broken_;
8954 Database *database_;
8961 StashController *stash_;
8970 @implementation Cydia
8972 - (void) beginUpdate {
8973 [tabbar_ beginUpdate];
8977 return [tabbar_ updating];
8981 if ([broken_ count] != 0) {
8982 int count = [broken_ count];
8984 UIAlertView *alert = [[[UIAlertView alloc]
8985 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8986 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8988 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8990 UCLocalize("TEMPORARY_IGNORE"),
8994 [alert setContext:@"fixhalf"];
8995 [alert setNumberOfRows:2];
8997 } else if (!Ignored_ && [essential_ count] != 0) {
8998 int count = [essential_ count];
9000 UIAlertView *alert = [[[UIAlertView alloc]
9001 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9002 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9004 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9006 UCLocalize("UPGRADE_ESSENTIAL"),
9007 UCLocalize("COMPLETE_UPGRADE"),
9011 [alert setContext:@"upgrade"];
9016 - (void) _saveConfig {
9022 NSString *error(nil);
9024 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9026 NSError *error(nil);
9027 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9028 NSLog(@"failure to save metadata data: %@", error);
9033 NSLog(@"failure to serialize metadata: %@", error);
9038 // Navigation controller for the queuing badge.
9039 - (UINavigationController *) queueNavigationController {
9040 NSArray *controllers = [tabbar_ viewControllers];
9041 return [controllers objectAtIndex:3];
9044 - (void) unloadData {
9045 [tabbar_ unloadData];
9048 - (void) _updateData {
9053 UINavigationController *navigation = [self queueNavigationController];
9055 id queuedelegate = nil;
9056 if ([[navigation viewControllers] count] > 0)
9057 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9059 [queuedelegate queueStatusDidChange];
9060 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9063 - (void) _refreshIfPossible:(NSDate *)update {
9064 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9066 bool recently = false;
9067 if (update != nil) {
9068 NSTimeInterval interval([update timeIntervalSinceNow]);
9069 if (interval <= 0 && interval > -(15*60))
9073 // Don't automatic refresh if:
9074 // - We already refreshed recently.
9075 // - We already auto-refreshed this launch.
9076 // - Auto-refresh is disabled.
9077 if (recently || loaded_ || ManualRefresh) {
9078 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9080 // If we are cancelling, we need to make sure it knows it's already loaded.
9084 // We are going to load, so remember that.
9088 SCNetworkReachabilityFlags flags; {
9089 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9090 SCNetworkReachabilityGetFlags(reachability, &flags);
9091 CFRelease(reachability);
9094 // XXX: this elaborate mess is what Apple is using to determine this? :(
9095 // XXX: do we care if the user has to intervene? maybe that's ok?
9097 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9098 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9099 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9100 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9101 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9102 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9106 // If we can reach the server, auto-refresh!
9108 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9113 - (void) refreshIfPossible {
9114 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9117 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
9118 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9119 [hud setText:UCLocalize("RELOADING_DATA")];
9121 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9124 [self removeProgressHUD:hud];
9128 [essential_ removeAllObjects];
9129 [broken_ removeAllObjects];
9131 NSArray *packages([database_ packages]);
9132 for (Package *package in packages) {
9134 [broken_ addObject:package];
9135 if ([package upgradableAndEssential:NO]) {
9136 if ([package essential])
9137 [essential_ addObject:package];
9142 NSLog(@"changes:#%u", changes);
9144 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9147 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9148 [changesItem setBadgeValue:badge];
9149 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9150 [self setApplicationIconBadgeNumber:changes];
9153 [changesItem setBadgeValue:nil];
9154 [changesItem setAnimatedBadge:NO];
9155 [self setApplicationIconBadgeNumber:0];
9160 [self refreshIfPossible];
9163 - (void) updateData {
9172 @synchronized (self) {
9173 [self _reloadDataWithInvocation:nil];
9177 - (void) disemulate {
9178 if (emulated_ == nil)
9181 [window_ addSubview:[tabbar_ view]];
9182 [[emulated_ view] removeFromSuperview];
9183 [emulated_ release];
9185 [window_ setUserInteractionEnabled:YES];
9188 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9189 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9191 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9193 UIViewController *parent;
9194 if (emulated_ == nil)
9203 [parent presentModalViewController:navigation animated:YES];
9206 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9207 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9209 if (navigation != nil)
9210 [navigation pushViewController:progress animated:YES];
9212 [self presentModalViewController:progress force:YES];
9214 [progress invoke:invocation withTitle:title];
9218 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9219 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9222 - (void) repairWithInvocation:(NSInvocation *)invocation {
9224 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9228 - (void) repairWithSelector:(SEL)selector {
9229 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9235 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9236 _assert(file != NULL);
9238 for (NSString *key in [Sources_ allKeys]) {
9239 NSDictionary *source([Sources_ objectForKey:key]);
9241 fprintf(file, "%s %s %s\n",
9242 [[source objectForKey:@"Type"] UTF8String],
9243 [[source objectForKey:@"URI"] UTF8String],
9244 [[source objectForKey:@"Distribution"] UTF8String]
9250 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9255 - (void) addTrivialSource:(NSString *)href {
9256 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9259 @"./", @"Distribution",
9260 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9265 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9266 @synchronized (self) {
9267 [self _reloadDataWithInvocation:invocation];
9271 - (void) reloadData {
9272 [self reloadDataWithInvocation:nil];
9276 pkgProblemResolver *resolver = [database_ resolver];
9278 resolver->InstallProtect();
9279 if (!resolver->Resolve(true))
9284 // XXX: this is a really crappy way of doing this.
9285 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9286 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9287 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9288 if ([tabbar_ updating])
9289 [tabbar_ cancelUpdate];
9291 if (![database_ prepare])
9294 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9295 [page setDelegate:self];
9296 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9299 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9300 [tabbar_ presentModalViewController:confirm_ animated:YES];
9306 @synchronized (self) {
9311 - (void) clearPackage:(Package *)package {
9312 @synchronized (self) {
9319 - (void) installPackages:(NSArray *)packages {
9320 @synchronized (self) {
9321 for (Package *package in packages)
9328 - (void) installPackage:(Package *)package {
9329 @synchronized (self) {
9336 - (void) removePackage:(Package *)package {
9337 @synchronized (self) {
9344 - (void) distUpgrade {
9345 @synchronized (self) {
9346 if (![database_ upgrade])
9352 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9355 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
9360 - (void) showSettings {
9361 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9364 - (void) retainNetworkActivityIndicator {
9365 if (activity_++ == 0)
9366 [self setNetworkActivityIndicatorVisible:YES];
9369 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9373 - (void) releaseNetworkActivityIndicator {
9374 if (--activity_ == 0)
9375 [self setNetworkActivityIndicatorVisible:NO];
9378 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9383 - (void) cancelAndClear:(bool)clear {
9384 @synchronized (self) {
9396 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9397 NSString *context([alert context]);
9399 if ([context isEqualToString:@"conffile"]) {
9400 FILE *input = [database_ input];
9401 if (button == [alert cancelButtonIndex])
9402 fprintf(input, "N\n");
9403 else if (button == [alert firstOtherButtonIndex])
9404 fprintf(input, "Y\n");
9407 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9408 } else if ([context isEqualToString:@"fixhalf"]) {
9409 if (button == [alert cancelButtonIndex]) {
9410 @synchronized (self) {
9411 for (Package *broken in broken_) {
9414 NSString *id = [broken id];
9415 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9416 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9417 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9418 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9424 } else if (button == [alert firstOtherButtonIndex]) {
9425 [broken_ removeAllObjects];
9429 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9430 } else if ([context isEqualToString:@"upgrade"]) {
9431 if (button == [alert firstOtherButtonIndex]) {
9432 @synchronized (self) {
9433 for (Package *essential in essential_)
9434 [essential install];
9439 } else if (button == [alert firstOtherButtonIndex] + 1) {
9441 } else if (button == [alert cancelButtonIndex]) {
9445 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9449 - (void) system:(NSString *)command { _pooled
9451 system([command UTF8String]);
9455 - (void) applicationWillSuspend {
9457 [super applicationWillSuspend];
9460 - (BOOL) isSafeToSuspend {
9463 NSLog(@"isSafeToSuspend: locked_ != 0");
9468 // Use external process status API internally.
9469 // This is probably a really bad idea.
9470 // XXX: what is the point of this? does this solve anything at all?
9471 uint64_t status = 0;
9473 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9474 notify_get_state(notify_token, &status);
9475 notify_cancel(notify_token);
9480 NSLog(@"isSafeToSuspend: status != 0");
9486 NSLog(@"isSafeToSuspend: -> true");
9491 - (void) applicationSuspend:(__GSEvent *)event {
9492 if ([self isSafeToSuspend])
9493 [super applicationSuspend:event];
9496 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9497 if ([self isSafeToSuspend])
9498 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9501 - (void) _setSuspended:(BOOL)value {
9502 if ([self isSafeToSuspend])
9503 [super _setSuspended:value];
9506 - (UIProgressHUD *) addProgressHUD {
9507 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9508 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9510 [window_ setUserInteractionEnabled:NO];
9512 UIViewController *target(tabbar_);
9513 if (UIViewController *modal = [target modalViewController])
9516 UIView *view([target view]);
9517 [view addSubview:hud];
9525 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9528 [hud removeFromSuperview];
9529 [window_ setUserInteractionEnabled:YES];
9532 - (CYViewController *) pageForPackage:(NSString *)name {
9533 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9536 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9537 NSString *scheme([[url scheme] lowercaseString]);
9538 if ([[url absoluteString] length] <= [scheme length] + 3)
9540 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9541 NSArray *components([path pathComponents]);
9543 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9544 return [self pageForPackage:[components objectAtIndex:1]];
9546 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9549 NSString *base([components objectAtIndex:0]);
9551 CYViewController *controller = nil;
9553 if ([base isEqualToString:@"url"]) {
9554 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9555 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9556 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9557 } else if (!external && [components count] == 1) {
9558 if ([base isEqualToString:@"manage"]) {
9559 controller = [[[ManageController alloc] init] autorelease];
9562 if ([base isEqualToString:@"sources"]) {
9563 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9566 if ([base isEqualToString:@"home"]) {
9567 controller = [[[HomeController alloc] init] autorelease];
9570 if ([base isEqualToString:@"sections"]) {
9571 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9574 if ([base isEqualToString:@"search"]) {
9575 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9578 if ([base isEqualToString:@"changes"]) {
9579 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9582 if ([base isEqualToString:@"installed"]) {
9583 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9585 } else if ([components count] == 2) {
9586 NSString *argument = [components objectAtIndex:1];
9588 if ([base isEqualToString:@"package"]) {
9589 controller = [self pageForPackage:argument];
9592 if (!external && [base isEqualToString:@"search"]) {
9593 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9594 [(SearchController *)controller setSearchTerm:argument];
9597 if (!external && [base isEqualToString:@"sections"]) {
9598 if ([argument isEqualToString:@"all"])
9600 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9603 if (!external && [base isEqualToString:@"sources"]) {
9604 if ([argument isEqualToString:@"add"]) {
9605 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9606 [(SourcesController *)controller showAddSourcePrompt];
9608 Source *source = [database_ sourceWithKey:argument];
9609 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9613 if (!external && [base isEqualToString:@"launch"]) {
9614 [self launchApplicationWithIdentifier:argument suspended:NO];
9617 } else if (!external && [components count] == 3) {
9618 NSString *arg1 = [components objectAtIndex:1];
9619 NSString *arg2 = [components objectAtIndex:2];
9621 if ([base isEqualToString:@"package"]) {
9622 if ([arg2 isEqualToString:@"settings"]) {
9623 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9624 } else if ([arg2 isEqualToString:@"files"]) {
9625 if (Package *package = [database_ packageWithName:arg1]) {
9626 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9627 [(FileTable *)controller setPackage:package];
9633 [controller setDelegate:self];
9637 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9638 CYViewController *page([self pageForURL:url forExternal:external]);
9641 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9642 [nav setViewControllers:[NSArray arrayWithObject:page]];
9643 [tabbar_ setUnselectedViewController:nav];
9649 - (void) applicationOpenURL:(NSURL *)url {
9650 [super applicationOpenURL:url];
9652 if (!loaded_) starturl_ = [url retain];
9653 else [self openCydiaURL:url forExternal:YES];
9656 - (void) applicationWillResignActive:(UIApplication *)application {
9657 // Stop refreshing if you get a phone call or lock the device.
9658 if ([tabbar_ updating])
9659 [tabbar_ cancelUpdate];
9661 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9662 [super applicationWillResignActive:application];
9665 - (void) applicationWillTerminate:(UIApplication *)application {
9667 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9668 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9669 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9674 - (void) setConfigurationData:(NSString *)data {
9675 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9677 if (!conffile_r(data)) {
9678 lprintf("E:invalid conffile\n");
9682 NSString *ofile = conffile_r[1];
9683 //NSString *nfile = conffile_r[2];
9685 UIAlertView *alert = [[[UIAlertView alloc]
9686 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9687 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9689 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9691 UCLocalize("ACCEPT_NEW_COPY"),
9692 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9696 [alert setContext:@"conffile"];
9697 [alert setNumberOfRows:2];
9701 - (void) addStashController {
9703 stash_ = [[StashController alloc] init];
9704 [window_ addSubview:[stash_ view]];
9707 - (void) removeStashController {
9708 [[stash_ view] removeFromSuperview];
9714 [self setIdleTimerDisabled:YES];
9716 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9717 UpdateExternalStatus(1);
9718 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9719 UpdateExternalStatus(0);
9721 [self removeStashController];
9723 if (ExecFork() == 0) {
9724 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9725 perror("launchctl stop");
9729 - (void) setupViewControllers {
9730 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9732 NSMutableArray *items([NSMutableArray arrayWithObjects:
9733 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9734 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9735 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9736 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9740 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9741 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9743 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9746 NSMutableArray *controllers([NSMutableArray array]);
9747 for (UITabBarItem *item in items) {
9748 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9749 [controller setTabBarItem:item];
9750 [controllers addObject:controller];
9752 [tabbar_ setViewControllers:controllers];
9754 [tabbar_ setUpdateDelegate:self];
9757 - (void) applicationDidFinishLaunching:(id)unused {
9759 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9760 [self setApplicationSupportsShakeToEdit:NO];
9762 @synchronized (HostConfig_) {
9763 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9766 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9767 initWithMemoryCapacity:524288
9768 diskCapacity:10485760
9769 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9772 [CydiaWebViewController _initialize];
9774 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9776 Font12_ = [[UIFont systemFontOfSize:12] retain];
9777 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9778 Font14_ = [[UIFont systemFontOfSize:14] retain];
9779 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9780 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9782 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9783 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9785 // XXX: I really need this thing... like, seriously... I'm sorry
9786 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9788 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9789 [window_ orderFront:self];
9790 [window_ makeKey:self];
9791 [window_ setHidden:NO];
9794 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9795 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9796 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9797 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9798 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9799 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9800 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9801 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9802 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9805 [self addStashController];
9806 // XXX: this would be much cleaner as a yieldToSelector:
9807 // that way the removeStashController could happen right here inline
9808 // we also could no longer require the useless stash_ field anymore
9809 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9813 database_ = [Database sharedInstance];
9814 [database_ setDelegate:self];
9816 [window_ setUserInteractionEnabled:NO];
9817 [self setupViewControllers];
9819 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9820 [window_ addSubview:[emulated_ view]];
9822 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9826 - (NSArray *) defaultStartPages {
9827 NSMutableArray *standard = [NSMutableArray array];
9828 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9829 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9830 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9832 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9834 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9835 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9837 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9844 [window_ setUserInteractionEnabled:YES];
9845 [self showSettings];
9848 if ([emulated_ modalViewController] != nil)
9849 [emulated_ dismissModalViewControllerAnimated:YES];
9850 [window_ setUserInteractionEnabled:NO];
9858 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9859 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9860 int standardIndex = 0;
9861 NSArray *standard = [self defaultStartPages];
9868 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9869 if (valid && closed != nil) {
9870 NSTimeInterval interval([closed timeIntervalSinceNow]);
9871 // XXX: Is 15 minutes the optimal time here?
9872 if (interval > 0 && interval <= -(15*60))
9876 if (valid && [saved count] != [standard count])
9880 for (unsigned int i = 0; i < [standard count]; i++) {
9881 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9882 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9883 // but it's good enough for now.
9884 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9891 NSArray *items = nil;
9893 [tabbar_ setSelectedIndex:savedIndex];
9896 [tabbar_ setSelectedIndex:standardIndex];
9900 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9901 NSArray *stack = [items objectAtIndex:tab];
9902 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9903 NSMutableArray *current = [NSMutableArray array];
9905 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9906 NSString *addr = [stack objectAtIndex:nav];
9907 NSURL *url = [NSURL URLWithString:addr];
9908 CYViewController *page = [self pageForURL:url forExternal:NO];
9910 [current addObject:page];
9913 [navigation setViewControllers:current];
9916 // (Try to) show the startup URL.
9917 if (starturl_ != nil) {
9918 [self openCydiaURL:starturl_ forExternal:NO];
9919 [starturl_ release];
9924 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9925 if (item != nil && IsWildcat_) {
9926 [sheet showFromBarButtonItem:item animated:YES];
9928 [sheet showInView:window_];
9932 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9933 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9934 [progress setTitle:task];
9935 [progress addProgressEvent:event];
9938 - (void) addProgressEventForTask:(NSArray *)data {
9939 CydiaProgressEvent *event([data objectAtIndex:0]);
9940 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9941 [self addProgressEvent:event forTask:task];
9944 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9945 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9951 id Alloc_(id self, SEL selector) {
9952 id object = alloc_(self, selector);
9953 lprintf("[%s]A-%p\n", self->isa->name, object);
9958 id Dealloc_(id self, SEL selector) {
9959 id object = dealloc_(self, selector);
9960 lprintf("[%s]D-%p\n", self->isa->name, object);
9964 Class $WebDefaultUIKitDelegate;
9966 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9967 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9968 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9969 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9972 static NSSet *MobilizedFiles_;
9974 static NSURL *MobilizeURL(NSURL *url) {
9975 NSString *path([url path]);
9976 if ([path hasPrefix:@"/var/root/"]) {
9977 NSString *file([path substringFromIndex:10]);
9978 if ([MobilizedFiles_ containsObject:file])
9979 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9985 Class $CFXPreferencesPropertyListSource;
9986 @class CFXPreferencesPropertyListSource;
9988 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9989 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9990 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9991 url = MobilizeURL(url);
9992 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9993 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9999 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10000 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10001 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10002 url = MobilizeURL(url);
10003 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10004 //NSLog(@"%@ %@", [url absoluteString], value);
10010 Class $NSURLConnection;
10012 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10013 NSMutableURLRequest *copy([request mutableCopy]);
10015 NSURL *url([copy URL]);
10016 NSString *host([url host]);
10017 NSString *scheme([[url scheme] lowercaseString]);
10019 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10021 @synchronized (HostConfig_) {
10022 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10023 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10024 [copy setHTTPShouldUsePipelining:YES];
10027 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10031 int main(int argc, char *argv[]) { _pooled
10034 UpdateExternalStatus(0);
10036 if (Class $UIDevice = objc_getClass("UIDevice")) {
10037 UIDevice *device([$UIDevice currentDevice]);
10038 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10040 IsWildcat_ = false;
10042 UIScreen *screen([UIScreen mainScreen]);
10043 if ([screen respondsToSelector:@selector(scale)])
10044 ScreenScale_ = [screen scale];
10048 UIDevice *device([UIDevice currentDevice]);
10049 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10050 Idiom_ = @"iphone";
10052 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10053 if (idiom == UIUserInterfaceIdiomPhone)
10054 Idiom_ = @"iphone";
10055 else if (idiom == UIUserInterfaceIdiomPad)
10058 NSLog(@"unknown UIUserInterfaceIdiom!");
10061 SessionData_ = [[NSMutableDictionary alloc] initWithCapacity:4];
10063 HostConfig_ = [[NSObject alloc] init];
10064 @synchronized (HostConfig_) {
10065 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10066 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10069 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
10071 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10073 MobilizedFiles_ = [NSMutableSet setWithObjects:
10074 @"Library/Preferences/com.apple.Accessibility.plist",
10075 @"Library/Preferences/com.apple.preferences.sounds.plist",
10078 /* Library Hacks {{{ */
10079 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10081 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10083 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10084 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10085 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10086 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10089 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10090 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10091 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10092 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10095 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10096 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10097 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10098 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10099 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10102 $NSURLConnection = objc_getClass("NSURLConnection");
10103 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10104 if (NSURLConnection$init$ != NULL) {
10105 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10106 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10109 /* Set Locale {{{ */
10110 Locale_ = CFLocaleCopyCurrent();
10111 Languages_ = [NSLocale preferredLanguages];
10113 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10114 //NSLog(@"%@", [Languages_ description]);
10117 if (Locale_ != NULL)
10118 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10119 else if (Languages_ != nil && [Languages_ count] != 0)
10120 lang = [[Languages_ objectAtIndex:0] UTF8String];
10122 // XXX: consider just setting to C and then falling through?
10125 if (lang != NULL) {
10126 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10127 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10130 NSLog(@"Setting Language: %s", lang);
10132 if (lang != NULL) {
10133 setenv("LANG", lang, true);
10134 std::setlocale(LC_ALL, lang);
10138 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10140 /* Parse Arguments {{{ */
10141 bool substrate(false);
10147 for (int argi(1); argi != argc; ++argi)
10148 if (strcmp(argv[argi], "--") == 0) {
10150 argv[argi] = argv[0];
10156 for (int argi(1); argi != arge; ++argi)
10157 if (strcmp(args[argi], "--substrate") == 0)
10160 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10164 App_ = [[NSBundle mainBundle] bundlePath];
10170 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10171 alloc_ = alloc->method_imp;
10172 alloc->method_imp = (IMP) &Alloc_;*/
10174 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10175 dealloc_ = dealloc->method_imp;
10176 dealloc->method_imp = (IMP) &Dealloc_;*/
10178 /* System Information {{{ */
10182 size = sizeof(maxproc);
10183 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10184 perror("sysctlbyname(\"kern.maxproc\", ?)");
10185 else if (maxproc < 64) {
10187 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10188 perror("sysctlbyname(\"kern.maxproc\", #)");
10191 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10192 char *osversion = new char[size];
10193 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10194 perror("sysctlbyname(\"kern.osversion\", ?)");
10196 System_ = [NSString stringWithUTF8String:osversion];
10198 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10199 char *machine = new char[size];
10200 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10201 perror("sysctlbyname(\"hw.machine\", ?)");
10203 Machine_ = machine;
10205 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
10206 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
10207 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
10208 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
10212 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
10213 NSData *data((NSData *) ecid);
10214 size_t length([data length]);
10215 uint8_t bytes[length];
10216 [data getBytes:bytes];
10217 char string[length * 2 + 1];
10218 for (size_t i(0); i != length; ++i)
10219 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10220 ChipID_ = [NSString stringWithUTF8String:string];
10224 IOObjectRelease(service);
10228 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10230 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10231 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10232 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10234 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10235 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10236 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10238 if (mcc != NULL && mnc != NULL)
10239 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10246 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10247 Build_ = [system objectForKey:@"ProductBuildVersion"];
10248 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10249 Product_ = [info objectForKey:@"SafariProductVersion"];
10250 Safari_ = [info objectForKey:@"CFBundleVersion"];
10253 /* Load Database {{{ */
10255 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10257 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10259 if (Metadata_ == NULL)
10260 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10262 Settings_ = [Metadata_ objectForKey:@"Settings"];
10264 Packages_ = [Metadata_ objectForKey:@"Packages"];
10265 Sections_ = [Metadata_ objectForKey:@"Sections"];
10266 Sources_ = [Metadata_ objectForKey:@"Sources"];
10268 Token_ = [Metadata_ objectForKey:@"Token"];
10271 if (Settings_ != nil)
10272 Role_ = [Settings_ objectForKey:@"Role"];
10274 if (Sections_ == nil) {
10275 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10276 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10279 if (Sources_ == nil) {
10280 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10281 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10286 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10289 if (Packages_ != nil) {
10291 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10295 [Metadata_ removeObjectForKey:@"Packages"];
10301 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10303 #define MobileSubstrate_(name) \
10304 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10305 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10306 if (handle == NULL) \
10307 NSLog(@"%s", dlerror()); \
10310 MobileSubstrate_(Activator)
10311 MobileSubstrate_(libstatusbar)
10312 MobileSubstrate_(SimulatedKeyEvents)
10313 MobileSubstrate_(WinterBoard)
10315 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10316 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10318 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10320 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10321 unlink("/tmp/.cydia.fw");
10323 } else if (access("/User", F_OK) != 0 || version < 4) {
10326 system("/usr/libexec/cydia/firmware.sh");
10330 _assert([[NSFileManager defaultManager]
10331 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10332 withIntermediateDirectories:YES
10337 if (access("/tmp/cydia.chk", F_OK) == 0) {
10338 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10339 _assert(errno == ENOENT);
10340 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10341 _assert(errno == ENOENT);
10344 /* APT Initialization {{{ */
10345 _assert(pkgInitConfig(*_config));
10346 _assert(pkgInitSystem(*_config, _system));
10349 _config->Set("APT::Acquire::Translation", lang);
10351 // XXX: this timeout might be important :(
10352 //_config->Set("Acquire::http::Timeout", 15);
10354 _config->Set("Acquire::http::MaxParallel", 3);
10356 /* Color Choices {{{ */
10357 space_ = CGColorSpaceCreateDeviceRGB();
10359 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10360 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10361 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10362 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10363 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10364 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10365 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10366 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10367 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10369 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10370 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10372 /* UIKit Configuration {{{ */
10373 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10374 if ($GSFontSetUseLegacyFontMetrics != NULL)
10375 $GSFontSetUseLegacyFontMetrics(YES);
10377 // XXX: I have a feeling this was important
10378 //UIKeyboardDisableAutomaticAppearance();
10381 Colon_ = UCLocalize("COLON_DELIMITED");
10382 Elision_ = UCLocalize("ELISION");
10383 Error_ = UCLocalize("ERROR");
10384 Warning_ = UCLocalize("WARNING");
10387 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10389 CGColorSpaceRelease(space_);
10390 CFRelease(Locale_);