1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
121 #include <Cytore.hpp>
123 #include "UICaboodle/BrowserView.h"
124 #include "UICaboodle/NSString-UICaboodle.h"
125 #include "UICaboodle/PerlCompatibleRegEx.hpp"
127 #include "SDURLCache/SDURLCache.h"
129 #include "substrate.h"
136 #define _timestamp ({ \
138 gettimeofday(&tv, NULL); \
139 tv.tv_sec * 1000000 + tv.tv_usec; \
142 typedef std::vector<class ProfileTime *> TimeList;
152 ProfileTime(const char *name) :
156 times_.push_back(this);
159 void AddTime(uint64_t time) {
166 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
178 ProfileTimer(ProfileTime &time) :
185 time_.AddTime(_timestamp - start_);
190 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
192 std::cerr << "========" << std::endl;
195 #define _profile(name) { \
196 static ProfileTime name(#name); \
197 ProfileTimer _ ## name(name);
202 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
204 #define CYPoolStart() \
205 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
207 #define CYPoolEnd() \
211 #define Cydia_ CYDIA_VERSION
213 #define lprintf(args...) fprintf(stderr, args)
216 #define TraceLogging (1 && !ForRelease)
217 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
218 #define ProfileTimes (0 && !ForRelease)
219 #define ForSaurik (0 && !ForRelease)
220 #define LogBrowser (0 && !ForRelease)
221 #define TrackResize (0 && !ForRelease)
222 #define ManualRefresh (1 && !ForRelease)
223 #define ShowInternals (0 && !ForRelease)
224 #define AlwaysReload (0 && !ForRelease)
225 #define TryIndexedCollation (0 && !ForRelease)
229 #define _trace(args...)
234 #define _profile(name) {
237 #define PrintTimes() do {} while (false)
240 // Hash Functions/Structures {{{
241 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
249 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
251 static _finline NSString *CydiaURL(NSString *path) {
253 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
254 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
255 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
256 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
257 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
259 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
262 static _finline void UpdateExternalStatus(uint64_t newStatus) {
264 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
265 notify_set_state(notify_token, newStatus);
266 notify_cancel(notify_token);
268 notify_post("com.saurik.Cydia.status");
271 /* [NSObject yieldToSelector:(withObject:)] {{{*/
272 @interface NSObject (Cydia)
273 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
274 - (id) yieldToSelector:(SEL)selector;
277 @implementation NSObject (Cydia)
282 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
283 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
284 id object([[context objectAtIndex:1] nonretainedObjectValue]);
285 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
287 /* XXX: deal with exceptions */
288 id value([self performSelector:selector withObject:object]);
290 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
291 [context removeAllObjects];
292 if ([signature methodReturnLength] != 0 && value != nil)
293 [context addObject:value];
298 performSelectorOnMainThread:@selector(doNothing)
304 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
305 volatile bool stopped(false);
307 NSMutableArray *context([NSMutableArray arrayWithObjects:
308 [NSValue valueWithPointer:selector],
309 [NSValue valueWithNonretainedObject:object],
310 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
313 NSThread *thread([[[NSThread alloc]
315 selector:@selector(_yieldToContext:)
321 NSRunLoop *loop([NSRunLoop currentRunLoop]);
322 NSDate *future([NSDate distantFuture]);
323 NSString *mode([loop currentMode] ?: NSDefaultRunLoopMode);
326 while (!stopped && [loop runMode:mode beforeDate:future]);
329 return [context count] == 0 ? nil : [context objectAtIndex:0];
332 - (id) yieldToSelector:(SEL)selector {
333 return [self yieldToSelector:selector withObject:nil];
339 /* Cydia Alert View {{{ */
340 @interface CYAlertView : UIAlertView {
344 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
348 @implementation CYAlertView
350 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
351 if ((self = [super init]) != nil) {
352 [self setTitle:title];
353 [self setDelegate:self];
354 for (NSString *button in buttons) [self addButtonWithTitle:button];
355 [self setCancelButtonIndex:index];
359 - (void) _updateFrameForDisplay {
360 [super _updateFrameForDisplay];
361 if ([self cancelButtonIndex] == -1) {
362 NSArray *buttons = [self buttons];
363 if ([buttons count]) {
364 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
365 for (UIThreePartButton *button in buttons)
366 [button setBackground:background forState:0];
371 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
372 button_ = buttonIndex + 1;
376 [self dismissWithClickedButtonIndex:-1 animated:YES];
379 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
380 [self setRunsModal:YES];
389 /* NSForcedOrderingSearch doesn't work on the iPhone */
390 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
391 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
392 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
395 typedef uint32_t (*SKRadixFunction)(id, void *);
397 @interface NSMutableArray (Radix)
398 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
406 @implementation NSMutableArray (Radix)
408 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
409 size_t count([self count]);
410 struct RadixItem_ *swap(new RadixItem_[count * 2]);
412 for (size_t i(0); i != count; ++i) {
413 RadixItem_ &item(swap[i]);
416 id object([self objectAtIndex:i]);
417 item.key = function(object, argument);
420 struct RadixItem_ *lhs(swap), *rhs(swap + count);
422 static const size_t width = 32;
423 static const size_t bits = 11;
424 static const size_t slots = 1 << bits;
425 static const size_t passes = (width + (bits - 1)) / bits;
427 size_t *hist(new size_t[slots]);
429 for (size_t pass(0); pass != passes; ++pass) {
430 memset(hist, 0, sizeof(size_t) * slots);
432 for (size_t i(0); i != count; ++i) {
433 uint32_t key(lhs[i].key);
435 key &= _not(uint32_t) >> width - bits;
440 for (size_t i(0); i != slots; ++i) {
441 size_t local(offset);
446 for (size_t i(0); i != count; ++i) {
447 uint32_t key(lhs[i].key);
449 key &= _not(uint32_t) >> width - bits;
450 rhs[hist[key]++] = lhs[i];
453 RadixItem_ *tmp(lhs);
460 const void **values(new const void *[count]);
461 for (size_t i(0); i != count; ++i)
462 values[i] = [self objectAtIndex:lhs[i].index];
463 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
471 /* Insertion Sort {{{ */
473 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
474 const char *ptr = (const char *)list;
476 CFIndex half = count / 2;
477 const char *probe = ptr + elementSize * half;
478 CFComparisonResult cr = comparator(element, probe, context);
479 if (0 == cr) return (probe - (const char *)list) / elementSize;
480 ptr = (cr < 0) ? ptr : probe + elementSize;
481 count = (cr < 0) ? half : (half + (count & 1) - 1);
483 return (ptr - (const char *)list) / elementSize;
486 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
487 const char *ptr = (const char *)list;
489 CFIndex half = count / 2;
490 const char *probe = ptr + elementSize * half;
491 CFComparisonResult cr = comparator(element, probe, context);
492 if (0 == cr) return (probe - (const char *)list) / elementSize;
493 ptr = (cr < 0) ? ptr : probe + elementSize;
494 count = (cr < 0) ? half : (half + (count & 1) - 1);
496 return (ptr - (const char *)list) / elementSize;
499 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
500 if (range.length == 0)
502 const void **values(new const void *[range.length]);
503 CFArrayGetValues(array, range, values);
505 #if HistogramInsertionSort > 0
506 uint32_t total(0), *offsets(new uint32_t[range.length]);
509 for (CFIndex index(1); index != range.length; ++index) {
510 const void *value(values[index]);
511 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
512 CFIndex correct(index);
513 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
514 #if HistogramInsertionSort > 1
515 NSLog(@"%@ < %@", value, values[correct - 1]);
520 if (correct != index) {
521 size_t offset(index - correct);
522 #if HistogramInsertionSort
526 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
528 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
529 values[correct] = value;
533 CFArrayReplaceValues(array, range, values, range.length);
536 #if HistogramInsertionSort > 0
537 for (CFIndex index(0); index != range.length; ++index)
538 if (offsets[index] != 0)
539 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
540 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
547 /* Apple Bug Fixes {{{ */
548 @implementation UIWebDocumentView (Cydia)
550 - (void) _setScrollerOffset:(CGPoint)offset {
551 UIScroller *scroller([self _scroller]);
553 CGSize size([scroller contentSize]);
554 CGSize bounds([scroller bounds].size);
557 max.x = size.width - bounds.width;
558 max.y = size.height - bounds.height;
566 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
567 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
569 [scroller setOffset:offset];
575 @interface NSInvocation (Cydia)
576 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target;
579 @implementation NSInvocation (Cydia)
581 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target {
582 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]]);
583 [invocation setTarget:target];
584 [invocation setSelector:selector];
590 @implementation WebScriptObject (NSFastEnumeration)
592 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
593 size_t length([self count] - state->state);
596 else if (length > count)
598 for (size_t i(0); i != length; ++i)
599 objects[i] = [self objectAtIndex:state->state++];
600 state->itemsPtr = objects;
601 state->mutationsPtr = (unsigned long *) self;
607 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
608 size_t length([self length] - state->state);
611 else if (length > count)
613 for (size_t i(0); i != length; ++i)
614 objects[i] = [self item:state->state++];
615 state->itemsPtr = objects;
616 state->mutationsPtr = (unsigned long *) self;
620 /* Cydia NSString Additions {{{ */
621 @interface NSString (Cydia)
622 - (NSComparisonResult) compareByPath:(NSString *)other;
623 - (NSString *) stringByCachingURLWithCurrentCDN;
624 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
627 @implementation NSString (UICaboodle)
629 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
630 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
633 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
634 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
639 @implementation NSString (Cydia)
641 - (NSComparisonResult) compareByPath:(NSString *)other {
642 NSString *prefix = [self commonPrefixWithString:other options:0];
643 size_t length = [prefix length];
645 NSRange lrange = NSMakeRange(length, [self length] - length);
646 NSRange rrange = NSMakeRange(length, [other length] - length);
648 lrange = [self rangeOfString:@"/" options:0 range:lrange];
649 rrange = [other rangeOfString:@"/" options:0 range:rrange];
651 NSComparisonResult value;
653 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
654 value = NSOrderedSame;
655 else if (lrange.location == NSNotFound)
656 value = NSOrderedAscending;
657 else if (rrange.location == NSNotFound)
658 value = NSOrderedDescending;
660 value = NSOrderedSame;
662 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
663 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
664 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
665 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
667 NSComparisonResult result = [lpath compare:rpath];
668 return result == NSOrderedSame ? value : result;
671 - (NSString *) stringByCachingURLWithCurrentCDN {
673 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
674 withString:@"://cache.cydia.saurik.com/"
678 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
679 return [(id)CFURLCreateStringByAddingPercentEscapes(
684 kCFStringEncodingUTF8
691 /* C++ NSString Wrapper Cache {{{ */
692 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
693 return size == 0 ? NULL :
694 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
695 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
698 static _finline CFStringRef CYStringCreate(const char *data) {
699 return CYStringCreate(data, strlen(data));
708 _finline void clear_() {
709 if (cache_ != NULL) {
716 _finline bool empty() const {
720 _finline size_t size() const {
724 _finline char *data() const {
728 _finline void clear() {
733 _finline CYString() :
740 _finline ~CYString() {
744 void operator =(const CYString &rhs) {
748 if (rhs.cache_ == nil)
751 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
754 void copy(apr_pool_t *pool) {
755 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
756 memcpy(temp, data_, size_);
761 void set(apr_pool_t *pool, const char *data, size_t size) {
767 data_ = const_cast<char *>(data);
775 _finline void set(apr_pool_t *pool, const char *data) {
776 set(pool, data, data == NULL ? 0 : strlen(data));
779 _finline void set(apr_pool_t *pool, const std::string &rhs) {
780 set(pool, rhs.data(), rhs.size());
783 bool operator ==(const CYString &rhs) const {
784 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
787 _finline operator CFStringRef() {
789 cache_ = CYStringCreate(data_, size_);
793 _finline operator id() {
794 return (NSString *) static_cast<CFStringRef>(*this);
797 _finline operator const char *() {
798 return reinterpret_cast<const char *>(data_);
802 /* C++ NSString Algorithm Adapters {{{ */
804 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
807 struct NSStringMapHash :
808 std::unary_function<NSString *, size_t>
810 _finline size_t operator ()(NSString *value) const {
811 return CFStringHashNSString((CFStringRef) value);
815 struct NSStringMapLess :
816 std::binary_function<NSString *, NSString *, bool>
818 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
819 return [lhs compare:rhs] == NSOrderedAscending;
823 struct NSStringMapEqual :
824 std::binary_function<NSString *, NSString *, bool>
826 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
827 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
828 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
829 //[lhs isEqualToString:rhs];
834 /* Mime Addresses {{{ */
835 @interface Address : NSObject {
841 - (NSString *) address;
843 - (void) setAddress:(NSString *)address;
845 + (Address *) addressWithString:(NSString *)string;
846 - (Address *) initWithString:(NSString *)string;
850 @implementation Address
859 - (NSString *) name {
863 - (NSString *) address {
867 - (void) setAddress:(NSString *)address {
869 [address_ autorelease];
873 address_ = [address retain];
876 + (Address *) addressWithString:(NSString *)string {
877 return [[[Address alloc] initWithString:string] autorelease];
880 + (NSArray *) _attributeKeys {
881 return [NSArray arrayWithObjects:
887 - (NSArray *) attributeKeys {
888 return [[self class] _attributeKeys];
891 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
892 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
895 - (Address *) initWithString:(NSString *)string {
896 if ((self = [super init]) != nil) {
897 const char *data = [string UTF8String];
898 size_t size = [string length];
900 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
902 if (address_r(data, size)) {
903 name_ = [address_r[1] retain];
904 address_ = [address_r[2] retain];
906 name_ = [string retain];
914 /* CoreGraphics Primitives {{{ */
919 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
920 CGFloat color[] = {red, green, blue, alpha};
921 return CGColorCreate(space, color);
930 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
931 color_(Create_(space, red, green, blue, alpha))
933 Set(space, red, green, blue, alpha);
938 CGColorRelease(color_);
945 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
947 color_ = Create_(space, red, green, blue, alpha);
950 operator CGColorRef() {
956 /* Random Global Variables {{{ */
957 static const int PulseInterval_ = 50000;
959 static const NSString *UI_;
962 static bool RestartSubstrate_;
963 static NSArray *Finishes_;
965 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
966 #define NotifyConfig_ "/etc/notify.conf"
968 static bool Queuing_;
970 static CYColor Blue_;
971 static CYColor Blueish_;
972 static CYColor Black_;
974 static CYColor White_;
975 static CYColor Gray_;
976 static CYColor Green_;
977 static CYColor Purple_;
978 static CYColor Purplish_;
980 static UIColor *InstallingColor_;
981 static UIColor *RemovingColor_;
983 static NSString *App_;
985 static BOOL Advanced_;
986 static BOOL Ignored_;
988 static UIFont *Font12_;
989 static UIFont *Font12Bold_;
990 static UIFont *Font14_;
991 static UIFont *Font18Bold_;
992 static UIFont *Font22Bold_;
994 static const char *Machine_ = NULL;
995 static NSString *System_ = nil;
996 static NSString *SerialNumber_ = nil;
997 static NSString *ChipID_ = nil;
998 static _H<NSString> Token_;
999 static NSString *UniqueID_ = nil;
1000 static NSString *PLMN_ = nil;
1001 static NSString *Build_ = nil;
1002 static NSString *Product_ = nil;
1003 static NSString *Safari_ = nil;
1005 static CFLocaleRef Locale_;
1006 static NSArray *Languages_;
1007 static CGColorSpaceRef space_;
1009 static NSDictionary *SectionMap_;
1010 static NSMutableDictionary *Metadata_;
1011 static _transient NSMutableDictionary *Settings_;
1012 static _transient NSString *Role_;
1013 static _transient NSMutableDictionary *Packages_;
1014 static _transient NSMutableDictionary *Sections_;
1015 static _transient NSMutableDictionary *Sources_;
1016 static bool Changed_;
1020 static CGFloat ScreenScale_;
1021 static NSString *Idiom_;
1023 static NSMutableDictionary *SessionData_;
1024 static NSObject *HostConfig_;
1025 static NSMutableSet *BridgedHosts_;
1026 static NSMutableSet *PipelinedHosts_;
1028 static NSString *kCydiaProgressEventTypeError = @"Error";
1029 static NSString *kCydiaProgressEventTypeInformation = @"Information";
1030 static NSString *kCydiaProgressEventTypeStatus = @"Status";
1031 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
1034 /* Display Helpers {{{ */
1035 inline float Interpolate(float begin, float end, float fraction) {
1036 return (end - begin) * fraction + begin;
1039 static _finline const char *StripVersion_(const char *version) {
1040 const char *colon(strchr(version, ':'));
1041 return colon == NULL ? version : colon + 1;
1044 NSString *LocalizeSection(NSString *section) {
1045 static Pcre title_r("^(.*?) \\((.*)\\)$");
1046 if (title_r(section)) {
1047 NSString *parent(title_r[1]);
1048 NSString *child(title_r[2]);
1050 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1051 LocalizeSection(parent),
1052 LocalizeSection(child)
1056 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1059 NSString *Simplify(NSString *title) {
1060 const char *data = [title UTF8String];
1061 size_t size = [title length];
1063 static Pcre square_r("^\\[(.*)\\]$");
1064 if (square_r(data, size))
1065 return Simplify(square_r[1]);
1067 static Pcre paren_r("^\\((.*)\\)$");
1068 if (paren_r(data, size))
1069 return Simplify(paren_r[1]);
1071 static Pcre title_r("^(.*?) \\((.*)\\)$");
1072 if (title_r(data, size))
1073 return Simplify(title_r[1]);
1079 NSString *GetLastUpdate() {
1080 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1083 return UCLocalize("NEVER_OR_UNKNOWN");
1085 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1086 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1088 CFRelease(formatter);
1090 return [(NSString *) formatted autorelease];
1093 bool isSectionVisible(NSString *section) {
1094 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1095 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1096 return hidden == nil || ![hidden boolValue];
1101 /* Delegate Prototypes {{{ */
1104 @class CydiaProgressEvent;
1106 @protocol DatabaseDelegate
1107 - (void) repairWithSelector:(SEL)selector;
1108 - (void) setConfigurationData:(NSString *)data;
1109 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
1112 @class CYPackageController;
1114 @protocol CydiaDelegate
1115 - (void) retainNetworkActivityIndicator;
1116 - (void) releaseNetworkActivityIndicator;
1117 - (void) clearPackage:(Package *)package;
1118 - (void) installPackage:(Package *)package;
1119 - (void) installPackages:(NSArray *)packages;
1120 - (void) removePackage:(Package *)package;
1121 - (void) beginUpdate;
1123 - (void) distUpgrade;
1125 - (void) updateData;
1127 - (void) addTrivialSource:(NSString *)href;
1128 - (void) showSettings;
1129 - (UIProgressHUD *) addProgressHUD;
1130 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1131 - (CYViewController *) pageForPackage:(NSString *)name;
1132 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1133 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1137 /* ProgressEvent Interface/Delegate {{{ */
1138 @interface CydiaProgressEvent : NSObject {
1139 _H<NSString> message_;
1143 _H<NSString> package_;
1145 _H<NSString> version_;
1148 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type;
1149 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package;
1150 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item;
1152 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type;
1154 - (NSString *) message;
1155 - (NSString *) type;
1158 - (NSString *) package;
1160 - (NSString *) version;
1162 - (void) setItem:(NSArray *)item;
1163 - (void) setPackage:(NSString *)package;
1164 - (void) setURL:(NSString *)url;
1165 - (void) setVersion:(NSString *)version;
1167 - (NSString *) compound:(NSString *)value;
1168 - (NSString *) compoundMessage;
1169 - (NSString *) compoundTitle;
1173 @protocol ProgressDelegate
1174 - (void) addProgressEvent:(CydiaProgressEvent *)event;
1175 - (void) setProgressPercent:(NSNumber *)percent;
1176 - (void) setProgressStatus:(NSDictionary *)status;
1177 - (void) setProgressCancellable:(NSNumber *)cancellable;
1178 - (bool) isProgressCancelled;
1179 - (void) setTitle:(NSString *)title;
1182 /* Status Delegation {{{ */
1184 public pkgAcquireStatus
1187 _transient NSObject<ProgressDelegate> *delegate_;
1197 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1198 delegate_ = delegate;
1201 NSObject<ProgressDelegate> *getDelegate() const {
1205 virtual bool MediaChange(std::string media, std::string drive) {
1209 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1212 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1213 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1214 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
1215 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1218 virtual void Done(pkgAcquire::ItemDesc &item) {
1221 virtual void Fail(pkgAcquire::ItemDesc &item) {
1223 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1224 item.Owner->Status == pkgAcquire::Item::StatDone
1228 std::string &error(item.Owner->ErrorText);
1232 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
1233 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1236 virtual bool Pulse(pkgAcquire *Owner) {
1237 bool value = pkgAcquireStatus::Pulse(Owner);
1240 double(CurrentBytes + CurrentItems) /
1241 double(TotalBytes + TotalItems)
1244 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1245 [NSNumber numberWithDouble:percent], @"Percent",
1247 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1248 [NSNumber numberWithDouble:TotalBytes], @"Total",
1249 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1250 nil] waitUntilDone:YES];
1252 if (value && ![delegate_ isProgressCancelled])
1260 _finline bool WasCancelled() const {
1264 virtual void Start() {
1265 pkgAcquireStatus::Start();
1266 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1269 virtual void Stop() {
1270 pkgAcquireStatus::Stop();
1271 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1272 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1276 /* Database Interface {{{ */
1277 typedef std::map< unsigned long, _H<Source> > SourceMap;
1279 @interface Database : NSObject {
1285 pkgCacheFile cache_;
1286 pkgDepCache::Policy *policy_;
1287 pkgRecords *records_;
1288 pkgProblemResolver *resolver_;
1289 pkgAcquire *fetcher_;
1291 SPtr<pkgPackageManager> manager_;
1292 pkgSourceList *list_;
1294 SourceMap sourceMap_;
1295 NSMutableArray *sourceList_;
1297 CFMutableArrayRef packages_;
1299 _transient NSObject<DatabaseDelegate> *delegate_;
1300 _transient NSObject<ProgressDelegate> *progress_;
1308 std::map<const char *, _H<NSString> > sections_;
1311 + (Database *) sharedInstance;
1314 - (void) _readCydia:(NSNumber *)fd;
1315 - (void) _readStatus:(NSNumber *)fd;
1316 - (void) _readOutput:(NSNumber *)fd;
1320 - (Package *) packageWithName:(NSString *)name;
1322 - (pkgCacheFile &) cache;
1323 - (pkgDepCache::Policy *) policy;
1324 - (pkgRecords *) records;
1325 - (pkgProblemResolver *) resolver;
1326 - (pkgAcquire &) fetcher;
1327 - (pkgSourceList &) list;
1328 - (NSArray *) packages;
1329 - (NSArray *) sources;
1330 - (Source *) sourceWithKey:(NSString *)key;
1331 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1339 - (void) updateWithStatus:(Status &)status;
1341 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1343 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1344 - (NSObject<ProgressDelegate> *) progressDelegate;
1346 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1348 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1352 /* ProgressEvent Implementation {{{ */
1353 @implementation CydiaProgressEvent
1355 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1356 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1359 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1360 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1361 [event setPackage:package];
1365 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1366 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1368 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1369 NSArray *fields([description componentsSeparatedByString:@" "]);
1370 [event setItem:fields];
1372 if ([fields count] > 3) {
1373 [event setPackage:[fields objectAtIndex:2]];
1374 [event setVersion:[fields objectAtIndex:3]];
1377 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1382 + (NSArray *) _attributeKeys {
1383 return [NSArray arrayWithObjects:
1393 - (NSArray *) attributeKeys {
1394 return [[self class] _attributeKeys];
1397 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1398 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1401 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1402 if ((self = [super init]) != nil) {
1408 - (NSString *) message {
1412 - (NSString *) type {
1416 - (NSArray *) item {
1417 return (id) item_ ?: [NSNull null];
1420 - (void) setItem:(NSArray *)item {
1424 - (NSString *) package {
1425 return (id) package_ ?: [NSNull null];
1428 - (void) setPackage:(NSString *)package {
1432 - (NSString *) url {
1433 return (id) url_ ?: [NSNull null];
1436 - (void) setURL:(NSString *)url {
1440 - (void) setVersion:(NSString *)version {
1444 - (NSString *) version {
1445 return (id) version_ ?: [NSNull null];
1448 - (NSString *) compound:(NSString *)value {
1450 NSString *mode(nil); {
1451 NSString *type([self type]);
1452 if ([type isEqualToString:kCydiaProgressEventTypeError])
1453 mode = UCLocalize("ERROR");
1454 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1455 mode = UCLocalize("WARNING");
1459 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1465 - (NSString *) compoundMessage {
1466 return [self compound:[self message]];
1469 - (NSString *) compoundTitle {
1472 if (package_ == nil)
1474 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1475 title = [package name];
1479 return [self compound:title];
1485 // Cytore Definitions {{{
1486 struct PackageValue :
1489 Cytore::Offset<PackageValue> next_;
1491 uint32_t index_ : 23;
1492 uint32_t subscribed_ : 1;
1509 Cytore::Offset<PackageValue> packages_[1 << 16];
1512 static Cytore::File<MetaValue> MetaFile_;
1514 // Cytore Helper Functions {{{
1515 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1516 SplitHash nhash = { hashlittle(name, length) };
1518 PackageValue *metadata;
1520 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1521 offset: if (offset->IsNull()) {
1522 *offset = MetaFile_.New<PackageValue>(length + 1);
1523 metadata = &MetaFile_.Get(*offset);
1525 if (metadata == NULL) {
1529 metadata = new PackageValue();
1530 memset(metadata, 0, sizeof(*metadata));
1533 memcpy(metadata->name_, name, length + 1);
1534 metadata->nhash_ = nhash.u16[1];
1536 metadata = &MetaFile_.Get(*offset);
1538 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1539 offset = &metadata->next_;
1547 static void PackageImport(const void *key, const void *value, void *context) {
1548 bool &fail(*reinterpret_cast<bool *>(context));
1551 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1552 NSLog(@"failed to import package %@", key);
1556 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1557 NSDictionary *package((NSDictionary *) value);
1559 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1560 if ([subscribed boolValue] && !metadata->subscribed_)
1561 metadata->subscribed_ = true;
1563 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1564 time_t time([date timeIntervalSince1970]);
1565 if (metadata->first_ > time || metadata->first_ == 0)
1566 metadata->first_ = time;
1569 NSDate *date([package objectForKey:@"LastSeen"]);
1570 NSString *version([package objectForKey:@"LastVersion"]);
1572 if (date != nil && version != nil) {
1573 time_t time([date timeIntervalSince1970]);
1574 if (metadata->last_ < time || metadata->last_ == 0)
1575 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1576 size_t length(strlen(buffer));
1577 uint16_t vhash(hashlittle(buffer, length));
1579 size_t capped(std::min<size_t>(8, length));
1580 char *latest(buffer + length - capped);
1582 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1583 metadata->vhash_ = vhash;
1585 metadata->last_ = time;
1591 /* Source Class {{{ */
1592 @interface Source : NSObject {
1593 CYString depiction_;
1594 CYString description_;
1600 CYString distribution_;
1605 _H<NSString> authority_;
1607 CYString defaultIcon_;
1609 _H<NSDictionary> record_;
1613 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1615 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1617 - (NSString *) depictionForPackage:(NSString *)package;
1618 - (NSString *) supportForPackage:(NSString *)package;
1620 - (NSDictionary *) record;
1624 - (NSString *) distribution;
1625 - (NSString *) type;
1627 - (NSString *) host;
1629 - (NSString *) name;
1630 - (NSString *) shortDescription;
1631 - (NSString *) label;
1632 - (NSString *) origin;
1633 - (NSString *) version;
1635 - (NSString *) defaultIcon;
1639 @implementation Source
1643 distribution_.clear();
1646 description_.clear();
1652 defaultIcon_.clear();
1660 // XXX: this is a very inefficient way to call these deconstructors
1665 + (NSArray *) _attributeKeys {
1666 return [NSArray arrayWithObjects:
1673 @"shortDescription",
1681 - (NSArray *) attributeKeys {
1682 return [[self class] _attributeKeys];
1685 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1686 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1689 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1692 trusted_ = index->IsTrusted();
1694 uri_.set(pool, index->GetURI());
1695 distribution_.set(pool, index->GetDist());
1696 type_.set(pool, index->GetType());
1698 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1699 if (dindex != NULL) {
1701 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1704 pkgTagFile tags(&fd);
1706 pkgTagSection section;
1713 {"default-icon", &defaultIcon_},
1714 {"depiction", &depiction_},
1715 {"description", &description_},
1717 {"origin", &origin_},
1718 {"support", &support_},
1719 {"version", &version_},
1722 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1723 const char *start, *end;
1725 if (section.Find(names[i].name_, start, end)) {
1726 CYString &value(*names[i].value_);
1727 value.set(pool, start, end - start);
1733 record_ = [Sources_ objectForKey:[self key]];
1735 NSURL *url([NSURL URLWithString:uri_]);
1739 host_ = [host_ lowercaseString];
1742 // XXX: this is due to a bug in _H<>
1743 authority_ = (id) host_;
1745 authority_ = [url path];
1748 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1749 if ((self = [super init]) != nil) {
1750 [self setMetaIndex:index inPool:pool];
1754 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1755 NSDictionary *lhr = [self record];
1756 NSDictionary *rhr = [source record];
1759 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1761 NSString *lhs = [self name];
1762 NSString *rhs = [source name];
1764 if ([lhs length] != 0 && [rhs length] != 0) {
1765 unichar lhc = [lhs characterAtIndex:0];
1766 unichar rhc = [rhs characterAtIndex:0];
1768 if (isalpha(lhc) && !isalpha(rhc))
1769 return NSOrderedAscending;
1770 else if (!isalpha(lhc) && isalpha(rhc))
1771 return NSOrderedDescending;
1774 return [lhs compare:rhs options:LaxCompareOptions_];
1777 - (NSString *) depictionForPackage:(NSString *)package {
1778 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1781 - (NSString *) supportForPackage:(NSString *)package {
1782 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1785 - (NSDictionary *) record {
1793 - (NSString *) uri {
1797 - (NSString *) distribution {
1798 return distribution_;
1801 - (NSString *) type {
1805 - (NSString *) key {
1806 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1809 - (NSString *) host {
1813 - (NSString *) name {
1814 return origin_.empty() ? (id) authority_ : origin_;
1817 - (NSString *) shortDescription {
1818 return description_;
1821 - (NSString *) label {
1822 return label_.empty() ? (id) authority_ : label_;
1825 - (NSString *) origin {
1829 - (NSString *) version {
1833 - (NSString *) defaultIcon {
1834 return defaultIcon_;
1839 /* CydiaOperation Class {{{ */
1840 @interface CydiaOperation : NSObject {
1841 NSString *operator_;
1845 - (NSString *) operator;
1846 - (NSString *) value;
1850 @implementation CydiaOperation
1853 [operator_ release];
1858 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1859 if ((self = [super init]) != nil) {
1860 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1861 value_ = [[NSString alloc] initWithUTF8String:value];
1865 + (NSArray *) _attributeKeys {
1866 return [NSArray arrayWithObjects:
1872 - (NSArray *) attributeKeys {
1873 return [[self class] _attributeKeys];
1876 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1877 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1880 - (NSString *) operator {
1884 - (NSString *) value {
1890 /* CydiaClause Class {{{ */
1891 @interface CydiaClause : NSObject {
1893 CydiaOperation *version_;
1896 - (NSString *) package;
1897 - (CydiaOperation *) version;
1901 @implementation CydiaClause
1909 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1910 if ((self = [super init]) != nil) {
1911 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1913 if (const char *version = dep.TargetVer())
1914 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1916 version_ = [[NSNull null] retain];
1920 + (NSArray *) _attributeKeys {
1921 return [NSArray arrayWithObjects:
1927 - (NSArray *) attributeKeys {
1928 return [[self class] _attributeKeys];
1931 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1932 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1935 - (NSString *) package {
1939 - (CydiaOperation *) version {
1945 /* CydiaRelation Class {{{ */
1946 @interface CydiaRelation : NSObject {
1947 NSString *relationship_;
1948 NSMutableArray *clauses_;
1951 - (NSString *) relationship;
1952 - (NSArray *) clauses;
1956 @implementation CydiaRelation
1959 [relationship_ release];
1964 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1965 if ((self = [super init]) != nil) {
1966 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
1967 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
1969 pkgCache::DepIterator start;
1970 pkgCache::DepIterator end;
1971 dep.GlobOr(start, end); // ++dep
1974 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1976 // yes, seriously. (wtf?)
1984 + (NSArray *) _attributeKeys {
1985 return [NSArray arrayWithObjects:
1991 - (NSArray *) attributeKeys {
1992 return [[self class] _attributeKeys];
1995 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1996 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1999 - (NSString *) relationship {
2000 return relationship_;
2003 - (NSArray *) clauses {
2007 - (void) addClause:(CydiaClause *)clause {
2008 [clauses_ addObject:clause];
2013 /* Package Class {{{ */
2014 struct ParsedPackage {
2019 CYString depiction_;
2029 @interface Package : NSObject {
2032 uint32_t essential_ : 1;
2033 uint32_t obsolete_ : 1;
2034 uint32_t ignored_ : 1;
2038 _transient Database *database_;
2040 pkgCache::VerIterator version_;
2041 pkgCache::PkgIterator iterator_;
2042 pkgCache::VerFileIterator file_;
2048 CYString installed_;
2050 const char *section_;
2051 _transient NSString *section$_;
2055 PackageValue *metadata_;
2056 ParsedPackage *parsed_;
2058 NSMutableArray *tags_;
2061 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2062 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2064 - (pkgCache::PkgIterator) iterator;
2067 - (NSString *) section;
2068 - (NSString *) simpleSection;
2070 - (NSString *) longSection;
2071 - (NSString *) shortSection;
2075 - (Address *) maintainer;
2077 - (NSString *) longDescription;
2078 - (NSString *) shortDescription;
2081 - (PackageValue *) metadata;
2084 - (bool) subscribed;
2085 - (bool) setSubscribed:(bool)subscribed;
2089 - (NSString *) latest;
2090 - (NSString *) installed;
2091 - (BOOL) uninstalled;
2094 - (BOOL) upgradableAndEssential:(BOOL)essential;
2097 - (BOOL) unfiltered;
2101 - (BOOL) halfConfigured;
2102 - (BOOL) halfInstalled;
2104 - (NSString *) mode;
2107 - (NSString *) name;
2109 - (NSString *) homepage;
2110 - (NSString *) depiction;
2111 - (Address *) author;
2113 - (NSString *) support;
2115 - (NSArray *) files;
2116 - (NSArray *) warnings;
2117 - (NSArray *) applications;
2119 - (Source *) source;
2121 - (BOOL) matches:(NSString *)text;
2123 - (bool) hasSupportingRole;
2124 - (BOOL) hasTag:(NSString *)tag;
2125 - (NSString *) primaryPurpose;
2126 - (NSArray *) purposes;
2127 - (bool) isCommercial;
2129 - (void) setIndex:(size_t)index;
2131 - (CYString &) cyname;
2133 - (uint32_t) compareBySection:(NSArray *)sections;
2138 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2139 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2140 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2141 - (bool) isVisibleInSection:(NSString *)section;
2142 - (bool) isVisibleInSource:(Source *)source;
2146 uint32_t PackageChangesRadix(Package *self, void *) {
2151 uint32_t timestamp : 30;
2152 uint32_t ignored : 1;
2153 uint32_t upgradable : 1;
2157 bool upgradable([self upgradableAndEssential:YES]);
2158 value.bits.upgradable = upgradable ? 1 : 0;
2161 value.bits.timestamp = 0;
2162 value.bits.ignored = [self ignored] ? 0 : 1;
2163 value.bits.upgradable = 1;
2165 value.bits.timestamp = [self seen] >> 2;
2166 value.bits.ignored = 0;
2167 value.bits.upgradable = 0;
2170 return _not(uint32_t) - value.key;
2173 uint32_t PackagePrefixRadix(Package *self, void *context) {
2174 size_t offset(reinterpret_cast<size_t>(context));
2175 CYString &name([self cyname]);
2177 size_t size(name.size());
2180 char *text(name.data());
2183 if (!isdigit(text[0]))
2187 while (size != digits && isdigit(text[digits]))
2195 if (offset == 0 && zeros != 0) {
2196 memset(data, '0', zeros);
2197 memcpy(data + zeros, text, 4 - zeros);
2199 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2200 if (size <= offset - zeros)
2203 text += offset - zeros;
2204 size -= offset - zeros;
2207 memcpy(data, text, 4);
2209 memcpy(data, text, size);
2210 memset(data + size, 0, 4 - size);
2213 for (size_t i(0); i != 4; ++i)
2214 if (isalpha(data[i]))
2222 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2224 /* XXX: ntohl may be more honest */
2225 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2228 CYString &(*PackageName)(Package *self, SEL sel);
2230 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2231 _profile(PackageNameCompare)
2232 CYString &lhi(PackageName(lhs, @selector(cyname)));
2233 CYString &rhi(PackageName(rhs, @selector(cyname)));
2234 CFStringRef lhn(lhi), rhn(rhi);
2237 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2238 else if (rhn == NULL)
2239 return NSOrderedDescending;
2241 _profile(PackageNameCompare$NumbersLast)
2242 if (!lhi.empty() && !rhi.empty()) {
2243 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2244 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2245 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2246 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2247 return lha ? NSOrderedAscending : NSOrderedDescending;
2251 CFIndex length = CFStringGetLength(lhn);
2253 _profile(PackageNameCompare$Compare)
2254 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2259 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2260 return PackageNameCompare(*lhs, *rhs, context);
2263 struct PackageNameOrdering :
2264 std::binary_function<Package *, Package *, bool>
2266 _finline bool operator ()(Package *lhs, Package *rhs) const {
2267 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2271 @implementation Package
2273 - (NSString *) description {
2274 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2278 if (parsed_ != NULL)
2287 + (NSString *) webScriptNameForSelector:(SEL)selector {
2289 else if (selector == @selector(clear))
2291 else if (selector == @selector(getField:))
2293 else if (selector == @selector(hasTag:))
2295 else if (selector == @selector(install))
2297 else if (selector == @selector(remove))
2303 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2304 return [self webScriptNameForSelector:selector] == nil;
2307 + (NSArray *) _attributeKeys {
2308 return [NSArray arrayWithObjects:
2327 @"shortDescription",
2340 - (NSArray *) attributeKeys {
2341 return [[self class] _attributeKeys];
2344 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2345 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2348 - (NSArray *) relations {
2349 @synchronized (database_) {
2350 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2351 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2352 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2356 - (NSString *) getField:(NSString *)name {
2357 @synchronized (database_) {
2358 if ([database_ era] != era_ || file_.end())
2361 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2363 const char *start, *end;
2364 if (!parser.Find([name UTF8String], start, end))
2365 return (NSString *) [NSNull null];
2367 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2371 if (parsed_ != NULL)
2373 @synchronized (database_) {
2374 if ([database_ era] != era_ || file_.end())
2377 ParsedPackage *parsed(new ParsedPackage);
2380 _profile(Package$parse)
2381 pkgRecords::Parser *parser;
2383 _profile(Package$parse$Lookup)
2384 parser = &[database_ records]->Lookup(file_);
2389 _profile(Package$parse$Find)
2394 {"icon", &parsed->icon_},
2395 {"depiction", &parsed->depiction_},
2396 {"homepage", &parsed->homepage_},
2397 {"website", &website},
2398 {"bugs", &parsed->bugs_},
2399 {"support", &parsed->support_},
2400 {"sponsor", &parsed->sponsor_},
2401 {"author", &parsed->author_},
2404 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2405 const char *start, *end;
2407 if (parser->Find(names[i].name_, start, end)) {
2408 CYString &value(*names[i].value_);
2409 _profile(Package$parse$Value)
2410 value.set(pool_, start, end - start);
2416 _profile(Package$parse$Tagline)
2417 const char *start, *end;
2418 if (parser->ShortDesc(start, end)) {
2419 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2422 while (stop != start && stop[-1] == '\r')
2424 parsed->tagline_.set(pool_, start, stop - start);
2428 _profile(Package$parse$Retain)
2429 if (parsed->homepage_.empty())
2430 parsed->homepage_ = website;
2431 if (parsed->homepage_ == parsed->depiction_)
2432 parsed->homepage_.clear();
2437 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2438 if ((self = [super init]) != nil) {
2439 _profile(Package$initWithVersion)
2442 database_ = database;
2443 era_ = [database era];
2447 pkgCache::PkgIterator iterator(version.ParentPkg());
2448 iterator_ = iterator;
2450 _profile(Package$initWithVersion$Version)
2451 if (!version_.end())
2452 file_ = version_.FileList();
2454 pkgCache &cache([database_ cache]);
2455 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2459 _profile(Package$initWithVersion$Cache)
2460 name_.set(NULL, iterator.Display());
2462 latest_.set(NULL, StripVersion_(version_.VerStr()));
2464 pkgCache::VerIterator current(iterator.CurrentVer());
2466 installed_.set(NULL, StripVersion_(current.VerStr()));
2469 _profile(Package$initWithVersion$Tags)
2470 pkgCache::TagIterator tag(iterator.TagList());
2472 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2474 const char *name(tag.Name());
2475 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2477 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2478 if (strcmp(name + 6, "enduser") == 0)
2480 else if (strcmp(name + 6, "hacker") == 0)
2482 else if (strcmp(name + 6, "developer") == 0)
2484 else if (strcmp(name + 6, "cydia") == 0)
2490 if (strncmp(name, "cydia::", 7) == 0) {
2491 if (strcmp(name + 7, "essential") == 0)
2493 else if (strcmp(name + 7, "obsolete") == 0)
2498 } while (!tag.end());
2502 _profile(Package$initWithVersion$Metadata)
2503 const char *mixed(iterator.Name());
2504 size_t size(strlen(mixed));
2505 char lower[size + 1];
2507 for (size_t i(0); i != size; ++i)
2508 lower[i] = mixed[i] | 0x20;
2511 PackageValue *metadata(PackageFind(lower, size));
2512 metadata_ = metadata;
2514 id_.set(NULL, metadata->name_, size);
2516 const char *latest(version_.VerStr());
2517 size_t length(strlen(latest));
2519 uint16_t vhash(hashlittle(latest, length));
2521 size_t capped(std::min<size_t>(8, length));
2522 latest = latest + length - capped;
2524 if (metadata->first_ == 0)
2525 metadata->first_ = now_;
2527 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2528 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2529 metadata->vhash_ = vhash;
2530 metadata->last_ = now_;
2531 } else if (metadata->last_ == 0)
2532 metadata->last_ = metadata->first_;
2535 _profile(Package$initWithVersion$Section)
2536 section_ = iterator.Section();
2539 _profile(Package$initWithVersion$Flags)
2540 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2541 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2546 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2547 pkgCache::VerIterator version;
2549 _profile(Package$packageWithIterator$GetCandidateVer)
2550 version = [database policy]->GetCandidateVer(iterator);
2558 _profile(Package$packageWithIterator$Allocate)
2559 package = [Package allocWithZone:zone];
2562 _profile(Package$packageWithIterator$Initialize)
2564 initWithVersion:version
2571 _profile(Package$packageWithIterator$Autorelease)
2572 package = [package autorelease];
2578 - (pkgCache::PkgIterator) iterator {
2582 - (NSString *) section {
2583 if (section$_ == nil) {
2584 if (section_ == NULL)
2587 _profile(Package$section$mappedSectionForPointer)
2588 section$_ = [database_ mappedSectionForPointer:section_];
2593 - (NSString *) simpleSection {
2594 if (NSString *section = [self section])
2595 return Simplify(section);
2600 - (NSString *) longSection {
2601 return LocalizeSection([self section]);
2604 - (NSString *) shortSection {
2605 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2608 - (NSString *) uri {
2611 pkgIndexFile *index;
2612 pkgCache::PkgFileIterator file(file_.File());
2613 if (![database_ list].FindIndex(file, index))
2615 return [NSString stringWithUTF8String:iterator_->Path];
2616 //return [NSString stringWithUTF8String:file.Site()];
2617 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2621 - (Address *) maintainer {
2622 @synchronized (database_) {
2623 if ([database_ era] != era_ || file_.end())
2626 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2627 const std::string &maintainer(parser->Maintainer());
2628 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2632 @synchronized (database_) {
2633 if ([database_ era] != era_ || version_.end())
2636 return version_->InstalledSize;
2639 - (NSString *) longDescription {
2640 @synchronized (database_) {
2641 if ([database_ era] != era_ || file_.end())
2644 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2645 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2647 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2648 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2649 if ([lines count] < 2)
2652 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2653 for (size_t i(1), e([lines count]); i != e; ++i) {
2654 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2655 [trimmed addObject:trim];
2658 return [trimmed componentsJoinedByString:@"\n"];
2661 - (NSString *) shortDescription {
2662 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2666 _profile(Package$index)
2667 CFStringRef name((CFStringRef) [self name]);
2668 if (CFStringGetLength(name) == 0)
2670 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2671 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2673 return toupper(character);
2677 - (PackageValue *) metadata {
2682 PackageValue *metadata([self metadata]);
2683 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2686 - (bool) subscribed {
2687 return [self metadata]->subscribed_;
2690 - (bool) setSubscribed:(bool)subscribed {
2691 PackageValue *metadata([self metadata]);
2692 if (metadata->subscribed_ == subscribed)
2694 metadata->subscribed_ = subscribed;
2702 - (NSString *) latest {
2706 - (NSString *) installed {
2710 - (BOOL) uninstalled {
2711 return installed_.empty();
2715 return !version_.end();
2718 - (BOOL) upgradableAndEssential:(BOOL)essential {
2719 _profile(Package$upgradableAndEssential)
2720 pkgCache::VerIterator current(iterator_.CurrentVer());
2722 return essential && essential_;
2724 return !version_.end() && version_ != current;
2728 - (BOOL) essential {
2733 return [database_ cache][iterator_].InstBroken();
2736 - (BOOL) unfiltered {
2737 _profile(Package$unfiltered$obsolete)
2738 if (_unlikely(obsolete_))
2742 _profile(Package$unfiltered$hasSupportingRole)
2743 if (_unlikely(![self hasSupportingRole]))
2751 if (![self unfiltered])
2756 _profile(Package$visible$section)
2757 section = [self section];
2760 _profile(Package$visible$isSectionVisible)
2761 if (!isSectionVisible(section))
2769 unsigned char current(iterator_->CurrentState);
2770 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2773 - (BOOL) halfConfigured {
2774 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2777 - (BOOL) halfInstalled {
2778 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2782 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2783 return state.Mode != pkgDepCache::ModeKeep;
2786 - (NSString *) mode {
2787 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2789 switch (state.Mode) {
2790 case pkgDepCache::ModeDelete:
2791 if ((state.iFlags & pkgDepCache::Purge) != 0)
2795 case pkgDepCache::ModeKeep:
2796 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2797 return @"REINSTALL";
2798 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2802 case pkgDepCache::ModeInstall:
2803 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2804 return @"REINSTALL";
2805 else*/ switch (state.Status) {
2807 return @"DOWNGRADE";
2813 return @"NEW_INSTALL";
2824 - (NSString *) name {
2825 return name_.empty() ? id_ : name_;
2828 - (UIImage *) icon {
2829 NSString *section = [self simpleSection];
2832 if (parsed_ != NULL)
2833 if (NSString *href = parsed_->icon_)
2834 if ([href hasPrefix:@"file:///"])
2835 // XXX: correct escaping
2836 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2837 if (icon == nil) if (section != nil)
2838 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2839 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2840 if ([dicon hasPrefix:@"file:///"])
2841 // XXX: correct escaping
2842 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2844 icon = [UIImage applicationImageNamed:@"unknown.png"];
2848 - (NSString *) homepage {
2849 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2852 - (NSString *) depiction {
2853 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2856 - (Address *) sponsor {
2857 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2860 - (Address *) author {
2861 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2864 - (NSString *) support {
2865 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2868 - (NSArray *) files {
2869 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2870 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2873 fin.open([path UTF8String]);
2878 while (std::getline(fin, line))
2879 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2884 - (NSString *) state {
2885 @synchronized (database_) {
2886 if ([database_ era] != era_ || file_.end())
2889 switch (iterator_->CurrentState) {
2890 case pkgCache::State::NotInstalled:
2891 return @"NotInstalled";
2892 case pkgCache::State::UnPacked:
2894 case pkgCache::State::HalfConfigured:
2895 return @"HalfConfigured";
2896 case pkgCache::State::HalfInstalled:
2897 return @"HalfInstalled";
2898 case pkgCache::State::ConfigFiles:
2899 return @"ConfigFiles";
2900 case pkgCache::State::Installed:
2901 return @"Installed";
2902 case pkgCache::State::TriggersAwaited:
2903 return @"TriggersAwaited";
2904 case pkgCache::State::TriggersPending:
2905 return @"TriggersPending";
2908 return (NSString *) [NSNull null];
2911 - (NSString *) selection {
2912 @synchronized (database_) {
2913 if ([database_ era] != era_ || file_.end())
2916 switch (iterator_->SelectedState) {
2917 case pkgCache::State::Unknown:
2919 case pkgCache::State::Install:
2921 case pkgCache::State::Hold:
2923 case pkgCache::State::DeInstall:
2924 return @"DeInstall";
2925 case pkgCache::State::Purge:
2929 return (NSString *) [NSNull null];
2932 - (NSArray *) warnings {
2933 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2934 const char *name(iterator_.Name());
2936 size_t length(strlen(name));
2937 if (length < 2) invalid:
2938 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2939 else for (size_t i(0); i != length; ++i)
2941 /* XXX: technically this is not allowed */
2942 (name[i] < 'A' || name[i] > 'Z') &&
2943 (name[i] < 'a' || name[i] > 'z') &&
2944 (name[i] < '0' || name[i] > '9') &&
2945 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2948 if (strcmp(name, "cydia") != 0) {
2951 bool _private = false;
2954 bool repository = [[self section] isEqualToString:@"Repositories"];
2956 if (NSArray *files = [self files])
2957 for (NSString *file in files)
2958 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2960 else if (!user && [file isEqualToString:@"/User"])
2962 else if (!_private && [file isEqualToString:@"/private"])
2964 else if (!stash && [file isEqualToString:@"/var/stash"])
2967 /* XXX: this is not sensitive enough. only some folders are valid. */
2968 if (cydia && !repository)
2969 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2971 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2973 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2975 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2978 return [warnings count] == 0 ? nil : warnings;
2981 - (NSArray *) applications {
2982 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2984 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2986 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2987 if (NSArray *files = [self files])
2988 for (NSString *file in files)
2989 if (application_r(file)) {
2990 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2991 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2992 if ([id isEqualToString:me])
2995 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2997 display = application_r[1];
2999 NSString *bundle([file stringByDeletingLastPathComponent]);
3000 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3001 if (icon == nil || [icon length] == 0)
3003 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3005 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3006 [applications addObject:application];
3008 [application addObject:id];
3009 [application addObject:display];
3010 [application addObject:url];
3013 return [applications count] == 0 ? nil : applications;
3016 - (Source *) source {
3017 if (source_ == nil) {
3018 @synchronized (database_) {
3019 if ([database_ era] != era_ || file_.end())
3020 source_ = (Source *) [NSNull null];
3022 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
3026 return source_ == (Source *) [NSNull null] ? nil : source_;
3029 - (BOOL) matches:(NSString *)text {
3035 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
3036 if (range.location != NSNotFound)
3039 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
3040 if (range.location != NSNotFound)
3045 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
3046 if (range.location != NSNotFound)
3052 - (bool) hasSupportingRole {
3057 if ([Role_ isEqualToString:@"User"])
3061 if ([Role_ isEqualToString:@"Hacker"])
3065 if ([Role_ isEqualToString:@"Developer"])
3070 - (NSArray *) tags {
3074 - (BOOL) hasTag:(NSString *)tag {
3075 return tags_ == nil ? NO : [tags_ containsObject:tag];
3078 - (NSString *) primaryPurpose {
3079 for (NSString *tag in tags_)
3080 if ([tag hasPrefix:@"purpose::"])
3081 return [tag substringFromIndex:9];
3085 - (NSArray *) purposes {
3086 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3087 for (NSString *tag in tags_)
3088 if ([tag hasPrefix:@"purpose::"])
3089 [purposes addObject:[tag substringFromIndex:9]];
3090 return [purposes count] == 0 ? nil : purposes;
3093 - (bool) isCommercial {
3094 return [self hasTag:@"cydia::commercial"];
3097 - (void) setIndex:(size_t)index {
3098 if (metadata_->index_ != index)
3099 metadata_->index_ = index;
3102 - (CYString &) cyname {
3103 return name_.empty() ? id_ : name_;
3106 - (uint32_t) compareBySection:(NSArray *)sections {
3107 NSString *section([self section]);
3108 for (size_t i(0), e([sections count]); i != e; ++i) {
3109 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3113 return _not(uint32_t);
3117 @synchronized (database_) {
3118 pkgProblemResolver *resolver = [database_ resolver];
3119 resolver->Clear(iterator_);
3121 pkgCacheFile &cache([database_ cache]);
3122 cache->SetReInstall(iterator_, false);
3123 cache->MarkKeep(iterator_, false);
3127 @synchronized (database_) {
3128 pkgProblemResolver *resolver = [database_ resolver];
3129 resolver->Clear(iterator_);
3130 resolver->Protect(iterator_);
3132 pkgCacheFile &cache([database_ cache]);
3133 cache->SetReInstall(iterator_, false);
3134 cache->MarkInstall(iterator_, false);
3136 pkgDepCache::StateCache &state((*cache)[iterator_]);
3137 if (!state.Install())
3138 cache->SetReInstall(iterator_, true);
3142 @synchronized (database_) {
3143 pkgProblemResolver *resolver = [database_ resolver];
3144 resolver->Clear(iterator_);
3145 resolver->Remove(iterator_);
3146 resolver->Protect(iterator_);
3148 pkgCacheFile &cache([database_ cache]);
3149 cache->SetReInstall(iterator_, false);
3150 cache->MarkDelete(iterator_, true);
3153 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3154 _profile(Package$isUnfilteredAndSearchedForBy)
3157 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3158 value &= [self unfiltered];
3161 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3162 value &= [self matches:search];
3169 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3170 if ([search length] == 0)
3173 _profile(Package$isUnfilteredAndSelectedForBy)
3176 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3177 value &= [self unfiltered];
3180 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3181 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3188 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3189 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3192 - (bool) isVisibleInSection:(NSString *)name {
3193 NSString *section([self section]);
3197 section == nil && [name length] == 0 ||
3198 [name isEqualToString:section]
3199 ) && [self visible];
3202 - (bool) isVisibleInSource:(Source *)source {
3203 return [self source] == source && [self visible];
3208 /* Section Class {{{ */
3209 @interface Section : NSObject {
3214 NSString *localized_;
3217 - (NSComparisonResult) compareByLocalized:(Section *)section;
3218 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3219 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3220 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3221 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3222 - (NSString *) name;
3229 - (void) addToCount;
3231 - (void) setCount:(size_t)count;
3232 - (NSString *) localized;
3236 @implementation Section
3240 if (localized_ != nil)
3241 [localized_ release];
3245 - (NSComparisonResult) compareByLocalized:(Section *)section {
3246 NSString *lhs(localized_);
3247 NSString *rhs([section localized]);
3249 /*if ([lhs length] != 0 && [rhs length] != 0) {
3250 unichar lhc = [lhs characterAtIndex:0];
3251 unichar rhc = [rhs characterAtIndex:0];
3253 if (isalpha(lhc) && !isalpha(rhc))
3254 return NSOrderedAscending;
3255 else if (!isalpha(lhc) && isalpha(rhc))
3256 return NSOrderedDescending;
3259 return [lhs compare:rhs options:LaxCompareOptions_];
3262 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3263 if ((self = [self initWithName:name localize:NO]) != nil) {
3264 if (localized != nil)
3265 localized_ = [localized retain];
3269 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3270 return [self initWithName:name row:0 localize:localize];
3273 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3274 if ((self = [super init]) != nil) {
3275 name_ = [name retain];
3279 localized_ = [LocalizeSection(name_) retain];
3283 /* XXX: localize the index thingees */
3284 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3285 if ((self = [super init]) != nil) {
3286 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3292 - (NSString *) name {
3312 - (void) addToCount {
3316 - (void) setCount:(size_t)count {
3320 - (NSString *) localized {
3327 static NSString *Colon_;
3328 static NSString *Elision_;
3329 static NSString *Error_;
3330 static NSString *Warning_;
3332 /* Database Implementation {{{ */
3333 @implementation Database
3335 + (Database *) sharedInstance {
3336 static Database *instance;
3337 if (instance == nil)
3338 instance = [[Database alloc] init];
3346 - (void) releasePackages {
3347 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3348 CFArrayRemoveAllValues(packages_);
3352 // XXX: actually implement this thing
3354 [sourceList_ release];
3355 [self releasePackages];
3356 apr_pool_destroy(pool_);
3357 NSRecycleZone(zone_);
3361 - (void) _readCydia:(NSNumber *)fd { _pooled
3362 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3363 std::istream is(&ib);
3366 static Pcre finish_r("^finish:([^:]*)$");
3368 while (std::getline(is, line)) {
3369 const char *data(line.c_str());
3370 size_t size = line.size();
3371 lprintf("C:%s\n", data);
3373 if (finish_r(data, size)) {
3374 NSString *finish = finish_r[1];
3375 int index = [Finishes_ indexOfObject:finish];
3376 if (index != INT_MAX && index > Finish_)
3384 - (void) _readStatus:(NSNumber *)fd { _pooled
3385 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3386 std::istream is(&ib);
3389 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3390 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3392 while (std::getline(is, line)) {
3393 const char *data(line.c_str());
3394 size_t size(line.size());
3395 lprintf("S:%s\n", data);
3397 if (conffile_r(data, size)) {
3398 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3399 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3400 } else if (strncmp(data, "status: ", 8) == 0) {
3401 // status: <package>: {unpacked,half-configured,installed}
3402 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3403 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3404 } else if (strncmp(data, "processing: ", 12) == 0) {
3405 // processing: configure: config-test
3406 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3407 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3408 } else if (pmstatus_r(data, size)) {
3409 std::string type([pmstatus_r[1] UTF8String]);
3411 NSString *package = pmstatus_r[2];
3412 if ([package isEqualToString:@"dpkg-exec"])
3415 float percent([pmstatus_r[3] floatValue]);
3416 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3418 NSString *string = pmstatus_r[4];
3420 if (type == "pmerror") {
3421 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3422 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3423 } else if (type == "pmstatus") {
3424 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3425 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3426 } else if (type == "pmconffile")
3427 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3429 lprintf("E:unknown pmstatus\n");
3431 lprintf("E:unknown status\n");
3437 - (void) _readOutput:(NSNumber *)fd { _pooled
3438 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3439 std::istream is(&ib);
3442 while (std::getline(is, line)) {
3443 lprintf("O:%s\n", line.c_str());
3445 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3446 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3456 - (Package *) packageWithName:(NSString *)name {
3457 @synchronized (self) {
3458 if (static_cast<pkgDepCache *>(cache_) == NULL)
3460 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3461 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3465 if ((self = [super init]) != nil) {
3472 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3473 apr_pool_create(&pool_, NULL);
3475 size_t capacity(MetaFile_->active_);
3481 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3482 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3486 _assert(pipe(fds) != -1);
3489 _config->Set("APT::Keep-Fds::", cydiafd_);
3490 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3493 detachNewThreadSelector:@selector(_readCydia:)
3495 withObject:[NSNumber numberWithInt:fds[0]]
3498 _assert(pipe(fds) != -1);
3502 detachNewThreadSelector:@selector(_readStatus:)
3504 withObject:[NSNumber numberWithInt:fds[0]]
3507 _assert(pipe(fds) != -1);
3508 _assert(dup2(fds[0], 0) != -1);
3509 _assert(close(fds[0]) != -1);
3511 input_ = fdopen(fds[1], "a");
3513 _assert(pipe(fds) != -1);
3514 _assert(dup2(fds[1], 1) != -1);
3515 _assert(close(fds[1]) != -1);
3518 detachNewThreadSelector:@selector(_readOutput:)
3520 withObject:[NSNumber numberWithInt:fds[0]]
3525 - (pkgCacheFile &) cache {
3529 - (pkgDepCache::Policy *) policy {
3533 - (pkgRecords *) records {
3537 - (pkgProblemResolver *) resolver {
3541 - (pkgAcquire &) fetcher {
3545 - (pkgSourceList &) list {
3549 - (NSArray *) packages {
3550 return (NSArray *) packages_;
3553 - (NSArray *) sources {
3557 - (Source *) sourceWithKey:(NSString *)key {
3558 for (Source *source in [self sources]) {
3559 if ([[source key] isEqualToString:key])
3564 - (bool) popErrorWithTitle:(NSString *)title {
3567 while (!_error->empty()) {
3569 bool warning(!_error->PopMessage(error));
3574 size_t size(error.size());
3575 if (size == 0 || error[size - 1] != '\n')
3577 error.resize(size - 1);
3580 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3582 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3588 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3589 return [self popErrorWithTitle:title] || !success;
3592 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3593 @synchronized (self) {
3596 [self releasePackages];
3599 [sourceList_ removeAllObjects];
3619 apr_pool_clear(pool_);
3621 NSRecycleZone(zone_);
3622 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3624 int chk(creat("/tmp/cydia.chk", 0644));
3628 if (invocation != nil)
3629 [invocation invoke];
3631 NSString *title(UCLocalize("DATABASE"));
3634 OpProgress progress;
3635 while (!cache_.Open(progress, true)) { pop:
3637 bool warning(!_error->PopMessage(error));
3638 lprintf("cache_.Open():[%s]\n", error.c_str());
3640 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3641 [delegate_ repairWithSelector:@selector(configure)];
3642 else if (error == "The package lists or status file could not be parsed or opened.")
3643 [delegate_ repairWithSelector:@selector(update)];
3644 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3645 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3646 // else if (error == "Malformed Status line")
3647 // else if (error == "The list of sources could not be read.")
3649 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3659 unlink("/tmp/cydia.chk");
3661 now_ = [[NSDate date] timeIntervalSince1970];
3663 policy_ = new pkgDepCache::Policy();
3664 records_ = new pkgRecords(cache_);
3665 resolver_ = new pkgProblemResolver(cache_);
3666 fetcher_ = new pkgAcquire(&status_);
3669 list_ = new pkgSourceList();
3670 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3673 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3674 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3678 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3681 if (cache_->BrokenCount() != 0) {
3682 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3685 if (cache_->BrokenCount() != 0) {
3686 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3690 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3694 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3695 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3696 [sourceList_ addObject:object];
3698 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3699 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3700 // XXX: this could be more intelligent
3701 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3702 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3704 sourceMap_[cached->ID] = object;
3709 /*std::vector<Package *> packages;
3710 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3711 [packages_ release];
3716 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3717 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3718 //packages.push_back(package);
3719 CFArrayAppendValue(packages_, [package retain]);
3723 /*if (packages.empty())
3724 packages_ = [[NSArray alloc] init];
3726 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3729 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3730 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3731 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3739 /*if (!packages.empty())
3740 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3741 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3743 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3745 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3747 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3751 size_t count(CFArrayGetCount(packages_));
3752 MetaFile_->active_ = count;
3754 for (size_t index(0); index != count; ++index)
3755 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3759 } } CYPoolEnd() _trace(); }
3762 @synchronized (self) {
3764 resolver_ = new pkgProblemResolver(cache_);
3766 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3767 if (!cache_[iterator].Keep())
3768 cache_->MarkKeep(iterator, false);
3769 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3770 cache_->SetReInstall(iterator, false);
3773 - (void) configure {
3774 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3776 system([dpkg UTF8String]);
3781 // XXX: I don't remember this condition
3786 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3788 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3790 if ([self popErrorWithTitle:title])
3794 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3797 public pkgArchiveCleaner
3800 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3805 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3812 fetcher_->Shutdown();
3814 pkgRecords records(cache_);
3816 lock_ = new FileFd();
3817 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3819 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3821 if ([self popErrorWithTitle:title])
3825 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3828 manager_ = (_system->CreatePM(cache_));
3829 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3836 bool substrate(RestartSubstrate_);
3837 RestartSubstrate_ = false;
3839 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3841 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3843 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3845 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3846 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3849 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3851 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3853 [self popErrorWithTitle:title];
3857 bool failed = false;
3858 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3859 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3861 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3867 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3875 RestartSubstrate_ = true;
3878 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3880 if (_error->PendingError()) {
3885 if (result == pkgPackageManager::Failed) {
3890 if (result != pkgPackageManager::Completed) {
3895 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3897 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3899 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3900 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3903 if (![before isEqualToArray:after])
3908 NSString *title(UCLocalize("UPGRADE"));
3909 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3915 [self updateWithStatus:status_];
3918 - (void) updateWithStatus:(Status &)status {
3919 NSString *title(UCLocalize("REFRESHING_DATA"));
3922 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3926 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3927 if ([self popErrorWithTitle:title])
3930 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3932 bool success(ListUpdate(status, list, PulseInterval_));
3933 if (status.WasCancelled())
3936 [self popErrorWithTitle:title forOperation:success];
3938 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3940 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3944 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3945 delegate_ = delegate;
3948 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3949 progress_ = delegate;
3950 status_.setDelegate(delegate);
3953 - (NSObject<ProgressDelegate> *) progressDelegate {
3957 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3958 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3959 return i == sourceMap_.end() ? nil : i->second;
3962 - (NSString *) mappedSectionForPointer:(const char *)section {
3963 _H<NSString> *mapped;
3965 _profile(Database$mappedSectionForPointer$Cache)
3966 mapped = §ions_[section];
3969 if (*mapped == NULL) {
3970 size_t length(strlen(section));
3971 char spaced[length + 1];
3973 _profile(Database$mappedSectionForPointer$Replace)
3974 for (size_t index(0); index != length; ++index)
3975 spaced[index] = section[index] == '_' ? ' ' : section[index];
3976 spaced[length] = '\0';
3981 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3982 string = [NSString stringWithUTF8String:spaced];
3985 _profile(Database$mappedSectionForPointer$Map)
3986 string = [SectionMap_ objectForKey:string] ?: string;
3996 static NSMutableSet *Diversions_;
3998 @interface Diversion : NSObject {
4001 _H<NSString> format_;
4006 @implementation Diversion
4008 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4009 if ((self = [super init]) != nil) {
4010 pattern_ = [from UTF8String];
4016 - (NSString *) divert:(NSString *)url {
4017 return !pattern_(url) ? nil : pattern_->*format_;
4020 + (NSURL *) divertURL:(NSURL *)url {
4022 NSString *href([url absoluteString]);
4024 for (Diversion *diversion in Diversions_)
4025 if (NSString *diverted = [diversion divert:href]) {
4026 url = [NSURL URLWithString:diverted];
4033 - (NSString *) key {
4037 - (NSUInteger) hash {
4041 - (BOOL) isEqual:(Diversion *)object {
4042 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4047 @interface CydiaObject : NSObject {
4049 _transient id delegate_;
4052 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4056 @interface CYBrowserController : BrowserController {
4057 CydiaObject *cydia_;
4060 + (void) addDiversion:(Diversion *)diversion;
4064 /* Web Scripting {{{ */
4065 @implementation CydiaObject
4068 [indirect_ release];
4072 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4073 if ((self = [super init]) != nil) {
4074 indirect_ = [indirect retain];
4078 - (void) setDelegate:(id)delegate {
4079 delegate_ = delegate;
4082 + (NSArray *) _attributeKeys {
4083 return [NSArray arrayWithObjects:
4098 - (NSArray *) attributeKeys {
4099 return [[self class] _attributeKeys];
4102 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4103 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4106 - (NSString *) version {
4110 - (NSString *) device {
4111 return [[UIDevice currentDevice] uniqueIdentifier];
4114 - (NSString *) firmware {
4115 return [[UIDevice currentDevice] systemVersion];
4118 - (NSString *) hostname {
4119 return [[UIDevice currentDevice] name];
4122 - (NSString *) idiom {
4123 return (id) Idiom_ ?: [NSNull null];
4126 - (NSString *) plmn {
4127 return (id) PLMN_ ?: [NSNull null];
4130 - (NSString *) ecid {
4131 return (id) ChipID_ ?: [NSNull null];
4134 - (NSString *) serial {
4135 return SerialNumber_;
4138 - (NSString *) role {
4139 return (id) Role_ ?: [NSNull null];
4142 - (NSString *) model {
4143 return [NSString stringWithUTF8String:Machine_];
4146 - (NSString *) token {
4147 return (id) Token_ ?: [NSNull null];
4150 + (NSString *) webScriptNameForSelector:(SEL)selector {
4152 else if (selector == @selector(addBridgedHost:))
4153 return @"addBridgedHost";
4154 else if (selector == @selector(addPipelinedHost:scheme:))
4155 return @"addPipelinedHost";
4156 else if (selector == @selector(addTrivialSource:))
4157 return @"addTrivialSource";
4158 else if (selector == @selector(close))
4160 else if (selector == @selector(divert::))
4162 else if (selector == @selector(du:))
4164 else if (selector == @selector(stringWithFormat:arguments:))
4166 else if (selector == @selector(getAllSources))
4167 return @"getAllSourcs";
4168 else if (selector == @selector(getKernelNumber:))
4169 return @"getKernelNumber";
4170 else if (selector == @selector(getKernelString:))
4171 return @"getKernelString";
4172 else if (selector == @selector(getInstalledPackages))
4173 return @"getInstalledPackages";
4174 else if (selector == @selector(getPackageById:))
4175 return @"getPackageById";
4176 else if (selector == @selector(getSessionValue:))
4177 return @"getSessionValue";
4178 else if (selector == @selector(installPackages:))
4179 return @"installPackages";
4180 else if (selector == @selector(localizedStringForKey:value:table:))
4182 else if (selector == @selector(popViewController:))
4183 return @"popViewController";
4184 else if (selector == @selector(refreshSources))
4185 return @"refreshSources";
4186 else if (selector == @selector(removeButton))
4187 return @"removeButton";
4188 else if (selector == @selector(setSessionValue::))
4189 return @"setSessionValue";
4190 else if (selector == @selector(substitutePackageNames:))
4191 return @"substitutePackageNames";
4192 else if (selector == @selector(scrollToBottom:))
4193 return @"scrollToBottom";
4194 else if (selector == @selector(setAllowsNavigationAction:))
4195 return @"setAllowsNavigationAction";
4196 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4197 return @"setButtonImage";
4198 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4199 return @"setButtonTitle";
4200 else if (selector == @selector(setHidesBackButton:))
4201 return @"setHidesBackButton";
4202 else if (selector == @selector(setHidesNavigationBar:))
4203 return @"setHidesNavigationBar";
4204 else if (selector == @selector(setNavigationBarStyle:))
4205 return @"setNavigationBarStyle";
4206 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4207 return @"setNavigationBarTintColor";
4208 else if (selector == @selector(setToken:))
4210 else if (selector == @selector(setViewportWidth:))
4211 return @"setViewportWidth";
4212 else if (selector == @selector(statfs:))
4214 else if (selector == @selector(supports:))
4220 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4221 return [self webScriptNameForSelector:selector] == nil;
4224 - (BOOL) supports:(NSString *)feature {
4225 return [feature isEqualToString:@"window.open"];
4228 - (void) divert:(NSString *)from :(NSString *)to {
4229 [CYBrowserController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4232 - (NSNumber *) getKernelNumber:(NSString *)name {
4233 const char *string([name UTF8String]);
4236 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4237 return (id) [NSNull null];
4239 if (size != sizeof(int))
4240 return (id) [NSNull null];
4243 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4244 return (id) [NSNull null];
4246 return [NSNumber numberWithInt:value];
4249 - (NSString *) getKernelString:(NSString *)name {
4250 const char *string([name UTF8String]);
4253 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4254 return (id) [NSNull null];
4256 char value[size + 1];
4257 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4258 return (id) [NSNull null];
4260 // XXX: just in case you request something ludicrous
4263 return [NSString stringWithCString:value];
4266 - (id) getSessionValue:(NSString *)key {
4267 @synchronized (SessionData_) {
4268 return [SessionData_ objectForKey:key];
4271 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4272 @synchronized (SessionData_) {
4273 if (value == (id) [WebUndefined undefined])
4274 [SessionData_ removeObjectForKey:key];
4276 [SessionData_ setObject:value forKey:key];
4279 - (void) addBridgedHost:(NSString *)host {
4280 @synchronized (HostConfig_) {
4281 [BridgedHosts_ addObject:host];
4284 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4285 @synchronized (HostConfig_) {
4286 if (scheme != (id) [WebUndefined undefined])
4287 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4289 [PipelinedHosts_ addObject:host];
4292 - (void) popViewController:(NSNumber *)value {
4293 if (value == (id) [WebUndefined undefined])
4294 value = [NSNumber numberWithBool:YES];
4295 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4298 - (void) addTrivialSource:(NSString *)href {
4299 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4302 - (void) refreshSources {
4303 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4306 - (NSArray *) getAllSources {
4307 return [[Database sharedInstance] sources];
4310 - (NSArray *) getInstalledPackages {
4311 Database *database([Database sharedInstance]);
4312 @synchronized (database) {
4313 NSArray *packages([database packages]);
4314 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4315 for (Package *package in packages)
4316 if (![package uninstalled])
4317 [installed addObject:package];
4321 - (Package *) getPackageById:(NSString *)id {
4322 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4326 return (Package *) [NSNull null];
4329 - (NSArray *) statfs:(NSString *)path {
4332 if (path == nil || statfs([path UTF8String], &stat) == -1)
4335 return [NSArray arrayWithObjects:
4336 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4337 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4338 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4342 - (NSNumber *) du:(NSString *)path {
4343 NSNumber *value(nil);
4346 _assert(pipe(fds) != -1);
4348 pid_t pid(ExecFork());
4350 _assert(dup2(fds[1], 1) != -1);
4351 _assert(close(fds[0]) != -1);
4352 _assert(close(fds[1]) != -1);
4353 /* XXX: this should probably not use du */
4354 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4359 _assert(close(fds[1]) != -1);
4361 if (FILE *du = fdopen(fds[0], "r")) {
4363 while (fgets(line, sizeof(line), du) != NULL) {
4364 size_t length(strlen(line));
4365 while (length != 0 && line[length - 1] == '\n')
4366 line[--length] = '\0';
4367 if (char *tab = strchr(line, '\t')) {
4369 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4374 } else _assert(close(fds[0]));
4378 if (waitpid(pid, &status, 0) == -1)
4381 else _assert(false);
4387 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4390 - (void) installPackages:(NSArray *)packages {
4391 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4394 - (NSString *) substitutePackageNames:(NSString *)message {
4395 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4396 for (size_t i(0), e([words count]); i != e; ++i) {
4397 NSString *word([words objectAtIndex:i]);
4398 if (Package *package = [[Database sharedInstance] packageWithName:word])
4399 [words replaceObjectAtIndex:i withObject:[package name]];
4402 return [words componentsJoinedByString:@" "];
4405 - (void) removeButton {
4406 [indirect_ removeButton];
4409 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4410 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4413 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4414 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
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) _setToken:(NSString *)token {
4443 [Metadata_ removeObjectForKey:@"Token"];
4445 [Metadata_ setObject:Token_ forKey:@"Token"];
4450 - (void) setToken:(NSString *)token {
4451 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4454 - (void) scrollToBottom:(NSNumber *)animated {
4455 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4458 - (void) setViewportWidth:(float)width {
4459 [indirect_ setViewportWidthOnMainThread:width];
4462 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4463 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4464 unsigned count([arguments count]);
4466 for (unsigned i(0); i != count; ++i)
4467 values[i] = [arguments objectAtIndex:i];
4468 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4471 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4472 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4474 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4476 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4482 /* @ Loading... Indicator {{{ */
4483 @interface CYLoadingIndicator : UIView {
4484 _H<UIActivityIndicatorView> spinner_;
4486 _H<UIView> container_;
4489 @property (readonly, nonatomic) UILabel *label;
4490 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4494 @implementation CYLoadingIndicator
4496 - (id) initWithFrame:(CGRect)frame {
4497 if ((self = [super initWithFrame:frame]) != nil) {
4498 container_ = [[[UIView alloc] init] autorelease];
4499 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4501 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4502 [spinner_ startAnimating];
4503 [container_ addSubview:spinner_];
4505 label_ = [[[UILabel alloc] init] autorelease];
4506 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4507 [label_ setBackgroundColor:[UIColor clearColor]];
4508 [label_ setTextColor:[UIColor blackColor]];
4509 [label_ setShadowColor:[UIColor whiteColor]];
4510 [label_ setShadowOffset:CGSizeMake(0, 1)];
4511 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4512 [container_ addSubview:label_];
4514 CGSize viewsize = frame.size;
4515 CGSize spinnersize = [spinner_ bounds].size;
4516 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4517 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4519 CGRect containrect = {
4520 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4521 CGSizeMake(bothwidth, spinnersize.height)
4524 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4532 [container_ setFrame:containrect];
4533 [spinner_ setFrame:spinrect];
4534 [label_ setFrame:textrect];
4535 [self addSubview:container_];
4539 - (UILabel *) label {
4543 - (UIActivityIndicatorView *) activityIndicatorView {
4549 /* Emulated Loading Controller {{{ */
4550 @interface CYEmulatedLoadingController : CYViewController {
4551 _transient Database *database_;
4552 _H<CYLoadingIndicator> indicator_;
4553 _H<UITabBar> tabbar_;
4554 _H<UINavigationBar> navbar_;
4559 @implementation CYEmulatedLoadingController
4561 - (id) initWithDatabase:(Database *)database {
4562 if ((self = [super init]) != nil) {
4563 database_ = database;
4568 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4570 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4571 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4572 [[self view] addSubview:table];
4574 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4575 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4576 [[self view] addSubview:indicator_];
4578 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4579 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4580 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4581 [[self view] addSubview:tabbar_];
4583 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4584 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4585 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4586 [[self view] addSubview:navbar_];
4589 - (void) releaseSubviews {
4598 /* Cydia Browser Controller {{{ */
4599 @implementation CYBrowserController
4606 - (NSURL *) navigationURL {
4607 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4610 + (void) initialize {
4611 Diversions_ = [[NSMutableSet alloc] initWithCapacity:0];
4614 + (void) addDiversion:(Diversion *)diversion {
4615 [Diversions_ addObject:diversion];
4618 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4619 [super webView:view didClearWindowObject:window forFrame:frame];
4621 WebDataSource *source([frame dataSource]);
4622 NSURLResponse *response([source response]);
4623 NSURL *url([response URL]);
4624 NSString *scheme([[url scheme] lowercaseString]);
4626 bool bridged(false);
4628 @synchronized (HostConfig_) {
4629 if ([scheme isEqualToString:@"file"])
4631 else if ([scheme isEqualToString:@"https"])
4632 if ([BridgedHosts_ containsObject:[url host]])
4637 [window setValue:cydia_ forKey:@"cydia"];
4640 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4641 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4643 [copy setURL:[Diversion divertURL:[copy URL]]];
4645 if (System_ != NULL)
4646 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4647 if (Machine_ != NULL)
4648 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4650 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4655 - (void) setDelegate:(id)delegate {
4656 [super setDelegate:delegate];
4657 [cydia_ setDelegate:delegate];
4661 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4662 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4664 WebView *webview([[webview_ _documentView] webView]);
4666 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4669 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4671 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4672 if (Product_ != nil)
4673 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4675 [webview setApplicationNameForUserAgent:application];
4683 @interface NSObject (CydiaScript)
4684 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4687 @implementation NSObject (CydiaScript)
4689 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4695 @implementation NSArray (CydiaScript)
4697 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4698 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4699 for (size_t i(0), e([self count]); i != e; ++i)
4700 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4706 @implementation NSDictionary (CydiaScript)
4708 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4709 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4711 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4718 /* Confirmation Controller {{{ */
4719 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4720 if (!iterator.end())
4721 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4722 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4724 pkgCache::PkgIterator package(dep.TargetPkg());
4727 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4734 @protocol ConfirmationControllerDelegate
4735 - (void) cancelAndClear:(bool)clear;
4736 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4740 @interface ConfirmationController : CYBrowserController {
4741 _transient Database *database_;
4743 UIAlertView *essential_;
4745 NSDictionary *changes_;
4746 NSMutableArray *issues_;
4747 NSDictionary *sizes_;
4752 - (id) initWithDatabase:(Database *)database;
4756 @implementation ConfirmationController
4763 if (essential_ != nil)
4764 [essential_ release];
4771 RestartSubstrate_ = true;
4772 [delegate_ confirmWithNavigationController:[self navigationController]];
4775 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4776 NSString *context([alert context]);
4778 if ([context isEqualToString:@"remove"]) {
4779 if (button == [alert cancelButtonIndex])
4780 [self dismissModalViewControllerAnimated:YES];
4781 else if (button == [alert firstOtherButtonIndex]) {
4785 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4786 } else if ([context isEqualToString:@"unable"]) {
4787 [self dismissModalViewControllerAnimated:YES];
4788 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4790 [super alertView:alert clickedButtonAtIndex:button];
4794 - (void) _doContinue {
4795 [self dismissModalViewControllerAnimated:YES];
4796 [delegate_ cancelAndClear:NO];
4799 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4800 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4804 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4805 [super webView:view didClearWindowObject:window forFrame:frame];
4807 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4808 changes_, @"changes",
4812 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4815 - (id) initWithDatabase:(Database *)database {
4816 if ((self = [super init]) != nil) {
4817 database_ = database;
4819 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4820 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4821 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4822 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4823 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4827 pkgCacheFile &cache([database_ cache]);
4828 NSArray *packages([database_ packages]);
4829 pkgDepCache::Policy *policy([database_ policy]);
4831 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4833 for (Package *package in packages) {
4834 pkgCache::PkgIterator iterator([package iterator]);
4835 NSString *name([package id]);
4837 if ([package broken]) {
4838 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4840 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4842 reasons, @"reasons",
4845 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4849 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4850 pkgCache::DepIterator start;
4851 pkgCache::DepIterator end;
4852 dep.GlobOr(start, end); // ++dep
4854 if (!cache->IsImportantDep(end))
4856 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4859 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4861 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4862 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4863 clauses, @"clauses",
4867 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4869 pkgCache::PkgIterator target(start.TargetPkg());
4870 if (target->ProvidesList != 0)
4871 reason = @"missing";
4873 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4875 reason = @"installed";
4876 installed = [NSString stringWithUTF8String:ver.VerStr()];
4877 } else if (!cache[target].CandidateVerIter(cache).end())
4878 reason = @"uninstalled";
4879 else if (target->ProvidesList == 0)
4880 reason = @"uninstallable";
4882 reason = @"virtual";
4885 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4886 [NSString stringWithUTF8String:start.CompType()], @"operator",
4887 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4890 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4891 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4892 version, @"version",
4894 installed, @"installed",
4897 // yes, seriously. (wtf?)
4905 pkgDepCache::StateCache &state(cache[iterator]);
4907 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4909 if (state.NewInstall())
4910 [installs addObject:name];
4911 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4912 [reinstalls addObject:name];
4913 else if (state.Upgrade())
4914 [upgrades addObject:name];
4915 else if (state.Downgrade())
4916 [downgrades addObject:name];
4917 else if (!state.Delete())
4919 else if (special_r(name))
4920 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4921 [NSNull null], @"package",
4922 [NSArray arrayWithObjects:
4923 [NSDictionary dictionaryWithObjectsAndKeys:
4924 @"Conflicts", @"relationship",
4925 [NSArray arrayWithObjects:
4926 [NSDictionary dictionaryWithObjectsAndKeys:
4928 [NSNull null], @"version",
4929 @"installed", @"reason",
4936 if ([package essential])
4938 [removes addObject:name];
4941 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4942 substrate_ |= DepSubstrate(iterator.CurrentVer());
4947 else if (Advanced_) {
4948 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4950 essential_ = [[UIAlertView alloc]
4951 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4952 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4954 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4956 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4960 [essential_ setContext:@"remove"];
4962 essential_ = [[UIAlertView alloc]
4963 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4964 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4966 cancelButtonTitle:UCLocalize("OKAY")
4967 otherButtonTitles:nil
4970 [essential_ setContext:@"unable"];
4973 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4974 installs, @"installs",
4975 reinstalls, @"reinstalls",
4976 upgrades, @"upgrades",
4977 downgrades, @"downgrades",
4978 removes, @"removes",
4981 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4982 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4983 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4986 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4988 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4989 initWithTitle:UCLocalize("CANCEL")
4990 style:UIBarButtonItemStylePlain
4992 action:@selector(cancelButtonClicked)
4998 - (void) applyRightButton {
4999 if ([issues_ count] == 0 && ![self isLoading])
5000 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5001 initWithTitle:UCLocalize("CONFIRM")
5002 style:UIBarButtonItemStyleDone
5004 action:@selector(confirmButtonClicked)
5007 [[self navigationItem] setRightBarButtonItem:nil];
5011 - (void) cancelButtonClicked {
5012 [self dismissModalViewControllerAnimated:YES];
5013 [delegate_ cancelAndClear:YES];
5017 - (void) confirmButtonClicked {
5018 if (essential_ != nil)
5028 /* Progress Data {{{ */
5029 @interface CydiaProgressData : NSObject {
5030 _transient id delegate_;
5039 _H<NSMutableArray> events_;
5040 _H<NSString> title_;
5042 _H<NSString> status_;
5043 _H<NSString> finish_;
5048 @implementation CydiaProgressData
5050 + (NSArray *) _attributeKeys {
5051 return [NSArray arrayWithObjects:
5063 - (NSArray *) attributeKeys {
5064 return [[self class] _attributeKeys];
5067 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5068 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5072 if ((self = [super init]) != nil) {
5073 events_ = [NSMutableArray arrayWithCapacity:32];
5077 - (void) setDelegate:(id)delegate {
5078 delegate_ = delegate;
5081 - (void) setPercent:(float)value {
5085 - (NSNumber *) percent {
5086 return [NSNumber numberWithFloat:percent_];
5089 - (void) setCurrent:(float)value {
5093 - (NSNumber *) current {
5094 return [NSNumber numberWithFloat:current_];
5097 - (void) setTotal:(float)value {
5101 - (NSNumber *) total {
5102 return [NSNumber numberWithFloat:total_];
5105 - (void) setSpeed:(float)value {
5109 - (NSNumber *) speed {
5110 return [NSNumber numberWithFloat:speed_];
5113 - (NSArray *) events {
5117 - (void) removeAllEvents {
5118 [events_ removeAllObjects];
5121 - (void) addEvent:(CydiaProgressEvent *)event {
5122 [events_ addObject:event];
5125 - (void) setTitle:(NSString *)text {
5129 - (NSString *) title {
5133 - (void) setFinish:(NSString *)text {
5137 - (NSString *) finish {
5138 return (id) finish_ ?: [NSNull null];
5141 - (void) setRunning:(bool)running {
5145 - (NSNumber *) running {
5146 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5151 /* Progress Controller {{{ */
5152 @interface ProgressController : CYBrowserController <
5155 _transient Database *database_;
5156 _H<CydiaProgressData> progress_;
5160 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5162 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5164 - (void) setTitle:(NSString *)title;
5165 - (void) setCancellable:(bool)cancellable;
5169 @implementation ProgressController
5172 [database_ setProgressDelegate:nil];
5173 [progress_ setDelegate:nil];
5177 - (void) updateCancel {
5178 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5179 initWithTitle:UCLocalize("CANCEL")
5180 style:UIBarButtonItemStylePlain
5182 action:@selector(cancel)
5183 ] autorelease] : nil)];
5186 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5187 if ((self = [super init]) != nil) {
5188 database_ = database;
5189 delegate_ = delegate;
5191 [database_ setProgressDelegate:self];
5193 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5194 [progress_ setDelegate:self];
5196 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5198 [scroller_ setBackgroundColor:[UIColor blackColor]];
5200 [[self navigationItem] setHidesBackButton:YES];
5202 [self updateCancel];
5206 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5207 [super webView:view didClearWindowObject:window forFrame:frame];
5208 [window setValue:progress_ forKey:@"cydiaProgress"];
5211 - (void) updateProgress {
5212 [self dispatchEvent:@"CydiaProgressUpdate"];
5215 - (void) viewWillAppear:(BOOL)animated {
5216 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5217 [super viewWillAppear:animated];
5221 UpdateExternalStatus(0);
5228 [delegate_ terminateWithSuccess];
5229 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5230 [delegate_ suspendWithAnimation:YES];
5232 [delegate_ suspend];*/
5244 system("/usr/bin/sbreload");
5250 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5251 SBReboot(SBSSpringBoardServerPort());
5253 reboot2(RB_AUTOBOOT);
5260 - (void) setTitle:(NSString *)title {
5261 [progress_ setTitle:title];
5262 [self updateProgress];
5265 - (UIBarButtonItem *) rightButton {
5266 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5267 initWithTitle:UCLocalize("CLOSE")
5268 style:UIBarButtonItemStylePlain
5270 action:@selector(close)
5274 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5275 UpdateExternalStatus(1);
5277 [progress_ setRunning:true];
5278 [self setTitle:title];
5279 // implicit updateProgress
5281 SHA1SumValue notifyconf; {
5283 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5286 MMap mmap(file, MMap::ReadOnly);
5288 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5289 notifyconf = sha1.Result();
5293 SHA1SumValue springlist; {
5295 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5298 MMap mmap(file, MMap::ReadOnly);
5300 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5301 springlist = sha1.Result();
5305 if (invocation != nil) {
5306 [invocation yieldToSelector:@selector(invoke)];
5307 [self setTitle:@"COMPLETE"];
5312 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5315 MMap mmap(file, MMap::ReadOnly);
5317 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5318 if (!(notifyconf == sha1.Result()))
5325 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5328 MMap mmap(file, MMap::ReadOnly);
5330 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5331 if (!(springlist == sha1.Result()))
5337 if (RestartSubstrate_)
5341 RestartSubstrate_ = false;
5344 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5345 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5346 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5347 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5348 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5352 system("su -c /usr/bin/uicache mobile");
5355 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5357 [progress_ setRunning:false];
5358 [self updateProgress];
5360 [self applyRightButton];
5363 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5364 [progress_ addEvent:event];
5365 [self updateProgress];
5368 - (bool) isProgressCancelled {
5369 return cancel_ == 2;
5374 [self updateCancel];
5377 - (void) setCancellable:(bool)cancellable {
5378 unsigned cancel(cancel_);
5382 else if (cancel_ == 0)
5385 if (cancel != cancel_)
5386 [self updateCancel];
5389 - (void) setProgressCancellable:(NSNumber *)cancellable {
5390 [self setCancellable:[cancellable boolValue]];
5393 - (void) setProgressPercent:(NSNumber *)percent {
5394 [progress_ setPercent:[percent floatValue]];
5395 [self updateProgress];
5398 - (void) setProgressStatus:(NSDictionary *)status {
5399 if (status == nil) {
5400 [progress_ setCurrent:0];
5401 [progress_ setTotal:0];
5402 [progress_ setSpeed:0];
5404 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5406 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5407 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5408 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5411 [self updateProgress];
5417 /* Cell Content View {{{ */
5418 @protocol ContentDelegate
5419 - (void) drawContentRect:(CGRect)rect;
5422 @interface ContentView : UIView {
5423 _transient id<ContentDelegate> delegate_;
5428 @implementation ContentView
5430 - (id) initWithFrame:(CGRect)frame {
5431 if ((self = [super initWithFrame:frame]) != nil) {
5432 [self setNeedsDisplayOnBoundsChange:YES];
5436 - (void) setDelegate:(id<ContentDelegate>)delegate {
5437 delegate_ = delegate;
5440 - (void) drawRect:(CGRect)rect {
5441 [super drawRect:rect];
5442 [delegate_ drawContentRect:rect];
5447 /* Cydia TableView Cell {{{ */
5448 @interface CYTableViewCell : UITableViewCell {
5449 ContentView *content_;
5455 @implementation CYTableViewCell
5462 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5463 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5465 if (view == content_) {
5466 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5467 highlighted_ = highlighted;
5470 [super _updateHighlightColorsForView:view highlighted:highlighted];
5473 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5474 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5475 highlighted_ = selected;
5477 [super setSelected:selected animated:animated];
5478 [content_ setNeedsDisplay];
5484 /* Package Cell {{{ */
5485 @interface PackageCell : CYTableViewCell <
5490 NSString *description_;
5498 - (PackageCell *) init;
5499 - (void) setPackage:(Package *)package;
5501 - (void) drawContentRect:(CGRect)rect;
5505 @implementation PackageCell
5507 - (void) clearPackage {
5518 if (description_ != nil) {
5519 [description_ release];
5523 if (source_ != nil) {
5528 if (badge_ != nil) {
5533 if (placard_ != nil) {
5543 [self clearPackage];
5547 - (PackageCell *) init {
5548 CGRect frame(CGRectMake(0, 0, 320, 74));
5549 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5550 UIView *content([self contentView]);
5551 CGRect bounds([content bounds]);
5553 content_ = [[ContentView alloc] initWithFrame:bounds];
5554 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5555 [content addSubview:content_];
5557 [content_ setDelegate:self];
5558 [content_ setOpaque:YES];
5562 - (NSString *) accessibilityLabel {
5563 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5566 - (void) setPackage:(Package *)package {
5567 [self clearPackage];
5570 Source *source = [package source];
5572 icon_ = [[package icon] retain];
5573 name_ = [[package name] retain];
5576 description_ = [package longDescription];
5577 if (description_ == nil)
5578 description_ = [package shortDescription];
5579 if (description_ != nil)
5580 description_ = [description_ retain];
5582 commercial_ = [package isCommercial];
5584 package_ = [package retain];
5586 NSString *label = nil;
5587 bool trusted = false;
5589 if (source != nil) {
5590 label = [source label];
5591 trusted = [source trusted];
5592 } else if ([[package id] isEqualToString:@"firmware"])
5593 label = UCLocalize("APPLE");
5595 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5597 NSString *from(label);
5599 NSString *section = [package simpleSection];
5600 if (section != nil && ![section isEqualToString:label]) {
5601 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5602 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5605 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5606 source_ = [from retain];
5608 if (NSString *purpose = [package primaryPurpose])
5609 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5610 badge_ = [badge_ retain];
5615 if (NSString *mode = [package_ mode]) {
5616 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5617 color = RemovingColor_;
5618 //placard = @"removing";
5620 color = InstallingColor_;
5621 //placard = @"installing";
5624 // XXX: the removing/installing placards are not @2x
5627 color = [UIColor whiteColor];
5629 if ([package installed] != nil)
5630 placard = @"installed";
5635 [content_ setBackgroundColor:color];
5638 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5639 placard_ = [placard_ retain];
5641 [self setNeedsDisplay];
5642 [content_ setNeedsDisplay];
5645 - (void) drawContentRect:(CGRect)rect {
5646 bool highlighted(highlighted_);
5647 float width([self bounds].size.width);
5650 CGContextRef context(UIGraphicsGetCurrentContext());
5651 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5652 CGContextFillRect(context, rect);
5657 rect.size = [icon_ size];
5659 rect.size.width /= 2;
5660 rect.size.height /= 2;
5662 rect.origin.x = 25 - rect.size.width / 2;
5663 rect.origin.y = 25 - rect.size.height / 2;
5665 [icon_ drawInRect:rect];
5668 if (badge_ != nil) {
5670 rect.size = [badge_ size];
5672 rect.size.width /= 2;
5673 rect.size.height /= 2;
5675 rect.origin.x = 36 - rect.size.width / 2;
5676 rect.origin.y = 36 - rect.size.height / 2;
5678 [badge_ drawInRect:rect];
5685 UISetColor(commercial_ ? Purple_ : Black_);
5686 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5687 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5690 UISetColor(commercial_ ? Purplish_ : Gray_);
5691 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5693 if (placard_ != nil)
5694 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5699 /* Section Cell {{{ */
5700 @interface SectionCell : CYTableViewCell <
5712 - (void) setSection:(Section *)section editing:(BOOL)editing;
5716 @implementation SectionCell
5718 - (void) clearSection {
5719 if (basic_ != nil) {
5724 if (section_ != nil) {
5734 if (count_ != nil) {
5741 [self clearSection];
5747 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5748 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5749 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5750 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5751 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5753 UIView *content([self contentView]);
5754 CGRect bounds([content bounds]);
5756 content_ = [[ContentView alloc] initWithFrame:bounds];
5757 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5758 [content addSubview:content_];
5759 [content_ setBackgroundColor:[UIColor whiteColor]];
5761 [content_ setDelegate:self];
5765 - (void) onSwitch:(id)sender {
5766 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5767 if (metadata == nil) {
5768 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5769 [Sections_ setObject:metadata forKey:basic_];
5772 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5776 - (void) setSection:(Section *)section editing:(BOOL)editing {
5777 if (editing != editing_) {
5779 [switch_ removeFromSuperview];
5781 [self addSubview:switch_];
5785 [self clearSection];
5787 if (section == nil) {
5788 name_ = [UCLocalize("ALL_PACKAGES") retain];
5791 basic_ = [section name];
5793 basic_ = [basic_ retain];
5795 section_ = [section localized];
5796 if (section_ != nil)
5797 section_ = [section_ retain];
5799 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5800 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5803 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5806 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5807 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5809 [content_ setNeedsDisplay];
5812 - (void) setFrame:(CGRect)frame {
5813 [super setFrame:frame];
5815 CGRect rect([switch_ frame]);
5816 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5819 - (NSString *) accessibilityLabel {
5823 - (void) drawContentRect:(CGRect)rect {
5824 bool highlighted(highlighted_ && !editing_);
5826 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5831 float width(rect.size.width);
5837 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5839 CGSize size = [count_ sizeWithFont:Font14_];
5843 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5849 /* File Table {{{ */
5850 @interface FileTable : CYViewController <
5851 UITableViewDataSource,
5854 _transient Database *database_;
5857 NSMutableArray *files_;
5861 - (id) initWithDatabase:(Database *)database;
5862 - (void) setPackage:(Package *)package;
5866 @implementation FileTable
5869 [self releaseSubviews];
5878 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5879 return files_ == nil ? 0 : [files_ count];
5882 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5886 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5887 static NSString *reuseIdentifier = @"Cell";
5889 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5891 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5892 [cell setFont:[UIFont systemFontOfSize:16]];
5894 [cell setText:[files_ objectAtIndex:indexPath.row]];
5895 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5900 - (NSURL *) navigationURL {
5901 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5905 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5907 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5908 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5909 [list_ setRowHeight:24.0f];
5910 [list_ setDataSource:self];
5911 [list_ setDelegate:self];
5912 [[self view] addSubview:list_];
5915 - (void) viewDidLoad {
5916 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5919 - (void) releaseSubviews {
5924 - (id) initWithDatabase:(Database *)database {
5925 if ((self = [super init]) != nil) {
5926 database_ = database;
5928 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5932 - (void) setPackage:(Package *)package {
5933 if (package_ != nil) {
5934 [package_ autorelease];
5943 [files_ removeAllObjects];
5945 if (package != nil) {
5946 package_ = [package retain];
5947 name_ = [[package id] retain];
5949 if (NSArray *files = [package files])
5950 [files_ addObjectsFromArray:files];
5952 if ([files_ count] != 0) {
5953 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5954 [files_ removeObjectAtIndex:0];
5955 [files_ sortUsingSelector:@selector(compareByPath:)];
5957 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5958 [stack addObject:@"/"];
5960 for (int i(0), e([files_ count]); i != e; ++i) {
5961 NSString *file = [files_ objectAtIndex:i];
5962 while (![file hasPrefix:[stack lastObject]])
5963 [stack removeLastObject];
5964 NSString *directory = [stack lastObject];
5965 [stack addObject:[file stringByAppendingString:@"/"]];
5966 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5967 ([stack count] - 2) * 3, "",
5968 [file substringFromIndex:[directory length]]
5977 - (void) reloadData {
5980 [self setPackage:[database_ packageWithName:name_]];
5985 /* Package Controller {{{ */
5986 @interface CYPackageController : CYBrowserController <
5987 UIActionSheetDelegate
5989 _transient Database *database_;
5990 _H<Package> package_;
5993 _H<NSMutableArray> buttons_;
5994 _H<UIBarButtonItem> button_;
5997 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
6001 @implementation CYPackageController
6003 - (NSURL *) navigationURL {
6004 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6007 /* XXX: this is not safe at all... localization of /fail/ */
6008 - (void) _clickButtonWithName:(NSString *)name {
6009 if ([name isEqualToString:UCLocalize("CLEAR")])
6010 [delegate_ clearPackage:package_];
6011 else if ([name isEqualToString:UCLocalize("INSTALL")])
6012 [delegate_ installPackage:package_];
6013 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6014 [delegate_ installPackage:package_];
6015 else if ([name isEqualToString:UCLocalize("REMOVE")])
6016 [delegate_ removePackage:package_];
6017 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6018 [delegate_ installPackage:package_];
6019 else _assert(false);
6022 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6023 NSString *context([sheet context]);
6025 if ([context isEqualToString:@"modify"]) {
6026 if (button != [sheet cancelButtonIndex]) {
6027 NSString *buttonName = [buttons_ objectAtIndex:button];
6028 [self _clickButtonWithName:buttonName];
6031 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6035 - (bool) _allowJavaScriptPanel {
6040 - (void) _customButtonClicked {
6041 int count([buttons_ count]);
6046 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6048 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6049 [buttons addObjectsFromArray:buttons_];
6051 UIActionSheet *sheet = [[[UIActionSheet alloc]
6054 cancelButtonTitle:nil
6055 destructiveButtonTitle:nil
6056 otherButtonTitles:nil
6059 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6061 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6062 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6064 [sheet setContext:@"modify"];
6066 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6070 // We don't want to allow non-commercial packages to do custom things to the install button,
6071 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6072 - (void) customButtonClicked {
6074 [super customButtonClicked];
6076 [self _customButtonClicked];
6079 - (void) reloadButtonClicked {
6080 // Don't reload a commerical package by tapping the loading button,
6081 // but if it's not an Install button, we should forward it on.
6082 if (![package_ uninstalled])
6083 [self _customButtonClicked];
6086 - (void) applyLoadingTitle {
6087 // Don't show "Loading" as the title. Ever.
6090 - (UIBarButtonItem *) rightButton {
6095 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
6096 if ((self = [super init]) != nil) {
6097 database_ = database;
6098 buttons_ = [NSMutableArray arrayWithCapacity:4];
6099 name_ = [NSString stringWithString:name];
6100 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
6104 - (void) reloadData {
6107 package_ = [database_ packageWithName:name_];
6109 [buttons_ removeAllObjects];
6111 if (package_ != nil) {
6112 [(Package *) package_ parse];
6114 commercial_ = [package_ isCommercial];
6116 if ([package_ mode] != nil)
6117 [buttons_ addObject:UCLocalize("CLEAR")];
6118 if ([package_ source] == nil);
6119 else if ([package_ upgradableAndEssential:NO])
6120 [buttons_ addObject:UCLocalize("UPGRADE")];
6121 else if ([package_ uninstalled])
6122 [buttons_ addObject:UCLocalize("INSTALL")];
6124 [buttons_ addObject:UCLocalize("REINSTALL")];
6125 if (![package_ uninstalled])
6126 [buttons_ addObject:UCLocalize("REMOVE")];
6130 switch ([buttons_ count]) {
6131 case 0: title = nil; break;
6132 case 1: title = [buttons_ objectAtIndex:0]; break;
6133 default: title = UCLocalize("MODIFY"); break;
6136 button_ = [[[UIBarButtonItem alloc]
6138 style:UIBarButtonItemStylePlain
6140 action:@selector(customButtonClicked)
6144 - (bool) isLoading {
6145 return commercial_ ? [super isLoading] : false;
6151 /* Package List Controller {{{ */
6152 @interface PackageListController : CYViewController <
6153 UITableViewDataSource,
6156 _transient Database *database_;
6158 NSMutableArray *packages_;
6159 NSMutableArray *sections_;
6161 NSMutableArray *index_;
6162 NSMutableDictionary *indices_;
6166 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6167 - (void) setDelegate:(id)delegate;
6168 - (void) resetCursor;
6172 @implementation PackageListController
6175 [packages_ release];
6176 [sections_ release];
6185 - (void) deselectWithAnimation:(BOOL)animated {
6186 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6189 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6190 CGRect base = [[self view] bounds];
6191 base.size.height -= bounds.size.height;
6192 base.origin = [list_ frame].origin;
6194 [UIView beginAnimations:nil context:NULL];
6195 [UIView setAnimationBeginsFromCurrentState:YES];
6196 [UIView setAnimationCurve:curve];
6197 [UIView setAnimationDuration:duration];
6198 [list_ setFrame:base];
6199 [UIView commitAnimations];
6202 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6203 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6206 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6207 [self resizeForKeyboardBounds:bounds duration:0];
6210 - (void) keyboardWillShow:(NSNotification *)notification {
6213 NSTimeInterval duration;
6214 UIViewAnimationCurve curve;
6215 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6216 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6217 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6218 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6220 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);
6221 UIViewController *base = self;
6222 while ([base parentViewController] != nil)
6223 base = [base parentViewController];
6224 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6225 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6227 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6230 - (void) keyboardWillHide:(NSNotification *)notification {
6231 NSTimeInterval duration;
6232 UIViewAnimationCurve curve;
6233 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6234 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6236 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6239 - (void) viewWillAppear:(BOOL)animated {
6240 [super viewWillAppear:animated];
6242 [self resizeForKeyboardBounds:CGRectZero];
6243 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6244 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6247 - (void) viewWillDisappear:(BOOL)animated {
6248 [super viewWillDisappear:animated];
6250 [self resizeForKeyboardBounds:CGRectZero];
6251 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6252 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6255 - (void) viewDidAppear:(BOOL)animated {
6256 [super viewDidAppear:animated];
6257 [self deselectWithAnimation:animated];
6260 - (void) didSelectPackage:(Package *)package {
6261 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6262 [view setDelegate:delegate_];
6263 [[self navigationController] pushViewController:view animated:YES];
6266 #if TryIndexedCollation
6267 + (BOOL) hasIndexedCollation {
6268 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6272 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6273 NSInteger count([sections_ count]);
6274 return count == 0 ? 1 : count;
6277 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6278 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6280 return [[sections_ objectAtIndex:section] name];
6283 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6284 if ([sections_ count] == 0)
6286 return [[sections_ objectAtIndex:section] count];
6289 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6290 @synchronized (database_) {
6291 if ([database_ era] != era_)
6294 Section *section([sections_ objectAtIndex:[path section]]);
6295 NSInteger row([path row]);
6296 Package *package([packages_ objectAtIndex:([section row] + row)]);
6297 return [[package retain] autorelease];
6300 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6301 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6303 cell = [[[PackageCell alloc] init] autorelease];
6304 [cell setPackage:[self packageAtIndexPath:path]];
6308 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6309 Package *package([self packageAtIndexPath:path]);
6310 package = [database_ packageWithName:[package id]];
6311 [self didSelectPackage:package];
6314 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6315 // XXX: is 20 the most optimal number here?
6316 return [packages_ count] > 20 ? index_ : nil;
6319 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6320 #if TryIndexedCollation
6321 if ([[self class] hasIndexedCollation]) {
6322 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6329 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6330 if ((self = [super init]) != nil) {
6331 database_ = database;
6332 title_ = [title copy];
6333 [[self navigationItem] setTitle:title_];
6335 #if TryIndexedCollation
6336 if ([[self class] hasIndexedCollation])
6337 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6340 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6342 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6344 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6345 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6347 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6348 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6349 [list_ setRowHeight:73];
6350 [[self view] addSubview:list_];
6352 [list_ setDataSource:self];
6353 [list_ setDelegate:self];
6357 - (void) setDelegate:(id)delegate {
6358 delegate_ = delegate;
6361 - (bool) hasPackage:(Package *)package {
6365 - (void) reloadData {
6368 era_ = [database_ era];
6369 NSArray *packages = [database_ packages];
6371 [packages_ removeAllObjects];
6372 [sections_ removeAllObjects];
6374 _profile(PackageTable$reloadData$Filter)
6375 for (Package *package in packages)
6376 if ([self hasPackage:package])
6377 [packages_ addObject:package];
6380 [indices_ removeAllObjects];
6382 Section *section = nil;
6384 #if TryIndexedCollation
6385 if ([[self class] hasIndexedCollation]) {
6386 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6387 NSArray *titles = [collation sectionIndexTitles];
6390 _profile(PackageTable$reloadData$Section)
6391 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6395 _profile(PackageTable$reloadData$Section$Package)
6396 package = [packages_ objectAtIndex:offset];
6397 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6400 while (secidx < index) {
6403 _profile(PackageTable$reloadData$Section$Allocate)
6404 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6407 _profile(PackageTable$reloadData$Section$Add)
6408 [sections_ addObject:section];
6412 [section addToCount];
6418 [index_ removeAllObjects];
6420 _profile(PackageTable$reloadData$Section)
6421 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6425 _profile(PackageTable$reloadData$Section$Package)
6426 package = [packages_ objectAtIndex:offset];
6427 index = [package index];
6430 if (section == nil || [section index] != index) {
6431 _profile(PackageTable$reloadData$Section$Allocate)
6432 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6435 [index_ addObject:[section name]];
6436 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6438 _profile(PackageTable$reloadData$Section$Add)
6439 [sections_ addObject:section];
6443 [section addToCount];
6448 _profile(PackageTable$reloadData$List)
6453 - (void) resetCursor {
6454 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6459 /* Filtered Package List Controller {{{ */
6460 @interface FilteredPackageListController : PackageListController {
6466 - (void) setObject:(id)object;
6467 - (void) setObject:(id)object forFilter:(SEL)filter;
6469 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6473 @implementation FilteredPackageListController
6481 - (void) setFilter:(SEL)filter {
6484 /* XXX: this is an unsafe optimization of doomy hell */
6485 Method method(class_getInstanceMethod([Package class], filter));
6486 _assert(method != NULL);
6487 imp_ = method_getImplementation(method);
6488 _assert(imp_ != NULL);
6491 - (void) setObject:(id)object {
6497 object_ = [object retain];
6500 - (void) setObject:(id)object forFilter:(SEL)filter {
6501 [self setFilter:filter];
6502 [self setObject:object];
6505 - (bool) hasPackage:(Package *)package {
6506 _profile(FilteredPackageTable$hasPackage)
6507 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6511 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6512 if ((self = [super initWithDatabase:database title:title]) != nil) {
6513 [self setFilter:filter];
6514 [self setObject:object];
6521 /* Home Controller {{{ */
6522 @interface HomeController : CYBrowserController {
6527 @implementation HomeController
6530 if ((self = [super init]) != nil) {
6531 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6535 - (NSURL *) navigationURL {
6536 return [NSURL URLWithString:@"cydia://home"];
6539 - (void) aboutButtonClicked {
6540 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6542 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6543 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6544 [alert setCancelButtonIndex:0];
6547 @"Copyright (C) 2008-2011\n"
6548 "Jay Freeman (saurik)\n"
6549 "saurik@saurik.com\n"
6550 "http://www.saurik.com/"
6556 - (void) viewDidLoad {
6557 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6558 initWithTitle:UCLocalize("ABOUT")
6559 style:UIBarButtonItemStylePlain
6561 action:@selector(aboutButtonClicked)
6567 /* Manage Controller {{{ */
6568 @interface ManageController : CYBrowserController {
6571 - (void) queueStatusDidChange;
6575 @implementation ManageController
6578 if ((self = [super init]) != nil) {
6579 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6583 - (NSURL *) navigationURL {
6584 return [NSURL URLWithString:@"cydia://manage"];
6587 - (void) viewDidLoad {
6588 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6589 initWithTitle:UCLocalize("SETTINGS")
6590 style:UIBarButtonItemStylePlain
6592 action:@selector(settingsButtonClicked)
6595 [self queueStatusDidChange];
6598 - (void) settingsButtonClicked {
6599 [delegate_ showSettings];
6603 - (void) queueButtonClicked {
6607 - (void) applyLoadingTitle {
6608 // Disable "Loading" title.
6611 - (void) applyRightButton {
6612 // Disable right button.
6616 - (void) queueStatusDidChange {
6618 if (!IsWildcat_ && Queuing_) {
6619 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6620 initWithTitle:UCLocalize("QUEUE")
6621 style:UIBarButtonItemStyleDone
6623 action:@selector(queueButtonClicked)
6626 [[self navigationItem] setRightBarButtonItem:nil];
6631 - (bool) isLoading {
6632 // Never show as loading.
6639 /* Refresh Bar {{{ */
6640 @interface RefreshBar : UINavigationBar {
6641 UIProgressIndicator *indicator_;
6642 UITextLabel *prompt_;
6643 UIProgressBar *progress_;
6644 UINavigationButton *cancel_;
6649 @implementation RefreshBar
6652 [indicator_ release];
6654 [progress_ release];
6659 - (void) positionViews {
6660 CGRect frame = [cancel_ frame];
6661 frame.size = [cancel_ sizeThatFits:frame.size];
6662 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6663 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6664 [cancel_ setFrame:frame];
6666 CGSize prgsize = {75, 100};
6668 [self frame].size.width - prgsize.width - 10,
6669 ([self frame].size.height - prgsize.height) / 2
6671 [progress_ setFrame:prgrect];
6673 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6674 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6675 CGRect indrect = {{indoffset, indoffset}, indsize};
6676 [indicator_ setFrame:indrect];
6678 CGSize prmsize = {215, indsize.height + 4};
6680 indoffset * 2 + indsize.width,
6681 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6683 [prompt_ setFrame:prmrect];
6686 - (void) setFrame:(CGRect)frame {
6687 [super setFrame:frame];
6688 [self positionViews];
6691 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6692 if ((self = [super initWithFrame:frame]) != nil) {
6693 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6695 [self setBarStyle:UIBarStyleBlack];
6697 UIBarStyle barstyle([self _barStyle:NO]);
6698 bool ugly(barstyle == UIBarStyleDefault);
6700 UIProgressIndicatorStyle style = ugly ?
6701 UIProgressIndicatorStyleMediumBrown :
6702 UIProgressIndicatorStyleMediumWhite;
6704 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6705 [indicator_ setStyle:style];
6706 [indicator_ startAnimation];
6707 [self addSubview:indicator_];
6709 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6710 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6711 [prompt_ setBackgroundColor:[UIColor clearColor]];
6712 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6713 [self addSubview:prompt_];
6715 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6716 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6717 [progress_ setStyle:0];
6718 [self addSubview:progress_];
6720 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6721 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6722 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6723 [cancel_ setBarStyle:barstyle];
6725 [self positionViews];
6729 - (void) setCancellable:(bool)cancellable {
6731 [self addSubview:cancel_];
6733 [cancel_ removeFromSuperview];
6737 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6738 [progress_ setProgress:0];
6742 [self setCancellable:NO];
6745 - (void) setPrompt:(NSString *)prompt {
6746 [prompt_ setText:prompt];
6749 - (void) setProgress:(float)progress {
6750 [progress_ setProgress:progress];
6756 /* Cydia Navigation Controller Interface {{{ */
6757 @interface UINavigationController (Cydia)
6759 - (NSArray *) navigationURLCollection;
6760 - (void) unloadData;
6765 /* Cydia Tab Bar Controller {{{ */
6766 @interface CYTabBarController : UITabBarController <
6767 UITabBarControllerDelegate,
6770 _transient Database *database_;
6771 RefreshBar *refreshbar_;
6775 // XXX: ok, "updatedelegate_"?...
6776 _transient NSObject<CydiaDelegate> *updatedelegate_;
6779 UIViewController *remembered_;
6780 _transient UIViewController *transient_;
6783 - (NSArray *) navigationURLCollection;
6784 - (void) dropBar:(BOOL)animated;
6785 - (void) beginUpdate;
6786 - (void) raiseBar:(BOOL)animated;
6788 - (void) unloadData;
6792 @implementation CYTabBarController
6794 - (void) setUnselectedViewController:(UIViewController *)transient {
6795 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6796 if (transient != nil) {
6797 if (transient_ == nil)
6798 remembered_ = [[controllers objectAtIndex:0] retain];
6799 transient_ = transient;
6800 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6801 [controllers replaceObjectAtIndex:0 withObject:transient_];
6802 [self setSelectedIndex:0];
6803 [self setViewControllers:controllers];
6804 [self concealTabBarSelection];
6805 } else if (remembered_ != nil) {
6806 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6807 transient_ = transient;
6808 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6809 [remembered_ release];
6811 [self setViewControllers:controllers];
6812 [self revealTabBarSelection];
6816 - (UIViewController *) unselectedViewController {
6820 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6821 if ([self unselectedViewController])
6822 [self setUnselectedViewController:nil];
6825 - (NSArray *) navigationURLCollection {
6826 NSMutableArray *items([NSMutableArray array]);
6828 // XXX: Should this deal with transient view controllers?
6829 for (id navigation in [self viewControllers]) {
6830 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6832 [items addObject:stack];
6838 - (void) unloadData {
6839 UIViewController *selected([self selectedViewController]);
6840 for (UINavigationController *controller in [self viewControllers])
6841 [controller unloadData];
6843 [selected reloadData];
6845 if (UIViewController *unselected = [self unselectedViewController])
6846 [unselected reloadData];
6852 [refreshbar_ release];
6853 [[NSNotificationCenter defaultCenter] removeObserver:self];
6858 - (id) initWithDatabase:(Database *)database {
6859 if ((self = [super init]) != nil) {
6860 database_ = database;
6861 [self setDelegate:self];
6863 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6864 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6866 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6870 - (void) setUpdate:(NSDate *)date {
6874 - (void) beginUpdate {
6875 [refreshbar_ start];
6878 [updatedelegate_ retainNetworkActivityIndicator];
6882 detachNewThreadSelector:@selector(performUpdate)
6888 - (void) performUpdate { _pooled
6890 status.setDelegate(self);
6891 [database_ updateWithStatus:status];
6894 performSelectorOnMainThread:@selector(completeUpdate)
6900 - (void) stopUpdateWithSelector:(SEL)selector {
6902 [updatedelegate_ releaseNetworkActivityIndicator];
6904 [self raiseBar:YES];
6907 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6910 - (void) completeUpdate {
6913 [self stopUpdateWithSelector:@selector(reloadData)];
6916 - (void) cancelUpdate {
6917 [self stopUpdateWithSelector:@selector(updateData)];
6920 - (void) cancelPressed {
6921 [self cancelUpdate];
6928 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6929 [refreshbar_ setPrompt:[event compoundMessage]];
6932 - (bool) isProgressCancelled {
6936 - (void) setProgressCancellable:(NSNumber *)cancellable {
6937 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6940 - (void) setProgressPercent:(NSNumber *)percent {
6941 [refreshbar_ setProgress:[percent floatValue]];
6944 - (void) setProgressStatus:(NSDictionary *)status {
6946 [self setProgressPercent:[status objectForKey:@"Percent"]];
6949 - (void) setUpdateDelegate:(id)delegate {
6950 updatedelegate_ = delegate;
6953 - (CGFloat) statusBarHeight {
6954 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6955 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6957 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6961 - (UIView *) transitionView {
6962 if ([self respondsToSelector:@selector(_transitionView)])
6963 return [self _transitionView];
6965 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6968 - (void) dropBar:(BOOL)animated {
6973 UIView *transition([self transitionView]);
6974 [[self view] addSubview:refreshbar_];
6976 CGRect barframe([refreshbar_ frame]);
6978 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6979 barframe.origin.y = [self statusBarHeight];
6981 barframe.origin.y = 0;
6983 [refreshbar_ setFrame:barframe];
6986 [UIView beginAnimations:nil context:NULL];
6988 CGRect viewframe = [transition frame];
6989 viewframe.origin.y += barframe.size.height;
6990 viewframe.size.height -= barframe.size.height;
6991 [transition setFrame:viewframe];
6994 [UIView commitAnimations];
6996 // Ensure bar has the proper width for our view, it might have changed
6997 barframe.size.width = viewframe.size.width;
6998 [refreshbar_ setFrame:barframe];
7000 // XXX: fix Apple's layout bug
7001 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7004 - (void) raiseBar:(BOOL)animated {
7009 UIView *transition([self transitionView]);
7010 [refreshbar_ removeFromSuperview];
7012 CGRect barframe([refreshbar_ frame]);
7015 [UIView beginAnimations:nil context:NULL];
7017 CGRect viewframe = [transition frame];
7018 viewframe.origin.y -= barframe.size.height;
7019 viewframe.size.height += barframe.size.height;
7020 [transition setFrame:viewframe];
7023 [UIView commitAnimations];
7025 // XXX: fix Apple's layout bug
7026 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7030 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7031 // XXX: fix Apple's layout bug
7032 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7036 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7037 bool dropped(dropped_);
7042 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7047 // XXX: fix Apple's layout bug
7048 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7051 - (void) statusBarFrameChanged:(NSNotification *)notification {
7061 /* Cydia Navigation Controller Implementation {{{ */
7062 @implementation UINavigationController (Cydia)
7064 - (NSArray *) navigationURLCollection {
7065 NSMutableArray *stack([NSMutableArray array]);
7067 for (CYViewController *controller in [self viewControllers]) {
7068 NSString *url = [[controller navigationURL] absoluteString];
7070 [stack addObject:url];
7076 - (void) reloadData {
7079 if (UIViewController *visible = [self visibleViewController])
7080 [visible reloadData];
7083 - (void) unloadData {
7084 for (CYViewController *page in [self viewControllers])
7093 /* Cydia:// Protocol {{{ */
7094 @interface CydiaURLProtocol : NSURLProtocol {
7099 @implementation CydiaURLProtocol
7101 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7102 NSURL *url([request URL]);
7106 NSString *scheme([[url scheme] lowercaseString]);
7107 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7109 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7115 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7119 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7120 id<NSURLProtocolClient> client([self client]);
7122 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7124 NSData *data(UIImagePNGRepresentation(icon));
7126 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7127 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7128 [client URLProtocol:self didLoadData:data];
7129 [client URLProtocolDidFinishLoading:self];
7133 - (void) startLoading {
7134 id<NSURLProtocolClient> client([self client]);
7135 NSURLRequest *request([self request]);
7137 NSURL *url([request URL]);
7138 NSString *href([url absoluteString]);
7139 NSString *scheme([[url scheme] lowercaseString]);
7143 if ([scheme isEqualToString:@"cydia"])
7144 path = [href substringFromIndex:8];
7145 else if ([scheme isEqualToString:@"about"])
7146 path = [href substringFromIndex:12];
7147 else _assert(false);
7149 NSRange slash([path rangeOfString:@"/"]);
7152 if (slash.location == NSNotFound) {
7156 command = [path substringToIndex:slash.location];
7157 path = [path substringFromIndex:(slash.location + 1)];
7160 Database *database([Database sharedInstance]);
7162 if ([command isEqualToString:@"package-icon"]) {
7165 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7166 Package *package([database packageWithName:path]);
7169 UIImage *icon([package icon]);
7170 [self _returnPNGWithImage:icon forRequest:request];
7171 } else if ([command isEqualToString:@"source-icon"]) {
7174 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7175 NSString *source(Simplify(path));
7176 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7178 icon = [UIImage applicationImageNamed:@"unknown.png"];
7179 [self _returnPNGWithImage:icon forRequest:request];
7180 } else if ([command isEqualToString:@"uikit-image"]) {
7183 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7184 UIImage *icon(_UIImageWithName(path));
7185 [self _returnPNGWithImage:icon forRequest:request];
7186 } else if ([command isEqualToString:@"section-icon"]) {
7189 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7190 NSString *section(Simplify(path));
7191 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7193 icon = [UIImage applicationImageNamed:@"unknown.png"];
7194 [self _returnPNGWithImage:icon forRequest:request];
7196 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7200 - (void) stopLoading {
7206 /* Section Controller {{{ */
7207 @interface SectionController : FilteredPackageListController {
7208 _H<NSString> section_;
7211 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7215 @implementation SectionController
7217 - (NSURL *) navigationURL {
7218 NSString *name = section_;
7222 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7225 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7228 title = UCLocalize("ALL_PACKAGES");
7229 else if (![name isEqual:@""])
7230 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7232 title = UCLocalize("NO_SECTION");
7234 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7241 /* Sections Controller {{{ */
7242 @interface SectionsController : CYViewController <
7243 UITableViewDataSource,
7246 _transient Database *database_;
7247 NSMutableArray *sections_;
7248 NSMutableArray *filtered_;
7252 - (id) initWithDatabase:(Database *)database;
7253 - (void) editButtonClicked;
7257 @implementation SectionsController
7260 [self releaseSubviews];
7261 [sections_ release];
7262 [filtered_ release];
7267 - (NSURL *) navigationURL {
7268 return [NSURL URLWithString:@"cydia://sections"];
7271 - (void) updateNavigationItem {
7272 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7273 if ([sections_ count] == 0) {
7274 [[self navigationItem] setRightBarButtonItem:nil];
7276 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7277 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7279 action:@selector(editButtonClicked)
7280 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7284 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7285 [super setEditing:editing animated:animated];
7290 [delegate_ updateData];
7292 [self updateNavigationItem];
7295 - (void) viewDidAppear:(BOOL)animated {
7296 [super viewDidAppear:animated];
7297 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7300 - (void) viewWillDisappear:(BOOL)animated {
7301 [super viewWillDisappear:animated];
7302 if ([self isEditing]) [self setEditing:NO];
7305 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7306 Section *section = nil;
7307 int index = [indexPath row];
7308 if (![self isEditing]) {
7311 section = [filtered_ objectAtIndex:index];
7313 section = [sections_ objectAtIndex:index];
7318 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7319 if ([self isEditing])
7320 return [sections_ count];
7322 return [filtered_ count] + 1;
7325 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7329 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7330 static NSString *reuseIdentifier = @"SectionCell";
7332 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7334 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7336 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7341 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7342 if ([self isEditing])
7345 Section *section = [self sectionAtIndexPath:indexPath];
7347 SectionController *controller = [[[SectionController alloc]
7348 initWithDatabase:database_
7349 section:[section name]
7351 [controller setDelegate:delegate_];
7353 [[self navigationController] pushViewController:controller animated:YES];
7357 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7359 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7360 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7361 [list_ setRowHeight:45.0f];
7362 [list_ setDataSource:self];
7363 [list_ setDelegate:self];
7364 [[self view] addSubview:list_];
7367 - (void) viewDidLoad {
7368 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7371 - (void) releaseSubviews {
7376 - (id) initWithDatabase:(Database *)database {
7377 if ((self = [super init]) != nil) {
7378 database_ = database;
7380 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7381 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7385 - (void) reloadData {
7388 NSArray *packages = [database_ packages];
7390 [sections_ removeAllObjects];
7391 [filtered_ removeAllObjects];
7393 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7396 for (Package *package in packages) {
7397 NSString *name([package section]);
7398 NSString *key(name == nil ? @"" : name);
7402 _profile(SectionsView$reloadData$Section)
7403 section = [sections objectForKey:key];
7404 if (section == nil) {
7405 _profile(SectionsView$reloadData$Section$Allocate)
7406 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7407 [sections setObject:section forKey:key];
7412 [section addToCount];
7414 _profile(SectionsView$reloadData$Filter)
7415 if (![package valid] || ![package visible])
7423 [sections_ addObjectsFromArray:[sections allValues]];
7425 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7427 for (Section *section in sections_) {
7428 size_t count([section row]);
7432 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7433 [section setCount:count];
7434 [filtered_ addObject:section];
7437 [self updateNavigationItem];
7442 - (void) editButtonClicked {
7443 [self setEditing:![self isEditing] animated:YES];
7449 /* Changes Controller {{{ */
7450 @interface ChangesController : CYViewController <
7451 UITableViewDataSource,
7454 _transient Database *database_;
7456 CFMutableArrayRef packages_;
7457 NSMutableArray *sections_;
7462 - (id) initWithDatabase:(Database *)database;
7466 @implementation ChangesController
7469 [self releaseSubviews];
7470 CFRelease(packages_);
7471 [sections_ release];
7476 - (NSURL *) navigationURL {
7477 return [NSURL URLWithString:@"cydia://changes"];
7480 - (void) viewDidAppear:(BOOL)animated {
7481 [super viewDidAppear:animated];
7482 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7485 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7486 NSInteger count([sections_ count]);
7487 return count == 0 ? 1 : count;
7490 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7491 if ([sections_ count] == 0)
7493 return [[sections_ objectAtIndex:section] name];
7496 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7497 if ([sections_ count] == 0)
7499 return [[sections_ objectAtIndex:section] count];
7502 - (Package *) packageAtIndex:(NSUInteger)index {
7503 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7506 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7507 @synchronized (database_) {
7508 if ([database_ era] != era_)
7511 NSUInteger sectionIndex([path section]);
7512 if (sectionIndex >= [sections_ count])
7514 Section *section([sections_ objectAtIndex:sectionIndex]);
7515 NSInteger row([path row]);
7516 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7519 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7520 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7522 cell = [[[PackageCell alloc] init] autorelease];
7523 [cell setPackage:[self packageAtIndexPath:path]];
7527 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7528 Package *package([self packageAtIndexPath:path]);
7529 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7530 [view setDelegate:delegate_];
7531 [[self navigationController] pushViewController:view animated:YES];
7535 - (void) refreshButtonClicked {
7536 [delegate_ beginUpdate];
7537 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7540 - (void) upgradeButtonClicked {
7541 [delegate_ distUpgrade];
7545 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7547 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7548 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7549 [list_ setRowHeight:73];
7550 [list_ setDataSource:self];
7551 [list_ setDelegate:self];
7552 [[self view] addSubview:list_];
7555 - (void) viewDidLoad {
7556 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7559 - (void) releaseSubviews {
7564 - (id) initWithDatabase:(Database *)database {
7565 if ((self = [super init]) != nil) {
7566 database_ = database;
7568 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7569 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7573 // this mostly works because reloadData (below) is @synchronized (database_)
7574 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7575 - (void) _reloadPackages:(NSArray *)packages {
7576 CFRelease(packages_);
7577 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7580 _profile(ChangesController$_reloadPackages$Filter)
7581 for (Package *package in packages)
7582 if ([package upgradableAndEssential:YES] || [package visible])
7583 CFArrayAppendValue(packages_, package);
7586 _profile(ChangesController$_reloadPackages$radixSort)
7587 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7592 - (void) _reloadData {
7593 @synchronized (database_) {
7594 era_ = [database_ era];
7595 NSArray *packages = [database_ packages];
7597 [sections_ removeAllObjects];
7600 UIProgressHUD *hud([delegate_ addProgressHUD]);
7601 [hud setText:UCLocalize("LOADING")];
7602 //NSLog(@"HUD:%@::%@", delegate_, hud);
7603 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7604 [delegate_ removeProgressHUD:hud];
7606 [self _reloadPackages:packages];
7609 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7610 Section *ignored = nil;
7611 Section *section = nil;
7615 bool unseens = false;
7617 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7619 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7620 Package *package = [self packageAtIndex:offset];
7622 BOOL uae = [package upgradableAndEssential:YES];
7626 time_t seen([package seen]);
7628 if (section == nil || last != seen) {
7632 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7635 _profile(ChangesController$reloadData$Allocate)
7636 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7637 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7638 [sections_ addObject:section];
7642 [section addToCount];
7643 } else if ([package ignored]) {
7644 if (ignored == nil) {
7645 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7647 [ignored addToCount];
7650 [upgradable addToCount];
7655 CFRelease(formatter);
7658 Section *last = [sections_ lastObject];
7659 size_t count = [last count];
7660 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7661 [sections_ removeLastObject];
7664 if ([ignored count] != 0)
7665 [sections_ insertObject:ignored atIndex:0];
7667 [sections_ insertObject:upgradable atIndex:0];
7672 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7673 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7674 style:UIBarButtonItemStylePlain
7676 action:@selector(upgradeButtonClicked)
7679 if (![delegate_ updating])
7680 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7681 initWithTitle:UCLocalize("REFRESH")
7682 style:UIBarButtonItemStylePlain
7684 action:@selector(refreshButtonClicked)
7690 - (void) reloadData {
7692 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7697 /* Search Controller {{{ */
7698 @interface SearchController : FilteredPackageListController <
7701 _H<UISearchBar> search_;
7705 - (id) initWithDatabase:(Database *)database;
7706 - (void) setSearchTerm:(NSString *)term;
7707 - (void) reloadData;
7711 @implementation SearchController
7714 [search_ setDelegate:nil];
7718 - (NSURL *) navigationURL {
7719 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7720 return [NSURL URLWithString:@"cydia://search"];
7722 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7725 - (void) setSearchTerm:(NSString *)searchTerm {
7726 [search_ setText:searchTerm];
7730 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7731 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7732 [search_ resignFirstResponder];
7736 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7737 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7741 - (id) initWithDatabase:(Database *)database {
7742 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7743 search_ = [[[UISearchBar alloc] init] autorelease];
7744 [search_ setDelegate:self];
7748 - (void) viewDidAppear:(BOOL)animated {
7749 [super viewDidAppear:animated];
7751 if (!searchloaded_) {
7752 searchloaded_ = YES;
7753 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7754 [search_ layoutSubviews];
7755 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7757 UITextField *textField;
7758 if ([search_ respondsToSelector:@selector(searchField)])
7759 textField = [search_ searchField];
7761 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7763 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7764 [textField setEnablesReturnKeyAutomatically:NO];
7765 [[self navigationItem] setTitleView:textField];
7769 - (void) reloadData {
7770 [self setObject:[search_ text]];
7776 - (void) didSelectPackage:(Package *)package {
7777 [search_ resignFirstResponder];
7778 [super didSelectPackage:package];
7783 /* Package Settings Controller {{{ */
7784 @interface PackageSettingsController : CYViewController <
7785 UITableViewDataSource,
7788 _transient Database *database_;
7791 UITableView *table_;
7792 UISwitch *subscribedSwitch_;
7793 UISwitch *ignoredSwitch_;
7794 UITableViewCell *subscribedCell_;
7795 UITableViewCell *ignoredCell_;
7798 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7802 @implementation PackageSettingsController
7805 [self releaseSubviews];
7812 - (NSURL *) navigationURL {
7813 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7816 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7817 if (package_ == nil)
7820 if ([package_ installed] == nil)
7826 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7827 if (package_ == nil)
7830 // both sections contain just one item right now.
7834 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7838 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7840 return UCLocalize("SHOW_ALL_CHANGES_EX");
7842 return UCLocalize("IGNORE_UPGRADES_EX");
7845 - (void) onSubscribed:(id)control {
7846 bool value([control isOn]);
7847 if (package_ == nil)
7849 if ([package_ setSubscribed:value])
7850 [delegate_ updateData];
7853 - (void) _updateIgnored {
7854 const char *package([name_ UTF8String]);
7855 bool on([ignoredSwitch_ isOn]);
7857 pid_t pid(ExecFork());
7859 FILE *dpkg(popen("dpkg --set-selections", "w"));
7860 fwrite(package, strlen(package), 1, dpkg);
7863 fwrite(" hold\n", 6, 1, dpkg);
7865 fwrite(" install\n", 9, 1, dpkg);
7875 int result(waitpid(pid, &status, 0));
7878 _assert(result == pid);
7884 - (void) onIgnored:(id)control {
7885 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7886 [invocation setTarget:self];
7887 [invocation setSelector:@selector(_updateIgnored)];
7889 [delegate_ reloadDataWithInvocation:invocation];
7892 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7893 if (package_ == nil)
7896 switch ([indexPath section]) {
7897 case 0: return subscribedCell_;
7898 case 1: return ignoredCell_;
7907 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7909 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7910 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7911 [table_ setDataSource:self];
7912 [table_ setDelegate:self];
7913 [[self view] addSubview:table_];
7915 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7916 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7917 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7919 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7920 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7921 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7923 subscribedCell_ = [[UITableViewCell alloc] init];
7924 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7925 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7926 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7928 ignoredCell_ = [[UITableViewCell alloc] init];
7929 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7930 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7931 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7934 - (void) viewDidLoad {
7935 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7938 - (void) releaseSubviews {
7939 [ignoredCell_ release];
7942 [subscribedCell_ release];
7943 subscribedCell_ = nil;
7948 [ignoredSwitch_ release];
7949 ignoredSwitch_ = nil;
7951 [subscribedSwitch_ release];
7952 subscribedSwitch_ = nil;
7955 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7956 if ((self = [super init]) != nil) {
7957 database_ = database;
7958 name_ = [package retain];
7962 - (void) reloadData {
7965 if (package_ != nil)
7966 [package_ autorelease];
7967 package_ = [database_ packageWithName:name_];
7969 if (package_ != nil) {
7970 package_ = [package_ retain];
7971 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7972 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7973 } // XXX: what now, G?
7975 [table_ reloadData];
7981 /* Installed Controller {{{ */
7982 @interface InstalledController : FilteredPackageListController {
7986 - (id) initWithDatabase:(Database *)database;
7988 - (void) updateRoleButton;
7989 - (void) queueStatusDidChange;
7993 @implementation InstalledController
7999 - (NSURL *) navigationURL {
8000 return [NSURL URLWithString:@"cydia://installed"];
8003 - (id) initWithDatabase:(Database *)database {
8004 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8005 [self updateRoleButton];
8006 [self queueStatusDidChange];
8011 - (void) queueButtonClicked {
8016 - (void) queueStatusDidChange {
8020 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8021 initWithTitle:UCLocalize("QUEUE")
8022 style:UIBarButtonItemStyleDone
8024 action:@selector(queueButtonClicked)
8027 [[self navigationItem] setLeftBarButtonItem:nil];
8033 - (void) updateRoleButton {
8034 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8035 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8036 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8037 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8039 action:@selector(roleButtonClicked)
8043 - (void) roleButtonClicked {
8044 [self setObject:[NSNumber numberWithBool:expert_]];
8048 [self updateRoleButton];
8054 /* Source Cell {{{ */
8055 @interface SourceCell : CYTableViewCell <
8063 - (void) setSource:(Source *)source;
8067 @implementation SourceCell
8069 - (void) clearSource {
8079 - (void) setSource:(Source *)source {
8083 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
8085 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8086 icon_ = [icon_ retain];
8088 origin_ = [[source name] retain];
8089 label_ = [[source uri] retain];
8091 [content_ setNeedsDisplay];
8099 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8100 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8101 UIView *content([self contentView]);
8102 CGRect bounds([content bounds]);
8104 content_ = [[ContentView alloc] initWithFrame:bounds];
8105 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8106 [content_ setBackgroundColor:[UIColor whiteColor]];
8107 [content addSubview:content_];
8109 [content_ setDelegate:self];
8110 [content_ setOpaque:YES];
8114 - (NSString *) accessibilityLabel {
8118 - (void) drawContentRect:(CGRect)rect {
8119 bool highlighted(highlighted_);
8120 float width(rect.size.width);
8123 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8130 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8134 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8139 /* Source Controller {{{ */
8140 @interface SourceController : FilteredPackageListController {
8141 _transient Source *source_;
8145 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8149 @implementation SourceController
8151 - (NSURL *) navigationURL {
8152 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8155 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8156 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8158 key_ = [[source key] retain];
8162 - (void) reloadData {
8163 source_ = [database_ sourceWithKey:key_];
8165 key_ = [[source_ key] retain];
8166 [self setObject:source_];
8168 [[self navigationItem] setTitle:[source_ label]];
8175 /* Sources Controller {{{ */
8176 @interface SourcesController : CYViewController <
8177 UITableViewDataSource,
8180 _transient Database *database_;
8182 NSMutableArray *sources_;
8186 UIProgressHUD *hud_;
8189 //NSURLConnection *installer_;
8190 NSURLConnection *trivial_;
8191 NSURLConnection *trivial_bz2_;
8192 NSURLConnection *trivial_gz_;
8193 //NSURLConnection *automatic_;
8198 - (id) initWithDatabase:(Database *)database;
8199 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8203 @implementation SourcesController
8205 - (void) _releaseConnection:(NSURLConnection *)connection {
8206 if (connection != nil) {
8207 [connection cancel];
8208 //[connection setDelegate:nil];
8209 [connection release];
8214 [self releaseSubviews];
8220 //[self _releaseConnection:installer_];
8221 [self _releaseConnection:trivial_];
8222 [self _releaseConnection:trivial_gz_];
8223 [self _releaseConnection:trivial_bz2_];
8224 //[self _releaseConnection:automatic_];
8230 - (NSURL *) navigationURL {
8231 return [NSURL URLWithString:@"cydia://sources"];
8234 - (void) viewDidAppear:(BOOL)animated {
8235 [super viewDidAppear:animated];
8236 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8239 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8240 return offset_ == 0 ? 1 : 2;
8243 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8244 switch (section + (offset_ == 0 ? 1 : 0)) {
8245 case 0: return UCLocalize("ENTERED_BY_USER");
8246 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8252 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8253 int count = [sources_ count];
8255 case 0: return (offset_ == 0 ? count : offset_);
8256 case 1: return count - offset_;
8262 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8264 switch (indexPath.section) {
8265 case 0: idx = indexPath.row; break;
8266 case 1: idx = indexPath.row + offset_; break;
8270 return [sources_ objectAtIndex:idx];
8273 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8274 static NSString *cellIdentifier = @"SourceCell";
8276 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8277 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8278 [cell setSource:[self sourceAtIndexPath:indexPath]];
8279 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8284 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8285 Source *source = [self sourceAtIndexPath:indexPath];
8287 SourceController *controller = [[[SourceController alloc]
8288 initWithDatabase:database_
8292 [controller setDelegate:delegate_];
8294 [[self navigationController] pushViewController:controller animated:YES];
8297 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8298 Source *source = [self sourceAtIndexPath:indexPath];
8299 return [source record] != nil;
8302 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8303 Source *source = [self sourceAtIndexPath:indexPath];
8304 [Sources_ removeObjectForKey:[source key]];
8305 [delegate_ syncData];
8309 [delegate_ addTrivialSource:href_];
8310 [delegate_ syncData];
8313 - (NSString *) getWarning {
8314 NSString *href(href_);
8315 NSRange colon([href rangeOfString:@"://"]);
8316 if (colon.location != NSNotFound)
8317 href = [href substringFromIndex:(colon.location + 3)];
8318 href = [href stringByAddingPercentEscapes];
8319 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8320 href = [href stringByCachingURLWithCurrentCDN];
8322 NSURL *url([NSURL URLWithString:href]);
8324 NSStringEncoding encoding;
8325 NSError *error(nil);
8327 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8328 return [warning length] == 0 ? nil : warning;
8332 - (void) _endConnection:(NSURLConnection *)connection {
8333 // XXX: the memory management in this method is horribly awkward
8335 NSURLConnection **field = NULL;
8336 if (connection == trivial_)
8338 else if (connection == trivial_bz2_)
8339 field = &trivial_bz2_;
8340 else if (connection == trivial_gz_)
8341 field = &trivial_gz_;
8342 _assert(field != NULL);
8343 [connection release];
8348 trivial_bz2_ == nil &&
8354 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8357 UIAlertView *alert = [[[UIAlertView alloc]
8358 initWithTitle:UCLocalize("SOURCE_WARNING")
8361 cancelButtonTitle:UCLocalize("CANCEL")
8363 UCLocalize("ADD_ANYWAY"),
8367 [alert setContext:@"warning"];
8368 [alert setNumberOfRows:1];
8372 } else if (error_ != nil) {
8373 UIAlertView *alert = [[[UIAlertView alloc]
8374 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8375 message:[error_ localizedDescription]
8377 cancelButtonTitle:UCLocalize("OK")
8378 otherButtonTitles:nil
8381 [alert setContext:@"urlerror"];
8384 UIAlertView *alert = [[[UIAlertView alloc]
8385 initWithTitle:UCLocalize("NOT_REPOSITORY")
8386 message:UCLocalize("NOT_REPOSITORY_EX")
8388 cancelButtonTitle:UCLocalize("OK")
8389 otherButtonTitles:nil
8392 [alert setContext:@"trivial"];
8396 [delegate_ releaseNetworkActivityIndicator];
8398 [delegate_ removeProgressHUD:hud_];
8407 if (error_ != nil) {
8414 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8415 switch ([response statusCode]) {
8421 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8422 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8424 error_ = [error retain];
8425 [self _endConnection:connection];
8428 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8429 [self _endConnection:connection];
8432 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8433 NSMutableURLRequest *request = [NSMutableURLRequest
8434 requestWithURL:[NSURL URLWithString:href]
8435 cachePolicy:NSURLRequestUseProtocolCachePolicy
8436 timeoutInterval:120.0
8439 [request setHTTPMethod:method];
8441 if (Machine_ != NULL)
8442 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8443 if (UniqueID_ != nil)
8444 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8446 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8449 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8450 NSString *context([alert context]);
8452 if ([context isEqualToString:@"source"]) {
8455 NSString *href = [[alert textField] text];
8457 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8459 if (![href hasSuffix:@"/"])
8460 href_ = [href stringByAppendingString:@"/"];
8463 href_ = [href_ retain];
8465 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8466 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8467 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8468 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8472 // XXX: this is stupid
8473 hud_ = [[delegate_ addProgressHUD] retain];
8474 [hud_ setText:UCLocalize("VERIFYING_URL")];
8475 [delegate_ retainNetworkActivityIndicator];
8484 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8485 } else if ([context isEqualToString:@"trivial"])
8486 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8487 else if ([context isEqualToString:@"urlerror"])
8488 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8489 else if ([context isEqualToString:@"warning"]) {
8504 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8509 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8511 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8512 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8513 [list_ setRowHeight:56];
8514 [list_ setDataSource:self];
8515 [list_ setDelegate:self];
8516 [[self view] addSubview:list_];
8519 - (void) viewDidLoad {
8520 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8521 [self updateButtonsForEditingStatus:NO animated:NO];
8524 - (void) releaseSubviews {
8529 - (id) initWithDatabase:(Database *)database {
8530 if ((self = [super init]) != nil) {
8531 database_ = database;
8532 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8536 - (void) reloadData {
8540 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8543 [sources_ removeAllObjects];
8544 [sources_ addObjectsFromArray:[database_ sources]];
8546 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8549 int count([sources_ count]);
8551 for (int i = 0; i != count; i++) {
8552 if ([[sources_ objectAtIndex:i] record] == nil)
8557 [list_ setEditing:NO];
8558 [self updateButtonsForEditingStatus:NO animated:NO];
8562 - (void) showAddSourcePrompt {
8563 UIAlertView *alert = [[[UIAlertView alloc]
8564 initWithTitle:UCLocalize("ENTER_APT_URL")
8567 cancelButtonTitle:UCLocalize("CANCEL")
8569 UCLocalize("ADD_SOURCE"),
8573 [alert setContext:@"source"];
8574 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8576 [alert setNumberOfRows:1];
8577 [alert addTextFieldWithValue:@"http://" label:@""];
8579 UITextInputTraits *traits = [[alert textField] textInputTraits];
8580 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8581 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8582 [traits setKeyboardType:UIKeyboardTypeURL];
8583 // XXX: UIReturnKeyDone
8584 [traits setReturnKeyType:UIReturnKeyNext];
8589 - (void) addButtonClicked {
8590 [self showAddSourcePrompt];
8593 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8594 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8595 initWithTitle:UCLocalize("ADD")
8596 style:UIBarButtonItemStylePlain
8598 action:@selector(addButtonClicked)
8599 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8601 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8602 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8603 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8605 action:@selector(editButtonClicked)
8606 ] autorelease] animated:animated];
8608 if (IsWildcat_ && !editing)
8609 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8610 initWithTitle:UCLocalize("SETTINGS")
8611 style:UIBarButtonItemStylePlain
8613 action:@selector(settingsButtonClicked)
8617 - (void) settingsButtonClicked {
8618 [delegate_ showSettings];
8621 - (void) editButtonClicked {
8622 [list_ setEditing:![list_ isEditing] animated:YES];
8624 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8630 /* Settings Controller {{{ */
8631 @interface SettingsController : CYViewController <
8632 UITableViewDataSource,
8635 _transient Database *database_;
8636 // XXX: ok, "roledelegate_"?...
8637 _transient id roledelegate_;
8638 UITableView *table_;
8639 UISegmentedControl *segment_;
8643 - (void) showDoneButton;
8644 - (void) resizeSegmentedControl;
8648 @implementation SettingsController
8651 [self releaseSubviews];
8657 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8659 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8660 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8661 [table_ setDelegate:self];
8662 [table_ setDataSource:self];
8663 [[self view] addSubview:table_];
8665 NSArray *items = [NSArray arrayWithObjects:
8667 UCLocalize("HACKER"),
8668 UCLocalize("DEVELOPER"),
8670 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8671 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8672 [container_ addSubview:segment_];
8675 - (void) viewDidLoad {
8676 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8679 if ([Role_ isEqualToString:@"User"]) index = 0;
8680 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8681 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8683 [segment_ setSelectedSegmentIndex:index];
8684 [self showDoneButton];
8687 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8688 [self resizeSegmentedControl];
8691 - (void) releaseSubviews {
8698 [container_ release];
8702 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8703 if ((self = [super init]) != nil) {
8704 database_ = database;
8705 roledelegate_ = delegate;
8709 - (void) resizeSegmentedControl {
8710 CGFloat width = [[self view] frame].size.width;
8711 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8714 - (void) viewWillAppear:(BOOL)animated {
8715 [super viewWillAppear:animated];
8717 [self resizeSegmentedControl];
8720 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8721 [self resizeSegmentedControl];
8724 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8725 [self resizeSegmentedControl];
8729 NSString *role(nil);
8731 switch ([segment_ selectedSegmentIndex]) {
8732 case 0: role = @"User"; break;
8733 case 1: role = @"Hacker"; break;
8734 case 2: role = @"Developer"; break;
8739 if (![role isEqualToString:Role_]) {
8740 bool rolling(Role_ == nil);
8743 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8747 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8751 [roledelegate_ loadData];
8753 [roledelegate_ updateData];
8757 - (void) segmentChanged:(UISegmentedControl *)control {
8758 [self showDoneButton];
8761 - (void) saveAndClose {
8764 [[self navigationItem] setRightBarButtonItem:nil];
8765 [[self navigationController] dismissModalViewControllerAnimated:YES];
8768 - (void) doneButtonClicked {
8769 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8770 [spinner startAnimating];
8771 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8772 [[self navigationItem] setRightBarButtonItem:spinItem];
8774 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8777 - (void) showDoneButton {
8778 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8779 initWithTitle:UCLocalize("DONE")
8780 style:UIBarButtonItemStyleDone
8782 action:@selector(doneButtonClicked)
8783 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8786 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8787 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8791 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8795 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8796 return nil; // This method is required by the protocol.
8799 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8801 return UCLocalize("ROLE_EX");
8803 return [NSString stringWithFormat:
8804 @"%@: %@\n%@: %@\n%@: %@",
8805 UCLocalize("USER"), UCLocalize("USER_EX"),
8806 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8807 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8812 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8813 return section == 3 ? 44.0f : 0;
8816 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8817 return section == 3 ? container_ : nil;
8820 - (void) reloadData {
8823 [table_ reloadData];
8828 /* Stash Controller {{{ */
8829 @interface StashController : CYViewController {
8830 UIActivityIndicatorView *spinner_;
8837 @implementation StashController
8840 [self releaseSubviews];
8846 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8847 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8849 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8850 CGRect spinrect = [spinner_ frame];
8851 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8852 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8853 [spinner_ setFrame:spinrect];
8854 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8855 [[self view] addSubview:spinner_];
8856 [spinner_ startAnimating];
8859 captrect.size.width = [[self view] frame].size.width;
8860 captrect.size.height = 40.0f;
8861 captrect.origin.x = 0;
8862 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8863 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8864 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8865 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8866 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8867 [caption_ setTextColor:[UIColor whiteColor]];
8868 [caption_ setBackgroundColor:[UIColor clearColor]];
8869 [caption_ setShadowColor:[UIColor blackColor]];
8870 [caption_ setTextAlignment:UITextAlignmentCenter];
8871 [[self view] addSubview:caption_];
8874 statusrect.size.width = [[self view] frame].size.width;
8875 statusrect.size.height = 30.0f;
8876 statusrect.origin.x = 0;
8877 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8878 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8879 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8880 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8881 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8882 [status_ setTextColor:[UIColor whiteColor]];
8883 [status_ setBackgroundColor:[UIColor clearColor]];
8884 [status_ setShadowColor:[UIColor blackColor]];
8885 [status_ setTextAlignment:UITextAlignmentCenter];
8886 [[self view] addSubview:status_];
8889 - (void) releaseSubviews {
8903 @interface Cydia : UIApplication <
8904 ConfirmationControllerDelegate,
8907 UINavigationControllerDelegate,
8908 UITabBarControllerDelegate
8910 // XXX: evaluate all fields for _transient
8913 CYTabBarController *tabbar_;
8914 CYEmulatedLoadingController *emulated_;
8916 NSMutableArray *essential_;
8917 NSMutableArray *broken_;
8919 Database *database_;
8926 StashController *stash_;
8935 @implementation Cydia
8937 - (void) beginUpdate {
8938 [tabbar_ beginUpdate];
8942 return [tabbar_ updating];
8946 if ([broken_ count] != 0) {
8947 int count = [broken_ count];
8949 UIAlertView *alert = [[[UIAlertView alloc]
8950 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8951 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8953 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8955 UCLocalize("TEMPORARY_IGNORE"),
8959 [alert setContext:@"fixhalf"];
8960 [alert setNumberOfRows:2];
8962 } else if (!Ignored_ && [essential_ count] != 0) {
8963 int count = [essential_ count];
8965 UIAlertView *alert = [[[UIAlertView alloc]
8966 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8967 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8969 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8971 UCLocalize("UPGRADE_ESSENTIAL"),
8972 UCLocalize("COMPLETE_UPGRADE"),
8976 [alert setContext:@"upgrade"];
8981 - (void) _saveConfig {
8987 NSString *error(nil);
8989 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8991 NSError *error(nil);
8992 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8993 NSLog(@"failure to save metadata data: %@", error);
8998 NSLog(@"failure to serialize metadata: %@", error);
9003 // Navigation controller for the queuing badge.
9004 - (UINavigationController *) queueNavigationController {
9005 NSArray *controllers = [tabbar_ viewControllers];
9006 return [controllers objectAtIndex:3];
9009 - (void) unloadData {
9010 [tabbar_ unloadData];
9013 - (void) _updateData {
9018 UINavigationController *navigation = [self queueNavigationController];
9020 id queuedelegate = nil;
9021 if ([[navigation viewControllers] count] > 0)
9022 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9024 [queuedelegate queueStatusDidChange];
9025 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9028 - (void) _refreshIfPossible:(NSDate *)update {
9029 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9031 bool recently = false;
9032 if (update != nil) {
9033 NSTimeInterval interval([update timeIntervalSinceNow]);
9034 if (interval <= 0 && interval > -(15*60))
9038 // Don't automatic refresh if:
9039 // - We already refreshed recently.
9040 // - We already auto-refreshed this launch.
9041 // - Auto-refresh is disabled.
9042 if (recently || loaded_ || ManualRefresh) {
9043 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9045 // If we are cancelling, we need to make sure it knows it's already loaded.
9049 // We are going to load, so remember that.
9053 SCNetworkReachabilityFlags flags; {
9054 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9055 SCNetworkReachabilityGetFlags(reachability, &flags);
9056 CFRelease(reachability);
9059 // XXX: this elaborate mess is what Apple is using to determine this? :(
9060 // XXX: do we care if the user has to intervene? maybe that's ok?
9062 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9063 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9064 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9065 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9066 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9067 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9071 // If we can reach the server, auto-refresh!
9073 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9078 - (void) refreshIfPossible {
9079 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9082 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
9083 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9084 [hud setText:UCLocalize("RELOADING_DATA")];
9086 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9089 [self removeProgressHUD:hud];
9093 [essential_ removeAllObjects];
9094 [broken_ removeAllObjects];
9096 NSArray *packages([database_ packages]);
9097 for (Package *package in packages) {
9099 [broken_ addObject:package];
9100 if ([package upgradableAndEssential:NO]) {
9101 if ([package essential])
9102 [essential_ addObject:package];
9107 NSLog(@"changes:#%u", changes);
9109 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9112 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9113 [changesItem setBadgeValue:badge];
9114 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9115 [self setApplicationIconBadgeNumber:changes];
9118 [changesItem setBadgeValue:nil];
9119 [changesItem setAnimatedBadge:NO];
9120 [self setApplicationIconBadgeNumber:0];
9125 [self refreshIfPossible];
9128 - (void) updateData {
9137 @synchronized (self) {
9138 [self _reloadDataWithInvocation:nil];
9142 - (void) disemulate {
9143 if (emulated_ == nil)
9146 [window_ addSubview:[tabbar_ view]];
9147 [[emulated_ view] removeFromSuperview];
9148 [emulated_ release];
9150 [window_ setUserInteractionEnabled:YES];
9153 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9154 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9156 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9158 UIViewController *parent;
9159 if (emulated_ == nil)
9168 [parent presentModalViewController:navigation animated:YES];
9171 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9172 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9174 if (navigation != nil)
9175 [navigation pushViewController:progress animated:YES];
9177 [self presentModalViewController:progress force:YES];
9179 [progress invoke:invocation withTitle:title];
9183 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9184 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9187 - (void) repairWithInvocation:(NSInvocation *)invocation {
9189 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9193 - (void) repairWithSelector:(SEL)selector {
9194 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9200 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9201 _assert(file != NULL);
9203 for (NSString *key in [Sources_ allKeys]) {
9204 NSDictionary *source([Sources_ objectForKey:key]);
9206 fprintf(file, "%s %s %s\n",
9207 [[source objectForKey:@"Type"] UTF8String],
9208 [[source objectForKey:@"URI"] UTF8String],
9209 [[source objectForKey:@"Distribution"] UTF8String]
9215 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9220 - (void) addTrivialSource:(NSString *)href {
9221 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9224 @"./", @"Distribution",
9225 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9230 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9231 @synchronized (self) {
9232 [self _reloadDataWithInvocation:invocation];
9236 - (void) reloadData {
9237 [self reloadDataWithInvocation:nil];
9241 pkgProblemResolver *resolver = [database_ resolver];
9243 resolver->InstallProtect();
9244 if (!resolver->Resolve(true))
9249 // XXX: this is a really crappy way of doing this.
9250 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9251 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9252 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9253 if ([tabbar_ updating])
9254 [tabbar_ cancelUpdate];
9256 if (![database_ prepare])
9259 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9260 [page setDelegate:self];
9261 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9264 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9265 [tabbar_ presentModalViewController:confirm_ animated:YES];
9271 @synchronized (self) {
9276 - (void) clearPackage:(Package *)package {
9277 @synchronized (self) {
9284 - (void) installPackages:(NSArray *)packages {
9285 @synchronized (self) {
9286 for (Package *package in packages)
9293 - (void) installPackage:(Package *)package {
9294 @synchronized (self) {
9301 - (void) removePackage:(Package *)package {
9302 @synchronized (self) {
9309 - (void) distUpgrade {
9310 @synchronized (self) {
9311 if (![database_ upgrade])
9317 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9320 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
9325 - (void) showSettings {
9326 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9329 - (void) retainNetworkActivityIndicator {
9330 if (activity_++ == 0)
9331 [self setNetworkActivityIndicatorVisible:YES];
9334 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9338 - (void) releaseNetworkActivityIndicator {
9339 if (--activity_ == 0)
9340 [self setNetworkActivityIndicatorVisible:NO];
9343 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9348 - (void) cancelAndClear:(bool)clear {
9349 @synchronized (self) {
9361 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9362 NSString *context([alert context]);
9364 if ([context isEqualToString:@"conffile"]) {
9365 FILE *input = [database_ input];
9366 if (button == [alert cancelButtonIndex])
9367 fprintf(input, "N\n");
9368 else if (button == [alert firstOtherButtonIndex])
9369 fprintf(input, "Y\n");
9372 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9373 } else if ([context isEqualToString:@"fixhalf"]) {
9374 if (button == [alert cancelButtonIndex]) {
9375 @synchronized (self) {
9376 for (Package *broken in broken_) {
9379 NSString *id = [broken id];
9380 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9381 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9382 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9383 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9389 } else if (button == [alert firstOtherButtonIndex]) {
9390 [broken_ removeAllObjects];
9394 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9395 } else if ([context isEqualToString:@"upgrade"]) {
9396 if (button == [alert firstOtherButtonIndex]) {
9397 @synchronized (self) {
9398 for (Package *essential in essential_)
9399 [essential install];
9404 } else if (button == [alert firstOtherButtonIndex] + 1) {
9406 } else if (button == [alert cancelButtonIndex]) {
9410 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9414 - (void) system:(NSString *)command { _pooled
9416 system([command UTF8String]);
9420 - (void) applicationWillSuspend {
9422 [super applicationWillSuspend];
9425 - (BOOL) isSafeToSuspend {
9428 NSLog(@"isSafeToSuspend: locked_ != 0");
9433 // Use external process status API internally.
9434 // This is probably a really bad idea.
9435 // XXX: what is the point of this? does this solve anything at all?
9436 uint64_t status = 0;
9438 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9439 notify_get_state(notify_token, &status);
9440 notify_cancel(notify_token);
9445 NSLog(@"isSafeToSuspend: status != 0");
9451 NSLog(@"isSafeToSuspend: -> true");
9456 - (void) applicationSuspend:(__GSEvent *)event {
9457 if ([self isSafeToSuspend])
9458 [super applicationSuspend:event];
9461 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9462 if ([self isSafeToSuspend])
9463 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9466 - (void) _setSuspended:(BOOL)value {
9467 if ([self isSafeToSuspend])
9468 [super _setSuspended:value];
9471 - (UIProgressHUD *) addProgressHUD {
9472 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9473 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9475 [window_ setUserInteractionEnabled:NO];
9477 UIViewController *target(tabbar_);
9478 if (UIViewController *modal = [target modalViewController])
9481 UIView *view([target view]);
9482 [view addSubview:hud];
9490 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9493 [hud removeFromSuperview];
9494 [window_ setUserInteractionEnabled:YES];
9497 - (CYViewController *) pageForPackage:(NSString *)name {
9498 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9501 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9502 NSString *scheme([[url scheme] lowercaseString]);
9503 if ([[url absoluteString] length] <= [scheme length] + 3)
9505 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9506 NSArray *components([path pathComponents]);
9508 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9509 return [self pageForPackage:[components objectAtIndex:1]];
9511 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9514 NSString *base([components objectAtIndex:0]);
9516 CYViewController *controller = nil;
9518 if ([base isEqualToString:@"url"]) {
9519 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9520 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9521 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9522 } else if (!external && [components count] == 1) {
9523 if ([base isEqualToString:@"manage"]) {
9524 controller = [[[ManageController alloc] init] autorelease];
9527 if ([base isEqualToString:@"sources"]) {
9528 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9531 if ([base isEqualToString:@"home"]) {
9532 controller = [[[HomeController alloc] init] autorelease];
9535 if ([base isEqualToString:@"sections"]) {
9536 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9539 if ([base isEqualToString:@"search"]) {
9540 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9543 if ([base isEqualToString:@"changes"]) {
9544 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9547 if ([base isEqualToString:@"installed"]) {
9548 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9550 } else if ([components count] == 2) {
9551 NSString *argument = [components objectAtIndex:1];
9553 if ([base isEqualToString:@"package"]) {
9554 controller = [self pageForPackage:argument];
9557 if (!external && [base isEqualToString:@"search"]) {
9558 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9559 [(SearchController *)controller setSearchTerm:argument];
9562 if (!external && [base isEqualToString:@"sections"]) {
9563 if ([argument isEqualToString:@"all"])
9565 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9568 if (!external && [base isEqualToString:@"sources"]) {
9569 if ([argument isEqualToString:@"add"]) {
9570 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9571 [(SourcesController *)controller showAddSourcePrompt];
9573 Source *source = [database_ sourceWithKey:argument];
9574 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9578 if (!external && [base isEqualToString:@"launch"]) {
9579 [self launchApplicationWithIdentifier:argument suspended:NO];
9582 } else if (!external && [components count] == 3) {
9583 NSString *arg1 = [components objectAtIndex:1];
9584 NSString *arg2 = [components objectAtIndex:2];
9586 if ([base isEqualToString:@"package"]) {
9587 if ([arg2 isEqualToString:@"settings"]) {
9588 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9589 } else if ([arg2 isEqualToString:@"files"]) {
9590 if (Package *package = [database_ packageWithName:arg1]) {
9591 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9592 [(FileTable *)controller setPackage:package];
9598 [controller setDelegate:self];
9602 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9603 CYViewController *page([self pageForURL:url forExternal:external]);
9606 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9607 [nav setViewControllers:[NSArray arrayWithObject:page]];
9608 [tabbar_ setUnselectedViewController:nav];
9614 - (void) applicationOpenURL:(NSURL *)url {
9615 [super applicationOpenURL:url];
9617 if (!loaded_) starturl_ = [url retain];
9618 else [self openCydiaURL:url forExternal:YES];
9621 - (void) applicationWillResignActive:(UIApplication *)application {
9622 // Stop refreshing if you get a phone call or lock the device.
9623 if ([tabbar_ updating])
9624 [tabbar_ cancelUpdate];
9626 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9627 [super applicationWillResignActive:application];
9630 - (void) applicationWillTerminate:(UIApplication *)application {
9632 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9633 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9634 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9639 - (void) setConfigurationData:(NSString *)data {
9640 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9642 if (!conffile_r(data)) {
9643 lprintf("E:invalid conffile\n");
9647 NSString *ofile = conffile_r[1];
9648 //NSString *nfile = conffile_r[2];
9650 UIAlertView *alert = [[[UIAlertView alloc]
9651 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9652 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9654 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9656 UCLocalize("ACCEPT_NEW_COPY"),
9657 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9661 [alert setContext:@"conffile"];
9662 [alert setNumberOfRows:2];
9666 - (void) addStashController {
9668 stash_ = [[StashController alloc] init];
9669 [window_ addSubview:[stash_ view]];
9672 - (void) removeStashController {
9673 [[stash_ view] removeFromSuperview];
9679 [self setIdleTimerDisabled:YES];
9681 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9682 UpdateExternalStatus(1);
9683 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9684 UpdateExternalStatus(0);
9686 [self removeStashController];
9688 if (ExecFork() == 0) {
9689 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9690 perror("launchctl stop");
9694 - (void) setupViewControllers {
9695 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9697 NSMutableArray *items([NSMutableArray arrayWithObjects:
9698 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9699 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9700 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9701 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9705 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9706 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9708 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9711 NSMutableArray *controllers([NSMutableArray array]);
9712 for (UITabBarItem *item in items) {
9713 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9714 [controller setTabBarItem:item];
9715 [controllers addObject:controller];
9717 [tabbar_ setViewControllers:controllers];
9719 [tabbar_ setUpdateDelegate:self];
9722 - (void) applicationDidFinishLaunching:(id)unused {
9724 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9725 [self setApplicationSupportsShakeToEdit:NO];
9727 @synchronized (HostConfig_) {
9728 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9731 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9732 initWithMemoryCapacity:524288
9733 diskCapacity:10485760
9734 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9737 [CYBrowserController _initialize];
9739 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9741 Font12_ = [[UIFont systemFontOfSize:12] retain];
9742 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9743 Font14_ = [[UIFont systemFontOfSize:14] retain];
9744 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9745 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9747 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9748 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9750 // XXX: I really need this thing... like, seriously... I'm sorry
9751 [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9753 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9754 [window_ orderFront:self];
9755 [window_ makeKey:self];
9756 [window_ setHidden:NO];
9759 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9760 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9761 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9762 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9763 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9764 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9765 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9766 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9767 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9770 [self addStashController];
9771 // XXX: this would be much cleaner as a yieldToSelector:
9772 // that way the removeStashController could happen right here inline
9773 // we also could no longer require the useless stash_ field anymore
9774 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9778 database_ = [Database sharedInstance];
9779 [database_ setDelegate:self];
9781 [window_ setUserInteractionEnabled:NO];
9782 [self setupViewControllers];
9784 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9785 [window_ addSubview:[emulated_ view]];
9787 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9791 - (NSArray *) defaultStartPages {
9792 NSMutableArray *standard = [NSMutableArray array];
9793 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9794 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9795 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9797 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9799 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9800 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9802 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9809 [window_ setUserInteractionEnabled:YES];
9810 [self showSettings];
9813 if ([emulated_ modalViewController] != nil)
9814 [emulated_ dismissModalViewControllerAnimated:YES];
9815 [window_ setUserInteractionEnabled:NO];
9823 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9824 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9825 int standardIndex = 0;
9826 NSArray *standard = [self defaultStartPages];
9833 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9834 if (valid && closed != nil) {
9835 NSTimeInterval interval([closed timeIntervalSinceNow]);
9836 // XXX: Is 15 minutes the optimal time here?
9837 if (interval > 0 && interval <= -(15*60))
9841 if (valid && [saved count] != [standard count])
9845 for (unsigned int i = 0; i < [standard count]; i++) {
9846 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9847 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9848 // but it's good enough for now.
9849 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9856 NSArray *items = nil;
9858 [tabbar_ setSelectedIndex:savedIndex];
9861 [tabbar_ setSelectedIndex:standardIndex];
9865 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9866 NSArray *stack = [items objectAtIndex:tab];
9867 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9868 NSMutableArray *current = [NSMutableArray array];
9870 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9871 NSString *addr = [stack objectAtIndex:nav];
9872 NSURL *url = [NSURL URLWithString:addr];
9873 CYViewController *page = [self pageForURL:url forExternal:NO];
9875 [current addObject:page];
9878 [navigation setViewControllers:current];
9881 // (Try to) show the startup URL.
9882 if (starturl_ != nil) {
9883 [self openCydiaURL:starturl_ forExternal:NO];
9884 [starturl_ release];
9889 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9890 if (item != nil && IsWildcat_) {
9891 [sheet showFromBarButtonItem:item animated:YES];
9893 [sheet showInView:window_];
9897 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9898 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9899 [progress setTitle:task];
9900 [progress addProgressEvent:event];
9903 - (void) addProgressEventForTask:(NSArray *)data {
9904 CydiaProgressEvent *event([data objectAtIndex:0]);
9905 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9906 [self addProgressEvent:event forTask:task];
9909 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9910 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9916 id Alloc_(id self, SEL selector) {
9917 id object = alloc_(self, selector);
9918 lprintf("[%s]A-%p\n", self->isa->name, object);
9923 id Dealloc_(id self, SEL selector) {
9924 id object = dealloc_(self, selector);
9925 lprintf("[%s]D-%p\n", self->isa->name, object);
9929 Class $WebDefaultUIKitDelegate;
9931 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9932 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9933 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9934 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9937 static NSSet *MobilizedFiles_;
9939 static NSURL *MobilizeURL(NSURL *url) {
9940 NSString *path([url path]);
9941 if ([path hasPrefix:@"/var/root/"]) {
9942 NSString *file([path substringFromIndex:10]);
9943 if ([MobilizedFiles_ containsObject:file])
9944 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9950 Class $CFXPreferencesPropertyListSource;
9951 @class CFXPreferencesPropertyListSource;
9953 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9954 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9955 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9956 url = MobilizeURL(url);
9957 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9958 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9964 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9965 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9966 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9967 url = MobilizeURL(url);
9968 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9969 //NSLog(@"%@ %@", [url absoluteString], value);
9975 Class $NSURLConnection;
9977 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9978 NSMutableURLRequest *copy([request mutableCopy]);
9980 NSURL *url([copy URL]);
9981 NSString *host([url host]);
9982 NSString *scheme([[url scheme] lowercaseString]);
9984 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9986 @synchronized (HostConfig_) {
9987 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9988 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9989 [copy setHTTPShouldUsePipelining:YES];
9992 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9996 int main(int argc, char *argv[]) { _pooled
9999 UpdateExternalStatus(0);
10001 if (Class $UIDevice = objc_getClass("UIDevice")) {
10002 UIDevice *device([$UIDevice currentDevice]);
10003 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10005 IsWildcat_ = false;
10007 UIScreen *screen([UIScreen mainScreen]);
10008 if ([screen respondsToSelector:@selector(scale)])
10009 ScreenScale_ = [screen scale];
10013 UIDevice *device([UIDevice currentDevice]);
10014 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10015 Idiom_ = @"iphone";
10017 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10018 if (idiom == UIUserInterfaceIdiomPhone)
10019 Idiom_ = @"iphone";
10020 else if (idiom == UIUserInterfaceIdiomPad)
10023 NSLog(@"unknown UIUserInterfaceIdiom!");
10026 SessionData_ = [[NSMutableDictionary alloc] initWithCapacity:4];
10028 HostConfig_ = [[NSObject alloc] init];
10029 @synchronized (HostConfig_) {
10030 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10031 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10034 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
10036 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10038 MobilizedFiles_ = [NSMutableSet setWithObjects:
10039 @"Library/Preferences/com.apple.Accessibility.plist",
10040 @"Library/Preferences/com.apple.preferences.sounds.plist",
10043 /* Library Hacks {{{ */
10044 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10046 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10048 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10049 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10050 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10051 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10054 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10055 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10056 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10057 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10060 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10061 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10062 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10063 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10064 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10067 $NSURLConnection = objc_getClass("NSURLConnection");
10068 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10069 if (NSURLConnection$init$ != NULL) {
10070 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10071 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10074 /* Set Locale {{{ */
10075 Locale_ = CFLocaleCopyCurrent();
10076 Languages_ = [NSLocale preferredLanguages];
10078 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10079 //NSLog(@"%@", [Languages_ description]);
10082 if (Locale_ != NULL)
10083 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10084 else if (Languages_ != nil && [Languages_ count] != 0)
10085 lang = [[Languages_ objectAtIndex:0] UTF8String];
10087 // XXX: consider just setting to C and then falling through?
10090 if (lang != NULL) {
10091 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10092 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10095 NSLog(@"Setting Language: %s", lang);
10097 if (lang != NULL) {
10098 setenv("LANG", lang, true);
10099 std::setlocale(LC_ALL, lang);
10103 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10105 /* Parse Arguments {{{ */
10106 bool substrate(false);
10112 for (int argi(1); argi != argc; ++argi)
10113 if (strcmp(argv[argi], "--") == 0) {
10115 argv[argi] = argv[0];
10121 for (int argi(1); argi != arge; ++argi)
10122 if (strcmp(args[argi], "--substrate") == 0)
10125 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10129 App_ = [[NSBundle mainBundle] bundlePath];
10135 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10136 alloc_ = alloc->method_imp;
10137 alloc->method_imp = (IMP) &Alloc_;*/
10139 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10140 dealloc_ = dealloc->method_imp;
10141 dealloc->method_imp = (IMP) &Dealloc_;*/
10143 /* System Information {{{ */
10147 size = sizeof(maxproc);
10148 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10149 perror("sysctlbyname(\"kern.maxproc\", ?)");
10150 else if (maxproc < 64) {
10152 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10153 perror("sysctlbyname(\"kern.maxproc\", #)");
10156 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10157 char *osversion = new char[size];
10158 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10159 perror("sysctlbyname(\"kern.osversion\", ?)");
10161 System_ = [NSString stringWithUTF8String:osversion];
10163 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10164 char *machine = new char[size];
10165 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10166 perror("sysctlbyname(\"hw.machine\", ?)");
10168 Machine_ = machine;
10170 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
10171 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
10172 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
10173 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
10177 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
10178 NSData *data((NSData *) ecid);
10179 size_t length([data length]);
10180 uint8_t bytes[length];
10181 [data getBytes:bytes];
10182 char string[length * 2 + 1];
10183 for (size_t i(0); i != length; ++i)
10184 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10185 ChipID_ = [NSString stringWithUTF8String:string];
10189 IOObjectRelease(service);
10193 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10195 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10196 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10197 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10199 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10200 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10201 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10203 if (mcc != NULL && mnc != NULL)
10204 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10211 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10212 Build_ = [system objectForKey:@"ProductBuildVersion"];
10213 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10214 Product_ = [info objectForKey:@"SafariProductVersion"];
10215 Safari_ = [info objectForKey:@"CFBundleVersion"];
10218 /* Load Database {{{ */
10220 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10222 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10224 if (Metadata_ == NULL)
10225 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10227 Settings_ = [Metadata_ objectForKey:@"Settings"];
10229 Packages_ = [Metadata_ objectForKey:@"Packages"];
10230 Sections_ = [Metadata_ objectForKey:@"Sections"];
10231 Sources_ = [Metadata_ objectForKey:@"Sources"];
10233 Token_ = [Metadata_ objectForKey:@"Token"];
10236 if (Settings_ != nil)
10237 Role_ = [Settings_ objectForKey:@"Role"];
10239 if (Sections_ == nil) {
10240 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10241 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10244 if (Sources_ == nil) {
10245 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10246 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10251 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10254 if (Packages_ != nil) {
10256 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10260 [Metadata_ removeObjectForKey:@"Packages"];
10266 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10268 #define MobileSubstrate_(name) \
10269 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10270 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10271 if (handle == NULL) \
10272 NSLog(@"%s", dlerror()); \
10275 MobileSubstrate_(Activator)
10276 MobileSubstrate_(libstatusbar)
10277 MobileSubstrate_(SimulatedKeyEvents)
10278 MobileSubstrate_(WinterBoard)
10280 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10281 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10283 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10285 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10286 unlink("/tmp/.cydia.fw");
10288 } else if (access("/User", F_OK) != 0 || version < 4) {
10291 system("/usr/libexec/cydia/firmware.sh");
10295 _assert([[NSFileManager defaultManager]
10296 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10297 withIntermediateDirectories:YES
10302 if (access("/tmp/cydia.chk", F_OK) == 0) {
10303 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10304 _assert(errno == ENOENT);
10305 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10306 _assert(errno == ENOENT);
10309 /* APT Initialization {{{ */
10310 _assert(pkgInitConfig(*_config));
10311 _assert(pkgInitSystem(*_config, _system));
10314 _config->Set("APT::Acquire::Translation", lang);
10316 // XXX: this timeout might be important :(
10317 //_config->Set("Acquire::http::Timeout", 15);
10319 _config->Set("Acquire::http::MaxParallel", 3);
10321 /* Color Choices {{{ */
10322 space_ = CGColorSpaceCreateDeviceRGB();
10324 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10325 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10326 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10327 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10328 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10329 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10330 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10331 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10332 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10334 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10335 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10337 /* UIKit Configuration {{{ */
10338 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10339 if ($GSFontSetUseLegacyFontMetrics != NULL)
10340 $GSFontSetUseLegacyFontMetrics(YES);
10342 // XXX: I have a feeling this was important
10343 //UIKeyboardDisableAutomaticAppearance();
10346 Colon_ = UCLocalize("COLON_DELIMITED");
10347 Elision_ = UCLocalize("ELISION");
10348 Error_ = UCLocalize("ERROR");
10349 Warning_ = UCLocalize("WARNING");
10352 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10354 CGColorSpaceRelease(space_);
10355 CFRelease(Locale_);