1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2009 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 #import "UICaboodle/UCPlatform.h"
45 #import "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <GraphicsServices/GraphicsServices.h>
52 #include <Foundation/Foundation.h>
55 #define DEPLOYMENT_TARGET_MACOSX 1
56 #define CF_BUILDING_CF 1
57 #include <CoreFoundation/CFInternal.h>
60 #include <CoreFoundation/CFPriv.h>
61 #include <CoreFoundation/CFUniChar.h>
63 #import <UIKit/UIKit.h>
65 #include <WebCore/WebCoreThread.h>
66 #import <WebKit/WebDefaultUIKitDelegate.h>
73 #include <ext/stdio_filebuf.h>
75 #include <apt-pkg/acquire.h>
76 #include <apt-pkg/acquire-item.h>
77 #include <apt-pkg/algorithms.h>
78 #include <apt-pkg/cachefile.h>
79 #include <apt-pkg/clean.h>
80 #include <apt-pkg/configuration.h>
81 #include <apt-pkg/debindexfile.h>
82 #include <apt-pkg/debmetaindex.h>
83 #include <apt-pkg/error.h>
84 #include <apt-pkg/init.h>
85 #include <apt-pkg/mmap.h>
86 #include <apt-pkg/pkgrecords.h>
87 #include <apt-pkg/sha1.h>
88 #include <apt-pkg/sourcelist.h>
89 #include <apt-pkg/sptr.h>
90 #include <apt-pkg/strutl.h>
91 #include <apt-pkg/tagfile.h>
93 #include <apr-1/apr_pools.h>
95 #include <sys/types.h>
97 #include <sys/sysctl.h>
98 #include <sys/param.h>
99 #include <sys/mount.h>
105 #include <mach-o/nlist.h>
115 #include <ext/hash_map>
117 #import "UICaboodle/BrowserView.h"
118 #import "UICaboodle/ResetView.h"
120 #import "substrate.h"
127 #define _timestamp ({ \
129 gettimeofday(&tv, NULL); \
130 tv.tv_sec * 1000000 + tv.tv_usec; \
133 typedef std::vector<class ProfileTime *> TimeList;
143 ProfileTime(const char *name) :
147 times_.push_back(this);
150 void AddTime(uint64_t time) {
157 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
169 ProfileTimer(ProfileTime &time) :
176 time_.AddTime(_timestamp - start_);
181 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
183 std::cerr << "========" << std::endl;
186 #define _profile(name) { \
187 static ProfileTime name(#name); \
188 ProfileTimer _ ## name(name);
192 /* Objective-C Handle<> {{{ */
193 template <typename Type_>
195 typedef _H<Type_> This_;
200 _finline void Retain_() {
205 _finline void Clear_() {
211 _finline _H(const This_ &rhs) :
212 value_(rhs.value_ == nil ? nil : [rhs.value_ retain])
216 _finline _H(Type_ *value = NULL, bool mended = false) :
227 _finline operator Type_ *() const {
231 _finline This_ &operator =(Type_ *value) {
232 if (value_ != value) {
243 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
245 void NSLogPoint(const char *fix, const CGPoint &point) {
246 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
249 void NSLogRect(const char *fix, const CGRect &rect) {
250 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
253 /* [NSObject yieldToSelector:(withObject:)] {{{*/
254 @interface NSObject (Cydia)
255 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
256 - (id) yieldToSelector:(SEL)selector;
259 @implementation NSObject (Cydia)
264 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
265 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
266 id object([[context objectAtIndex:1] nonretainedObjectValue]);
267 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
269 /* XXX: deal with exceptions */
270 id value([self performSelector:selector withObject:object]);
272 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
273 [context removeAllObjects];
274 if ([signature methodReturnLength] != 0 && value != nil)
275 [context addObject:value];
280 performSelectorOnMainThread:@selector(doNothing)
286 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
287 /*return [self performSelector:selector withObject:object];*/
289 volatile bool stopped(false);
291 NSMutableArray *context([NSMutableArray arrayWithObjects:
292 [NSValue valueWithPointer:selector],
293 [NSValue valueWithNonretainedObject:object],
294 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
297 NSThread *thread([[[NSThread alloc]
299 selector:@selector(_yieldToContext:)
305 NSRunLoop *loop([NSRunLoop currentRunLoop]);
306 NSDate *future([NSDate distantFuture]);
308 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
310 return [context count] == 0 ? nil : [context objectAtIndex:0];
313 - (id) yieldToSelector:(SEL)selector {
314 return [self yieldToSelector:selector withObject:nil];
320 /* NSForcedOrderingSearch doesn't work on the iPhone */
321 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
322 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
323 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
325 /* Information Dictionaries {{{ */
326 @interface NSMutableArray (Cydia)
327 - (void) addInfoDictionary:(NSDictionary *)info;
330 @implementation NSMutableArray (Cydia)
332 - (void) addInfoDictionary:(NSDictionary *)info {
333 [self addObject:info];
338 @interface NSMutableDictionary (Cydia)
339 - (void) addInfoDictionary:(NSDictionary *)info;
342 @implementation NSMutableDictionary (Cydia)
344 - (void) addInfoDictionary:(NSDictionary *)info {
345 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
350 /* Pop Transitions {{{ */
351 @interface PopTransitionView : UITransitionView {
356 @implementation PopTransitionView
358 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
359 if (from != nil && to == nil)
360 [self removeFromSuperview];
365 @implementation UIView (PopUpView)
367 - (void) popFromSuperviewAnimated:(BOOL)animated {
368 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
371 - (void) popSubview:(UIView *)view {
372 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
373 [transition setDelegate:transition];
374 [self addSubview:transition];
376 UIView *blank = [[[UIView alloc] initWithFrame:[transition bounds]] autorelease];
377 [transition transition:UITransitionNone toView:blank];
378 [transition transition:UITransitionPushFromBottom toView:view];
384 #define lprintf(args...) fprintf(stderr, args)
387 #define TraceLogging (1 && !ForRelease)
388 #define HistogramInsertionSort (0 && !ForRelease)
389 #define ProfileTimes (0 && !ForRelease)
390 #define ForSaurik (0 && !ForRelease)
391 #define LogBrowser (1 && !ForRelease)
392 #define TrackResize (0 && !ForRelease)
393 #define ManualRefresh (1 && !ForRelease)
394 #define ShowInternals (0 && !ForRelease)
395 #define IgnoreInstall (0 && !ForRelease)
396 #define RecycleWebViews 0
397 #define RecyclePackageViews 1
398 #define AlwaysReload (0 && !ForRelease)
402 #define _trace(args...)
407 #define _profile(name) {
410 #define PrintTimes() do {} while (false)
414 typedef uint32_t (*SKRadixFunction)(id, void *);
416 @interface NSMutableArray (Radix)
417 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
418 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
426 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
427 struct RadixItem_ *lhs(swap), *rhs(swap + count);
429 static const size_t width = 32;
430 static const size_t bits = 11;
431 static const size_t slots = 1 << bits;
432 static const size_t passes = (width + (bits - 1)) / bits;
434 size_t *hist(new size_t[slots]);
436 for (size_t pass(0); pass != passes; ++pass) {
437 memset(hist, 0, sizeof(size_t) * slots);
439 for (size_t i(0); i != count; ++i) {
440 uint32_t key(lhs[i].key);
442 key &= _not(uint32_t) >> width - bits;
447 for (size_t i(0); i != slots; ++i) {
448 size_t local(offset);
453 for (size_t i(0); i != count; ++i) {
454 uint32_t key(lhs[i].key);
456 key &= _not(uint32_t) >> width - bits;
457 rhs[hist[key]++] = lhs[i];
460 RadixItem_ *tmp(lhs);
467 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
468 for (size_t i(0); i != count; ++i)
469 [values addObject:[self objectAtIndex:lhs[i].index]];
470 [self setArray:values];
475 @implementation NSMutableArray (Radix)
477 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
478 size_t count([self count]);
483 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
484 [invocation setSelector:selector];
485 [invocation setArgument:&object atIndex:2];
487 /* XXX: this is an unsafe optimization of doomy hell */
488 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
489 _assert(method != NULL);
490 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
491 _assert(imp != NULL);
494 struct RadixItem_ *swap(new RadixItem_[count * 2]);
496 for (size_t i(0); i != count; ++i) {
497 RadixItem_ &item(swap[i]);
500 id object([self objectAtIndex:i]);
503 [invocation setTarget:object];
505 [invocation getReturnValue:&item.key];
507 item.key = imp(object, selector, object);
511 RadixSort_(self, count, swap);
514 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
515 size_t count([self count]);
516 struct RadixItem_ *swap(new RadixItem_[count * 2]);
518 for (size_t i(0); i != count; ++i) {
519 RadixItem_ &item(swap[i]);
522 id object([self objectAtIndex:i]);
523 item.key = function(object, argument);
526 RadixSort_(self, count, swap);
531 /* Insertion Sort {{{ */
533 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
534 const char *ptr = (const char *)list;
536 CFIndex half = count / 2;
537 const char *probe = ptr + elementSize * half;
538 CFComparisonResult cr = comparator(element, probe, context);
539 if (0 == cr) return (probe - (const char *)list) / elementSize;
540 ptr = (cr < 0) ? ptr : probe + elementSize;
541 count = (cr < 0) ? half : (half + (count & 1) - 1);
543 return (ptr - (const char *)list) / elementSize;
546 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
547 const char *ptr = (const char *)list;
549 CFIndex half = count / 2;
550 const char *probe = ptr + elementSize * half;
551 CFComparisonResult cr = comparator(element, probe, context);
552 if (0 == cr) return (probe - (const char *)list) / elementSize;
553 ptr = (cr < 0) ? ptr : probe + elementSize;
554 count = (cr < 0) ? half : (half + (count & 1) - 1);
556 return (ptr - (const char *)list) / elementSize;
559 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
560 if (range.length == 0)
562 const void **values(new const void *[range.length]);
563 CFArrayGetValues(array, range, values);
565 #if HistogramInsertionSort
566 uint32_t total(0), *offsets(new uint32_t[range.length]);
569 for (CFIndex index(1); index != range.length; ++index) {
570 const void *value(values[index]);
571 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
572 CFIndex correct(index);
573 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
576 if (correct != index) {
577 size_t offset(index - correct);
578 #if HistogramInsertionSort
582 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
584 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
585 values[correct] = value;
589 CFArrayReplaceValues(array, range, values, range.length);
592 #if HistogramInsertionSort
593 for (CFIndex index(0); index != range.length; ++index)
594 if (offsets[index] != 0)
595 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
596 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
603 /* Apple Bug Fixes {{{ */
604 @implementation UIWebDocumentView (Cydia)
606 - (void) _setScrollerOffset:(CGPoint)offset {
607 UIScroller *scroller([self _scroller]);
609 CGSize size([scroller contentSize]);
610 CGSize bounds([scroller bounds].size);
613 max.x = size.width - bounds.width;
614 max.y = size.height - bounds.height;
622 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
623 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
625 [scroller setOffset:offset];
631 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
632 size_t length([self length] - state->state);
635 else if (length > count)
637 for (size_t i(0); i != length; ++i)
638 objects[i] = [self item:state->state++];
639 state->itemsPtr = objects;
640 state->mutationsPtr = (unsigned long *) self;
644 @interface NSString (UIKit)
645 - (NSString *) stringByAddingPercentEscapes;
648 /* Cydia NSString Additions {{{ */
649 @interface NSString (Cydia)
650 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
651 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
652 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
653 - (NSComparisonResult) compareByPath:(NSString *)other;
654 - (NSString *) stringByCachingURLWithCurrentCDN;
655 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
658 @implementation NSString (Cydia)
660 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
661 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
664 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
665 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
666 memcpy(data, bytes, length);
667 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
670 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
671 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
674 - (NSComparisonResult) compareByPath:(NSString *)other {
675 NSString *prefix = [self commonPrefixWithString:other options:0];
676 size_t length = [prefix length];
678 NSRange lrange = NSMakeRange(length, [self length] - length);
679 NSRange rrange = NSMakeRange(length, [other length] - length);
681 lrange = [self rangeOfString:@"/" options:0 range:lrange];
682 rrange = [other rangeOfString:@"/" options:0 range:rrange];
684 NSComparisonResult value;
686 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
687 value = NSOrderedSame;
688 else if (lrange.location == NSNotFound)
689 value = NSOrderedAscending;
690 else if (rrange.location == NSNotFound)
691 value = NSOrderedDescending;
693 value = NSOrderedSame;
695 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
696 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
697 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
698 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
700 NSComparisonResult result = [lpath compare:rpath];
701 return result == NSOrderedSame ? value : result;
704 - (NSString *) stringByCachingURLWithCurrentCDN {
706 stringByReplacingOccurrencesOfString:@"://"
707 withString:@"://ne.edgecastcdn.net/8003A4/"
709 /* XXX: this is somewhat inaccurate */
710 range:NSMakeRange(0, 10)
714 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
715 return [(id)CFURLCreateStringByAddingPercentEscapes(
720 kCFStringEncodingUTF8
727 /* C++ NSString Wrapper Cache {{{ */
734 _finline void clear_() {
735 if (cache_ != NULL) {
742 _finline bool empty() const {
746 _finline size_t size() const {
750 _finline char *data() const {
754 _finline void clear() {
759 _finline CYString() :
766 _finline ~CYString() {
770 void operator =(const CYString &rhs) {
774 if (rhs.cache_ == nil)
777 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
780 void set(apr_pool_t *pool, const char *data, size_t size) {
786 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
787 memcpy(temp, data, size);
794 _finline void set(apr_pool_t *pool, const char *data) {
795 set(pool, data, data == NULL ? 0 : strlen(data));
798 _finline void set(apr_pool_t *pool, const std::string &rhs) {
799 set(pool, rhs.data(), rhs.size());
802 bool operator ==(const CYString &rhs) const {
803 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
806 operator CFStringRef() {
807 if (cache_ == NULL) {
810 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
814 _finline operator id() {
815 return (NSString *) static_cast<CFStringRef>(*this);
819 /* C++ NSString Algorithm Adapters {{{ */
821 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
824 struct NSStringMapHash :
825 std::unary_function<NSString *, size_t>
827 _finline size_t operator ()(NSString *value) const {
828 return CFStringHashNSString((CFStringRef) value);
832 struct NSStringMapLess :
833 std::binary_function<NSString *, NSString *, bool>
835 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
836 return [lhs compare:rhs] == NSOrderedAscending;
840 struct NSStringMapEqual :
841 std::binary_function<NSString *, NSString *, bool>
843 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
844 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
845 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
846 //[lhs isEqualToString:rhs];
851 /* Perl-Compatible RegEx {{{ */
861 Pcre(const char *regex) :
866 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
869 lprintf("%d:%s\n", offset, error);
873 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
874 matches_ = new int[(capture_ + 1) * 3];
882 NSString *operator [](size_t match) {
883 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
886 bool operator ()(NSString *data) {
887 // XXX: length is for characters, not for bytes
888 return operator ()([data UTF8String], [data length]);
891 bool operator ()(const char *data, size_t size) {
893 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
897 /* Mime Addresses {{{ */
898 @interface Address : NSObject {
904 - (NSString *) address;
906 - (void) setAddress:(NSString *)address;
908 + (Address *) addressWithString:(NSString *)string;
909 - (Address *) initWithString:(NSString *)string;
912 @implementation Address
921 - (NSString *) name {
925 - (NSString *) address {
929 - (void) setAddress:(NSString *)address {
931 [address_ autorelease];
935 address_ = [address retain];
938 + (Address *) addressWithString:(NSString *)string {
939 return [[[Address alloc] initWithString:string] autorelease];
942 + (NSArray *) _attributeKeys {
943 return [NSArray arrayWithObjects:@"address", @"name", nil];
946 - (NSArray *) attributeKeys {
947 return [[self class] _attributeKeys];
950 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
951 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
954 - (Address *) initWithString:(NSString *)string {
955 if ((self = [super init]) != nil) {
956 const char *data = [string UTF8String];
957 size_t size = [string length];
959 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
961 if (address_r(data, size)) {
962 name_ = [address_r[1] retain];
963 address_ = [address_r[2] retain];
965 name_ = [string retain];
973 /* CoreGraphics Primitives {{{ */
984 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
987 Set(space, red, green, blue, alpha);
992 CGColorRelease(color_);
999 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1001 float color[] = {red, green, blue, alpha};
1002 color_ = CGColorCreate(space, color);
1005 operator CGColorRef() {
1011 /* Random Global Variables {{{ */
1012 static const int PulseInterval_ = 50000;
1013 static const int ButtonBarHeight_ = 48;
1014 static const float KeyboardTime_ = 0.3f;
1017 static NSArray *Finishes_;
1019 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1020 #define NotifyConfig_ "/etc/notify.conf"
1022 static bool Queuing_;
1024 static CGColor Blue_;
1025 static CGColor Blueish_;
1026 static CGColor Black_;
1027 static CGColor Off_;
1028 static CGColor White_;
1029 static CGColor Gray_;
1030 static CGColor Green_;
1031 static CGColor Purple_;
1032 static CGColor Purplish_;
1034 static UIColor *InstallingColor_;
1035 static UIColor *RemovingColor_;
1037 static NSString *App_;
1038 static NSString *Home_;
1040 static BOOL Advanced_;
1041 static BOOL Loaded_;
1042 static BOOL Ignored_;
1044 static UIFont *Font12_;
1045 static UIFont *Font12Bold_;
1046 static UIFont *Font14_;
1047 static UIFont *Font18Bold_;
1048 static UIFont *Font22Bold_;
1050 static const char *Machine_ = NULL;
1051 static const NSString *System_ = NULL;
1052 static const NSString *SerialNumber_ = nil;
1053 static const NSString *ChipID_ = nil;
1054 static const NSString *UniqueID_ = nil;
1055 static const NSString *Build_ = nil;
1056 static const NSString *Product_ = nil;
1057 static const NSString *Safari_ = nil;
1059 static CFLocaleRef Locale_;
1060 static NSArray *Languages_;
1061 static CGColorSpaceRef space_;
1063 static bool reload_;
1065 static NSDictionary *SectionMap_;
1066 static NSMutableDictionary *Metadata_;
1067 static _transient NSMutableDictionary *Settings_;
1068 static _transient NSString *Role_;
1069 static _transient NSMutableDictionary *Packages_;
1070 static _transient NSMutableDictionary *Sections_;
1071 static _transient NSMutableDictionary *Sources_;
1072 static bool Changed_;
1073 static NSDate *now_;
1076 static NSMutableArray *Documents_;
1080 /* Display Helpers {{{ */
1081 inline float Interpolate(float begin, float end, float fraction) {
1082 return (end - begin) * fraction + begin;
1085 /* XXX: localize this! */
1086 NSString *SizeString(double size) {
1087 bool negative = size < 0;
1092 while (size > 1024) {
1097 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1099 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1102 static _finline CFStringRef CFCString(const char *value) {
1103 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1106 const char *StripVersion_(const char *version) {
1107 const char *colon(strchr(version, ':'));
1109 version = colon + 1;
1113 CFStringRef StripVersion(const char *version) {
1114 const char *colon(strchr(version, ':'));
1116 version = colon + 1;
1117 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1119 return CFCString(version);
1122 NSString *LocalizeSection(NSString *section) {
1123 static Pcre title_r("^(.*?) \\((.*)\\)$");
1124 if (title_r(section)) {
1125 NSString *parent(title_r[1]);
1126 NSString *child(title_r[2]);
1128 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1129 LocalizeSection(parent),
1130 LocalizeSection(child)
1134 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1137 NSString *Simplify(NSString *title) {
1138 const char *data = [title UTF8String];
1139 size_t size = [title length];
1141 static Pcre square_r("^\\[(.*)\\]$");
1142 if (square_r(data, size))
1143 return Simplify(square_r[1]);
1145 static Pcre paren_r("^\\((.*)\\)$");
1146 if (paren_r(data, size))
1147 return Simplify(paren_r[1]);
1149 static Pcre title_r("^(.*?) \\((.*)\\)$");
1150 if (title_r(data, size))
1151 return Simplify(title_r[1]);
1157 NSString *GetLastUpdate() {
1158 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1161 return UCLocalize("NEVER_OR_UNKNOWN");
1163 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1164 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1166 CFRelease(formatter);
1168 return [(NSString *) formatted autorelease];
1171 bool isSectionVisible(NSString *section) {
1172 NSDictionary *metadata([Sections_ objectForKey:section]);
1173 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1174 return hidden == nil || ![hidden boolValue];
1177 /* Delegate Prototypes {{{ */
1181 @interface NSObject (ProgressDelegate)
1184 @implementation NSObject(ProgressDelegate)
1186 - (void) _setProgressError:(NSArray *)args {
1187 [self performSelector:@selector(setProgressError:forPackage:)
1188 withObject:[args objectAtIndex:0]
1189 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1195 @protocol ProgressDelegate
1196 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1197 - (void) setProgressTitle:(NSString *)title;
1198 - (void) setProgressPercent:(float)percent;
1199 - (void) startProgress;
1200 - (void) addProgressOutput:(NSString *)output;
1201 - (bool) isCancelling:(size_t)received;
1204 @protocol ConfigurationDelegate
1205 - (void) repairWithSelector:(SEL)selector;
1206 - (void) setConfigurationData:(NSString *)data;
1211 @protocol CydiaDelegate
1212 - (void) setPackageView:(PackageView *)view;
1213 - (void) clearPackage:(Package *)package;
1214 - (void) installPackage:(Package *)package;
1215 - (void) removePackage:(Package *)package;
1216 - (void) slideUp:(UIActionSheet *)alert;
1217 - (void) distUpgrade;
1218 - (void) updateData;
1220 - (void) askForSettings;
1221 - (UIProgressHUD *) addProgressHUD;
1222 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1223 - (RVPage *) pageForPackage:(NSString *)name;
1224 - (PackageView *) packageView;
1228 /* Status Delegation {{{ */
1230 public pkgAcquireStatus
1233 _transient NSObject<ProgressDelegate> *delegate_;
1241 void setDelegate(id delegate) {
1242 delegate_ = delegate;
1245 virtual bool MediaChange(std::string media, std::string drive) {
1249 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1252 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1253 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1254 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1257 virtual void Done(pkgAcquire::ItemDesc &item) {
1260 virtual void Fail(pkgAcquire::ItemDesc &item) {
1262 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1263 item.Owner->Status == pkgAcquire::Item::StatDone
1267 std::string &error(item.Owner->ErrorText);
1271 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1272 NSArray *fields([description componentsSeparatedByString:@" "]);
1273 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1275 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1276 withObject:[NSArray arrayWithObjects:
1277 [NSString stringWithUTF8String:error.c_str()],
1284 virtual bool Pulse(pkgAcquire *Owner) {
1285 bool value = pkgAcquireStatus::Pulse(Owner);
1288 double(CurrentBytes + CurrentItems) /
1289 double(TotalBytes + TotalItems)
1292 [delegate_ setProgressPercent:percent];
1293 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1296 virtual void Start() {
1297 [delegate_ startProgress];
1300 virtual void Stop() {
1304 /* Progress Delegation {{{ */
1309 _transient id<ProgressDelegate> delegate_;
1313 virtual void Update() {
1314 if (abs(Percent - percent_) > 2) {
1315 NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1319 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1320 [delegate_ setProgressPercent:(Percent / 100)];*/
1330 void setDelegate(id delegate) {
1331 delegate_ = delegate;
1334 virtual void Done() {
1336 //[delegate_ setProgressPercent:1];
1341 /* Database Interface {{{ */
1342 typedef std::map< unsigned long, _H<Source> > SourceMap;
1344 @interface Database : NSObject {
1350 pkgCacheFile cache_;
1351 pkgDepCache::Policy *policy_;
1352 pkgRecords *records_;
1353 pkgProblemResolver *resolver_;
1354 pkgAcquire *fetcher_;
1356 SPtr<pkgPackageManager> manager_;
1357 pkgSourceList *list_;
1360 NSMutableArray *packages_;
1362 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1371 + (Database *) sharedInstance;
1374 - (void) _readCydia:(NSNumber *)fd;
1375 - (void) _readStatus:(NSNumber *)fd;
1376 - (void) _readOutput:(NSNumber *)fd;
1380 - (Package *) packageWithName:(NSString *)name;
1382 - (pkgCacheFile &) cache;
1383 - (pkgDepCache::Policy *) policy;
1384 - (pkgRecords *) records;
1385 - (pkgProblemResolver *) resolver;
1386 - (pkgAcquire &) fetcher;
1387 - (pkgSourceList &) list;
1388 - (NSArray *) packages;
1389 - (NSArray *) sources;
1390 - (void) reloadData;
1398 - (void) setVisible;
1400 - (NSString *) updateWithStatus:(Status &)status;
1402 - (void) setDelegate:(id)delegate;
1403 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1407 /* Source Class {{{ */
1408 @interface Source : NSObject {
1409 CYString depiction_;
1410 CYString description_;
1416 CYString distribution_;
1421 NSString *authority_;
1423 CYString defaultIcon_;
1425 NSDictionary *record_;
1429 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1431 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1433 - (NSString *) depictionForPackage:(NSString *)package;
1434 - (NSString *) supportForPackage:(NSString *)package;
1436 - (NSDictionary *) record;
1440 - (NSString *) distribution;
1441 - (NSString *) type;
1443 - (NSString *) host;
1445 - (NSString *) name;
1446 - (NSString *) description;
1447 - (NSString *) label;
1448 - (NSString *) origin;
1449 - (NSString *) version;
1451 - (NSString *) defaultIcon;
1455 @implementation Source
1459 distribution_.clear();
1462 description_.clear();
1468 defaultIcon_.clear();
1470 if (record_ != nil) {
1480 if (authority_ != nil) {
1481 [authority_ release];
1491 + (NSArray *) _attributeKeys {
1492 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1495 - (NSArray *) attributeKeys {
1496 return [[self class] _attributeKeys];
1499 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1500 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1503 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1506 trusted_ = index->IsTrusted();
1508 uri_.set(pool, index->GetURI());
1509 distribution_.set(pool, index->GetDist());
1510 type_.set(pool, index->GetType());
1512 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1513 if (dindex != NULL) {
1515 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1518 pkgTagFile tags(&fd);
1520 pkgTagSection section;
1527 {"default-icon", &defaultIcon_},
1528 {"depiction", &depiction_},
1529 {"description", &description_},
1531 {"origin", &origin_},
1532 {"support", &support_},
1533 {"version", &version_},
1536 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1537 const char *start, *end;
1539 if (section.Find(names[i].name_, start, end)) {
1540 CYString &value(*names[i].value_);
1541 value.set(pool, start, end - start);
1547 record_ = [Sources_ objectForKey:[self key]];
1549 record_ = [record_ retain];
1551 NSURL *url([NSURL URLWithString:uri_]);
1555 host_ = [[host_ lowercaseString] retain];
1558 authority_ = [host_ retain];
1560 authority_ = [url path];
1563 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1564 if ((self = [super init]) != nil) {
1565 [self setMetaIndex:index inPool:pool];
1569 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1570 NSDictionary *lhr = [self record];
1571 NSDictionary *rhr = [source record];
1574 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1576 NSString *lhs = [self name];
1577 NSString *rhs = [source name];
1579 if ([lhs length] != 0 && [rhs length] != 0) {
1580 unichar lhc = [lhs characterAtIndex:0];
1581 unichar rhc = [rhs characterAtIndex:0];
1583 if (isalpha(lhc) && !isalpha(rhc))
1584 return NSOrderedAscending;
1585 else if (!isalpha(lhc) && isalpha(rhc))
1586 return NSOrderedDescending;
1589 return [lhs compare:rhs options:LaxCompareOptions_];
1592 - (NSString *) depictionForPackage:(NSString *)package {
1593 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1596 - (NSString *) supportForPackage:(NSString *)package {
1597 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1600 - (NSDictionary *) record {
1608 - (NSString *) uri {
1612 - (NSString *) distribution {
1613 return distribution_;
1616 - (NSString *) type {
1620 - (NSString *) key {
1621 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1624 - (NSString *) host {
1628 - (NSString *) name {
1629 return origin_.empty() ? authority_ : origin_;
1632 - (NSString *) description {
1633 return description_;
1636 - (NSString *) label {
1637 return label_.empty() ? authority_ : label_;
1640 - (NSString *) origin {
1644 - (NSString *) version {
1648 - (NSString *) defaultIcon {
1649 return defaultIcon_;
1654 /* Relationship Class {{{ */
1655 @interface Relationship : NSObject {
1660 - (NSString *) type;
1662 - (NSString *) name;
1666 @implementation Relationship
1674 - (NSString *) type {
1682 - (NSString *) name {
1689 /* Package Class {{{ */
1690 @interface Package : NSObject {
1694 pkgCache::VerIterator version_;
1695 pkgCache::PkgIterator iterator_;
1696 _transient Database *database_;
1697 pkgCache::VerFileIterator file_;
1704 NSString *section$_;
1710 CYString installed_;
1716 CYString depiction_;
1727 NSMutableArray *tags_;
1730 NSArray *relationships_;
1732 NSMutableDictionary *metadata_;
1733 _transient NSDate *firstSeen_;
1734 _transient NSDate *lastSeen_;
1738 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1739 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1741 - (pkgCache::PkgIterator) iterator;
1744 - (NSString *) section;
1745 - (NSString *) simpleSection;
1747 - (NSString *) longSection;
1748 - (NSString *) shortSection;
1752 - (Address *) maintainer;
1754 - (NSString *) longDescription;
1755 - (NSString *) shortDescription;
1758 - (NSMutableDictionary *) metadata;
1760 - (BOOL) subscribed;
1763 - (NSString *) latest;
1764 - (NSString *) installed;
1765 - (BOOL) uninstalled;
1768 - (BOOL) upgradableAndEssential:(BOOL)essential;
1771 - (BOOL) unfiltered;
1775 - (BOOL) halfConfigured;
1776 - (BOOL) halfInstalled;
1778 - (NSString *) mode;
1780 - (void) setVisible;
1783 - (NSString *) name;
1785 - (NSString *) homepage;
1786 - (NSString *) depiction;
1787 - (Address *) author;
1789 - (NSString *) support;
1791 - (NSArray *) files;
1792 - (NSArray *) relationships;
1793 - (NSArray *) warnings;
1794 - (NSArray *) applications;
1796 - (Source *) source;
1797 - (NSString *) role;
1799 - (BOOL) matches:(NSString *)text;
1801 - (bool) hasSupportingRole;
1802 - (BOOL) hasTag:(NSString *)tag;
1803 - (NSString *) primaryPurpose;
1804 - (NSArray *) purposes;
1805 - (bool) isCommercial;
1807 - (CYString &) cyname;
1809 - (uint32_t) compareBySection:(NSArray *)sections;
1811 - (uint32_t) compareForChanges;
1816 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1817 - (bool) isInstalledAndVisible:(NSNumber *)number;
1818 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1819 - (bool) isVisibleInSource:(Source *)source;
1823 uint32_t PackageChangesRadix(Package *self, void *) {
1828 uint32_t timestamp : 30;
1829 uint32_t ignored : 1;
1830 uint32_t upgradable : 1;
1834 bool upgradable([self upgradableAndEssential:YES]);
1835 value.bits.upgradable = upgradable ? 1 : 0;
1838 value.bits.timestamp = 0;
1839 value.bits.ignored = [self ignored] ? 0 : 1;
1840 value.bits.upgradable = 1;
1842 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1843 value.bits.ignored = 0;
1844 value.bits.upgradable = 0;
1847 return _not(uint32_t) - value.key;
1850 _finline static void Stifle(uint8_t &value) {
1853 uint32_t PackagePrefixRadix(Package *self, void *context) {
1854 size_t offset(reinterpret_cast<size_t>(context));
1855 CYString &name([self cyname]);
1857 size_t size(name.size());
1860 char *text(name.data());
1863 if (!isdigit(text[0]))
1867 while (size != digits && isdigit(text[digits]))
1877 if (offset == 0 && zeros != 0) {
1878 memset(data, '0', zeros);
1879 memcpy(data + zeros, text, 4 - zeros);
1881 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1882 if (size <= offset - zeros)
1885 text += offset - zeros;
1886 size -= offset - zeros;
1889 memcpy(data, text, 4);
1891 memcpy(data, text, size);
1892 memset(data + size, 0, 4 - size);
1895 for (size_t i(0); i != 4; ++i)
1896 if (isalpha(data[i]))
1901 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1903 /* XXX: ntohl may be more honest */
1904 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1907 CYString &(*PackageName)(Package *self, SEL sel);
1909 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1910 _profile(PackageNameCompare)
1911 CYString &lhi(PackageName(lhs, @selector(cyname)));
1912 CYString &rhi(PackageName(rhs, @selector(cyname)));
1913 CFStringRef lhn(lhi), rhn(rhi);
1915 _profile(PackageNameCompare$NumbersLast)
1916 if (!lhi.empty() && !rhi.empty()) {
1917 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1918 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1919 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1920 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1921 return lha ? NSOrderedAscending : NSOrderedDescending;
1925 CFIndex length = CFStringGetLength(lhn);
1927 _profile(PackageNameCompare$Compare)
1928 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1933 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1934 return PackageNameCompare(*lhs, *rhs, context);
1937 struct PackageNameOrdering :
1938 std::binary_function<Package *, Package *, bool>
1940 _finline bool operator ()(Package *lhs, Package *rhs) const {
1941 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1945 @implementation Package
1947 - (NSString *) description {
1948 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1954 if (section$_ != nil)
1955 [section$_ release];
1960 if (sponsor$_ != nil)
1961 [sponsor$_ release];
1962 if (author$_ != nil)
1969 if (relationships_ != nil)
1970 [relationships_ release];
1971 if (metadata_ != nil)
1972 [metadata_ release];
1977 + (NSString *) webScriptNameForSelector:(SEL)selector {
1978 if (selector == @selector(hasTag:))
1984 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1985 return [self webScriptNameForSelector:selector] == nil;
1988 + (NSArray *) _attributeKeys {
1989 return [NSArray arrayWithObjects:@"applications", @"author", @"depiction", @"longDescription", @"essential", @"homepage", @"icon", @"id", @"installed", @"latest", @"longSection", @"maintainer", @"mode", @"name", @"purposes", @"section", @"shortDescription", @"shortSection", @"simpleSection", @"size", @"source", @"sponsor", @"support", @"warnings", nil];
1992 - (NSArray *) attributeKeys {
1993 return [[self class] _attributeKeys];
1996 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1997 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2007 _profile(Package$parse)
2008 pkgRecords::Parser *parser;
2010 _profile(Package$parse$Lookup)
2011 parser = &[database_ records]->Lookup(file_);
2016 _profile(Package$parse$Find)
2022 {"depiction", &depiction_},
2023 {"homepage", &homepage_},
2024 {"website", &website},
2026 {"support", &support_},
2027 {"sponsor", &sponsor_},
2028 {"author", &author_},
2031 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2032 const char *start, *end;
2034 if (parser->Find(names[i].name_, start, end)) {
2035 CYString &value(*names[i].value_);
2036 _profile(Package$parse$Value)
2037 value.set(pool_, start, end - start);
2043 _profile(Package$parse$Tagline)
2044 const char *start, *end;
2045 if (parser->ShortDesc(start, end)) {
2046 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2049 while (stop != start && stop[-1] == '\r')
2051 tagline_.set(pool_, start, stop - start);
2055 _profile(Package$parse$Retain)
2056 if (homepage_.empty())
2057 homepage_ = website;
2058 if (homepage_ == depiction_)
2064 - (void) setVisible {
2065 visible_ = required_ && [self hasSupportingRole] && [self unfiltered];
2068 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2069 if ((self = [super init]) != nil) {
2070 _profile(Package$initWithVersion)
2071 @synchronized (database) {
2072 era_ = [database era];
2076 iterator_ = version.ParentPkg();
2077 database_ = database;
2079 _profile(Package$initWithVersion$Latest)
2080 latest_ = (NSString *) StripVersion(version_.VerStr());
2083 pkgCache::VerIterator current;
2084 _profile(Package$initWithVersion$Versions)
2085 current = iterator_.CurrentVer();
2087 installed_.set(pool_, StripVersion_(current.VerStr()));
2089 if (!version_.end())
2090 file_ = version_.FileList();
2092 pkgCache &cache([database_ cache]);
2093 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2097 _profile(Package$initWithVersion$Name)
2098 id_.set(pool_, iterator_.Name());
2099 name_.set(pool, iterator_.Display());
2103 _profile(Package$initWithVersion$Source)
2104 source_ = [database_ getSource:file_.File()];
2113 _profile(Package$initWithVersion$Tags)
2114 pkgCache::TagIterator tag(iterator_.TagList());
2116 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2118 const char *name(tag.Name());
2119 [tags_ addObject:(NSString *)CFCString(name)];
2120 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2121 role_ = (NSString *) CFCString(name + 6);
2122 if (required_ && strncmp(name, "require::", 9) == 0 && (
2127 } while (!tag.end());
2131 bool changed(false);
2132 NSString *key([id_ lowercaseString]);
2134 _profile(Package$initWithVersion$Metadata)
2135 metadata_ = [Packages_ objectForKey:key];
2137 if (metadata_ == nil) {
2140 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2141 firstSeen_, @"FirstSeen",
2142 latest_, @"LastVersion",
2147 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2148 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2150 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2151 subscribed_ = [subscribed boolValue];
2153 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2155 if (firstSeen_ == nil) {
2156 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2157 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2161 if (version == nil) {
2162 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2165 if (![version isEqualToString:latest_]) {
2166 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2168 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2173 metadata_ = [metadata_ retain];
2176 [Packages_ setObject:metadata_ forKey:key];
2181 _profile(Package$initWithVersion$Section)
2182 section_.set(pool_, iterator_.Section());
2185 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2187 } _end } return self;
2190 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2191 @synchronized ([Database class]) {
2192 pkgCache::VerIterator version;
2194 _profile(Package$packageWithIterator$GetCandidateVer)
2195 version = [database policy]->GetCandidateVer(iterator);
2201 return [[[Package alloc]
2202 initWithVersion:version
2209 - (pkgCache::PkgIterator) iterator {
2213 - (NSString *) section {
2214 if (section$_ == nil) {
2215 if (section_.empty())
2218 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2219 NSString *name(section_);
2222 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2223 if (NSString *rename = [value objectForKey:@"Rename"]) {
2228 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2232 - (NSString *) simpleSection {
2233 if (NSString *section = [self section])
2234 return Simplify(section);
2239 - (NSString *) longSection {
2240 return LocalizeSection([self section]);
2243 - (NSString *) shortSection {
2244 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2247 - (NSString *) uri {
2250 pkgIndexFile *index;
2251 pkgCache::PkgFileIterator file(file_.File());
2252 if (![database_ list].FindIndex(file, index))
2254 return [NSString stringWithUTF8String:iterator_->Path];
2255 //return [NSString stringWithUTF8String:file.Site()];
2256 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2260 - (Address *) maintainer {
2263 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2264 const std::string &maintainer(parser->Maintainer());
2265 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2269 return version_.end() ? 0 : version_->InstalledSize;
2272 - (NSString *) longDescription {
2275 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2276 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2278 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2279 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2280 if ([lines count] < 2)
2283 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2284 for (size_t i(1), e([lines count]); i != e; ++i) {
2285 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2286 [trimmed addObject:trim];
2289 return [trimmed componentsJoinedByString:@"\n"];
2292 - (NSString *) shortDescription {
2297 _profile(Package$index)
2298 CFStringRef name((CFStringRef) [self name]);
2299 if (CFStringGetLength(name) == 0)
2301 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2302 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2304 return toupper(character);
2308 - (NSMutableDictionary *) metadata {
2313 if (subscribed_ && lastSeen_ != nil)
2318 - (BOOL) subscribed {
2323 NSDictionary *metadata([self metadata]);
2324 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2325 return [ignored boolValue];
2330 - (NSString *) latest {
2334 - (NSString *) installed {
2338 - (BOOL) uninstalled {
2339 return installed_.empty();
2343 return !version_.end();
2346 - (BOOL) upgradableAndEssential:(BOOL)essential {
2347 _profile(Package$upgradableAndEssential)
2348 pkgCache::VerIterator current(iterator_.CurrentVer());
2350 return essential && essential_ && visible_;
2352 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2356 - (BOOL) essential {
2361 return [database_ cache][iterator_].InstBroken();
2364 - (BOOL) unfiltered {
2365 NSString *section([self section]);
2366 return section == nil || isSectionVisible(section);
2374 unsigned char current(iterator_->CurrentState);
2375 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2378 - (BOOL) halfConfigured {
2379 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2382 - (BOOL) halfInstalled {
2383 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2387 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2388 return state.Mode != pkgDepCache::ModeKeep;
2391 - (NSString *) mode {
2392 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2394 switch (state.Mode) {
2395 case pkgDepCache::ModeDelete:
2396 if ((state.iFlags & pkgDepCache::Purge) != 0)
2400 case pkgDepCache::ModeKeep:
2401 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2402 return @"REINSTALL";
2403 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2407 case pkgDepCache::ModeInstall:
2408 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2409 return @"REINSTALL";
2410 else*/ switch (state.Status) {
2412 return @"DOWNGRADE";
2418 return @"NEW_INSTALL";
2431 - (NSString *) name {
2432 return name_.empty() ? id_ : name_;
2435 - (UIImage *) icon {
2436 NSString *section = [self simpleSection];
2440 if ([icon_ hasPrefix:@"file:///"])
2441 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2442 if (icon == nil) if (section != nil)
2443 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2444 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2445 if ([dicon hasPrefix:@"file:///"])
2446 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2448 icon = [UIImage applicationImageNamed:@"unknown.png"];
2452 - (NSString *) homepage {
2456 - (NSString *) depiction {
2457 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2460 - (Address *) sponsor {
2461 if (sponsor$_ == nil) {
2462 if (sponsor_.empty())
2464 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2468 - (Address *) author {
2469 if (author$_ == nil) {
2470 if (author_.empty())
2472 author$_ = [[Address addressWithString:author_] retain];
2476 - (NSString *) support {
2477 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2480 - (NSArray *) files {
2481 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2482 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2485 fin.open([path UTF8String]);
2490 while (std::getline(fin, line))
2491 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2496 - (NSArray *) relationships {
2497 return relationships_;
2500 - (NSArray *) warnings {
2501 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2502 const char *name(iterator_.Name());
2504 size_t length(strlen(name));
2505 if (length < 2) invalid:
2506 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2507 else for (size_t i(0); i != length; ++i)
2509 /* XXX: technically this is not allowed */
2510 (name[i] < 'A' || name[i] > 'Z') &&
2511 (name[i] < 'a' || name[i] > 'z') &&
2512 (name[i] < '0' || name[i] > '9') &&
2513 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2516 if (strcmp(name, "cydia") != 0) {
2519 bool _private = false;
2522 bool repository = [[self section] isEqualToString:@"Repositories"];
2524 if (NSArray *files = [self files])
2525 for (NSString *file in files)
2526 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2528 else if (!user && [file isEqualToString:@"/User"])
2530 else if (!_private && [file isEqualToString:@"/private"])
2532 else if (!stash && [file isEqualToString:@"/var/stash"])
2535 /* XXX: this is not sensitive enough. only some folders are valid. */
2536 if (cydia && !repository)
2537 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2539 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2541 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2543 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2546 return [warnings count] == 0 ? nil : warnings;
2549 - (NSArray *) applications {
2550 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2552 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2554 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2555 if (NSArray *files = [self files])
2556 for (NSString *file in files)
2557 if (application_r(file)) {
2558 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2559 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2560 if ([id isEqualToString:me])
2563 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2565 display = application_r[1];
2567 NSString *bundle([file stringByDeletingLastPathComponent]);
2568 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2569 if (icon == nil || [icon length] == 0)
2571 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2573 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2574 [applications addObject:application];
2576 [application addObject:id];
2577 [application addObject:display];
2578 [application addObject:url];
2581 return [applications count] == 0 ? nil : applications;
2584 - (Source *) source {
2586 @synchronized (database_) {
2587 if ([database_ era] != era_ || file_.end())
2590 source_ = [database_ getSource:file_.File()];
2602 - (NSString *) role {
2606 - (BOOL) matches:(NSString *)text {
2612 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2613 if (range.location != NSNotFound)
2616 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2617 if (range.location != NSNotFound)
2620 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2621 if (range.location != NSNotFound)
2627 - (bool) hasSupportingRole {
2630 if ([role_ isEqualToString:@"enduser"])
2632 if ([Role_ isEqualToString:@"User"])
2634 if ([role_ isEqualToString:@"hacker"])
2636 if ([Role_ isEqualToString:@"Hacker"])
2638 if ([role_ isEqualToString:@"developer"])
2640 if ([Role_ isEqualToString:@"Developer"])
2645 - (BOOL) hasTag:(NSString *)tag {
2646 return tags_ == nil ? NO : [tags_ containsObject:tag];
2649 - (NSString *) primaryPurpose {
2650 for (NSString *tag in tags_)
2651 if ([tag hasPrefix:@"purpose::"])
2652 return [tag substringFromIndex:9];
2656 - (NSArray *) purposes {
2657 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2658 for (NSString *tag in tags_)
2659 if ([tag hasPrefix:@"purpose::"])
2660 [purposes addObject:[tag substringFromIndex:9]];
2661 return [purposes count] == 0 ? nil : purposes;
2664 - (bool) isCommercial {
2665 return [self hasTag:@"cydia::commercial"];
2668 - (CYString &) cyname {
2669 return name_.empty() ? id_ : name_;
2672 - (uint32_t) compareBySection:(NSArray *)sections {
2673 NSString *section([self section]);
2674 for (size_t i(0), e([sections count]); i != e; ++i) {
2675 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2679 return _not(uint32_t);
2682 - (uint32_t) compareForChanges {
2687 uint32_t timestamp : 30;
2688 uint32_t ignored : 1;
2689 uint32_t upgradable : 1;
2693 bool upgradable([self upgradableAndEssential:YES]);
2694 value.bits.upgradable = upgradable ? 1 : 0;
2697 value.bits.timestamp = 0;
2698 value.bits.ignored = [self ignored] ? 0 : 1;
2699 value.bits.upgradable = 1;
2701 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2702 value.bits.ignored = 0;
2703 value.bits.upgradable = 0;
2706 return _not(uint32_t) - value.key;
2710 pkgProblemResolver *resolver = [database_ resolver];
2711 resolver->Clear(iterator_);
2712 resolver->Protect(iterator_);
2716 pkgProblemResolver *resolver = [database_ resolver];
2717 resolver->Clear(iterator_);
2718 resolver->Protect(iterator_);
2719 pkgCacheFile &cache([database_ cache]);
2720 cache->MarkInstall(iterator_, false);
2721 pkgDepCache::StateCache &state((*cache)[iterator_]);
2722 if (!state.Install())
2723 cache->SetReInstall(iterator_, true);
2727 pkgProblemResolver *resolver = [database_ resolver];
2728 resolver->Clear(iterator_);
2729 resolver->Protect(iterator_);
2730 resolver->Remove(iterator_);
2731 [database_ cache]->MarkDelete(iterator_, true);
2734 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2735 _profile(Package$isUnfilteredAndSearchedForBy)
2738 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2739 value &= [self unfiltered];
2742 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2743 value &= [self matches:search];
2750 - (bool) isInstalledAndVisible:(NSNumber *)number {
2751 return (![number boolValue] || [self visible]) && ![self uninstalled];
2754 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2755 NSString *section = [self section];
2759 [self uninstalled] && (
2761 section == nil && [name length] == 0 ||
2762 [name isEqualToString:section]
2766 - (bool) isVisibleInSource:(Source *)source {
2767 return [self source] == source && [self visible];
2772 /* Section Class {{{ */
2773 @interface Section : NSObject {
2778 NSString *localized_;
2781 - (NSComparisonResult) compareByLocalized:(Section *)section;
2782 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2783 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2784 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2785 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2786 - (NSString *) name;
2793 - (void) addToCount;
2795 - (void) setCount:(size_t)count;
2796 - (NSString *) localized;
2800 @implementation Section
2804 if (localized_ != nil)
2805 [localized_ release];
2809 - (NSComparisonResult) compareByLocalized:(Section *)section {
2810 NSString *lhs(localized_);
2811 NSString *rhs([section localized]);
2813 /*if ([lhs length] != 0 && [rhs length] != 0) {
2814 unichar lhc = [lhs characterAtIndex:0];
2815 unichar rhc = [rhs characterAtIndex:0];
2817 if (isalpha(lhc) && !isalpha(rhc))
2818 return NSOrderedAscending;
2819 else if (!isalpha(lhc) && isalpha(rhc))
2820 return NSOrderedDescending;
2823 return [lhs compare:rhs options:LaxCompareOptions_];
2826 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2827 if ((self = [self initWithName:name localize:NO]) != nil) {
2828 if (localized != nil)
2829 localized_ = [localized retain];
2833 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2834 return [self initWithName:name row:0 localize:localize];
2837 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2838 if ((self = [super init]) != nil) {
2839 name_ = [name retain];
2843 localized_ = [LocalizeSection(name_) retain];
2847 /* XXX: localize the index thingees */
2848 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2849 if ((self = [super init]) != nil) {
2850 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2856 - (NSString *) name {
2876 - (void) addToCount {
2880 - (void) setCount:(size_t)count {
2884 - (NSString *) localized {
2891 /* Database Implementation {{{ */
2892 @implementation Database
2894 + (Database *) sharedInstance {
2895 static Database *instance;
2896 if (instance == nil)
2897 instance = [[Database alloc] init];
2907 NSRecycleZone(zone_);
2908 // XXX: malloc_destroy_zone(zone_);
2909 apr_pool_destroy(pool_);
2913 - (void) _readCydia:(NSNumber *)fd { _pooled
2914 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2915 std::istream is(&ib);
2918 static Pcre finish_r("^finish:([^:]*)$");
2920 while (std::getline(is, line)) {
2921 const char *data(line.c_str());
2922 size_t size = line.size();
2923 lprintf("C:%s\n", data);
2925 if (finish_r(data, size)) {
2926 NSString *finish = finish_r[1];
2927 int index = [Finishes_ indexOfObject:finish];
2928 if (index != INT_MAX && index > Finish_)
2936 - (void) _readStatus:(NSNumber *)fd { _pooled
2937 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2938 std::istream is(&ib);
2941 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2942 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2944 while (std::getline(is, line)) {
2945 const char *data(line.c_str());
2946 size_t size = line.size();
2947 lprintf("S:%s\n", data);
2949 if (conffile_r(data, size)) {
2950 [delegate_ setConfigurationData:conffile_r[1]];
2951 } else if (strncmp(data, "status: ", 8) == 0) {
2952 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2953 [delegate_ setProgressTitle:string];
2954 } else if (pmstatus_r(data, size)) {
2955 std::string type([pmstatus_r[1] UTF8String]);
2956 NSString *id = pmstatus_r[2];
2958 float percent([pmstatus_r[3] floatValue]);
2959 [delegate_ setProgressPercent:(percent / 100)];
2961 NSString *string = pmstatus_r[4];
2963 if (type == "pmerror")
2964 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2965 withObject:[NSArray arrayWithObjects:string, id, nil]
2968 else if (type == "pmstatus") {
2969 [delegate_ setProgressTitle:string];
2970 } else if (type == "pmconffile")
2971 [delegate_ setConfigurationData:string];
2972 else _assert(false);
2973 } else _assert(false);
2979 - (void) _readOutput:(NSNumber *)fd { _pooled
2980 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2981 std::istream is(&ib);
2984 while (std::getline(is, line)) {
2985 lprintf("O:%s\n", line.c_str());
2986 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2996 - (Package *) packageWithName:(NSString *)name {
2997 @synchronized ([Database class]) {
2998 if (static_cast<pkgDepCache *>(cache_) == NULL)
3000 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3001 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3004 - (Database *) init {
3005 if ((self = [super init]) != nil) {
3012 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3013 apr_pool_create(&pool_, NULL);
3015 packages_ = [[NSMutableArray alloc] init];
3019 _assert(pipe(fds) != -1);
3022 _config->Set("APT::Keep-Fds::", cydiafd_);
3023 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3026 detachNewThreadSelector:@selector(_readCydia:)
3028 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3031 _assert(pipe(fds) != -1);
3035 detachNewThreadSelector:@selector(_readStatus:)
3037 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3040 _assert(pipe(fds) != -1);
3041 _assert(dup2(fds[0], 0) != -1);
3042 _assert(close(fds[0]) != -1);
3044 input_ = fdopen(fds[1], "a");
3046 _assert(pipe(fds) != -1);
3047 _assert(dup2(fds[1], 1) != -1);
3048 _assert(close(fds[1]) != -1);
3051 detachNewThreadSelector:@selector(_readOutput:)
3053 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3058 - (pkgCacheFile &) cache {
3062 - (pkgDepCache::Policy *) policy {
3066 - (pkgRecords *) records {
3070 - (pkgProblemResolver *) resolver {
3074 - (pkgAcquire &) fetcher {
3078 - (pkgSourceList &) list {
3082 - (NSArray *) packages {
3086 - (NSArray *) sources {
3087 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3088 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3089 [sources addObject:i->second];
3093 - (NSArray *) issues {
3094 if (cache_->BrokenCount() == 0)
3097 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3099 for (Package *package in packages_) {
3100 if (![package broken])
3102 pkgCache::PkgIterator pkg([package iterator]);
3104 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3105 [entry addObject:[package name]];
3106 [issues addObject:entry];
3108 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3112 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3113 pkgCache::DepIterator start;
3114 pkgCache::DepIterator end;
3115 dep.GlobOr(start, end); // ++dep
3117 if (!cache_->IsImportantDep(end))
3119 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3122 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3123 [entry addObject:failure];
3124 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3126 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3127 if (Package *package = [self packageWithName:name])
3128 name = [package name];
3129 [failure addObject:name];
3131 pkgCache::PkgIterator target(start.TargetPkg());
3132 if (target->ProvidesList != 0)
3133 [failure addObject:@"?"];
3135 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3137 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3138 else if (!cache_[target].CandidateVerIter(cache_).end())
3139 [failure addObject:@"-"];
3140 else if (target->ProvidesList == 0)
3141 [failure addObject:@"!"];
3143 [failure addObject:@"%"];
3147 if (start.TargetVer() != 0)
3148 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3159 - (void) reloadData { _pooled
3160 @synchronized ([Database class]) {
3162 @synchronized (self) {
3166 [packages_ removeAllObjects];
3192 apr_pool_clear(pool_);
3193 NSRecycleZone(zone_);
3195 int chk(creat("/tmp/cydia.chk", 0644));
3200 if (!cache_.Open(progress_, true)) {
3202 if (!_error->PopMessage(error))
3205 lprintf("cache_.Open():[%s]\n", error.c_str());
3207 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3208 [delegate_ repairWithSelector:@selector(configure)];
3209 else if (error == "The package lists or status file could not be parsed or opened.")
3210 [delegate_ repairWithSelector:@selector(update)];
3211 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3212 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3213 // else if (error == "The list of sources could not be read.")
3214 else _assert(false);
3220 unlink("/tmp/cydia.chk");
3222 now_ = [[NSDate date] retain];
3224 policy_ = new pkgDepCache::Policy();
3225 records_ = new pkgRecords(cache_);
3226 resolver_ = new pkgProblemResolver(cache_);
3227 fetcher_ = new pkgAcquire(&status_);
3230 list_ = new pkgSourceList();
3231 _assert(list_->ReadMainList());
3233 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3234 _assert(pkgApplyStatus(cache_));
3236 if (cache_->BrokenCount() != 0) {
3237 _assert(pkgFixBroken(cache_));
3238 _assert(cache_->BrokenCount() == 0);
3239 _assert(pkgMinimizeUpgrade(cache_));
3244 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3245 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3246 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3247 // XXX: this could be more intelligent
3248 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3249 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3251 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3258 /*std::vector<Package *> packages;
3259 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3260 [packages_ release];
3265 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3266 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3267 //packages.push_back(package);
3268 [packages_ addObject:package];
3272 /*if (packages.empty())
3273 packages_ = [[NSArray alloc] init];
3275 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3278 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3279 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3280 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3288 /*if (!packages.empty())
3289 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3290 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3292 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3294 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3296 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3302 - (void) configure {
3303 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3304 system([dpkg UTF8String]);
3312 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3313 _assert(!_error->PendingError());
3316 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3319 public pkgArchiveCleaner
3322 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3327 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3329 while (_error->PopMessage(error))
3330 lprintf("ArchiveCleaner: %s\n", error.c_str());
3335 fetcher_->Shutdown();
3337 pkgRecords records(cache_);
3339 lock_ = new FileFd();
3340 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3341 _assert(!_error->PendingError());
3344 // XXX: explain this with an error message
3345 _assert(list.ReadMainList());
3347 manager_ = (_system->CreatePM(cache_));
3348 _assert(manager_->GetArchives(fetcher_, &list, &records));
3349 _assert(!_error->PendingError());
3353 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3355 _assert(list.ReadMainList());
3356 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3357 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3360 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3365 bool failed = false;
3366 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3367 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3369 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3372 std::string uri = (*item)->DescURI();
3373 std::string error = (*item)->ErrorText;
3375 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3378 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3379 withObject:[NSArray arrayWithObjects:
3380 [NSString stringWithUTF8String:error.c_str()],
3392 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3394 if (_error->PendingError()) {
3399 if (result == pkgPackageManager::Failed) {
3404 if (result != pkgPackageManager::Completed) {
3409 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3411 _assert(list.ReadMainList());
3412 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3413 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3416 if (![before isEqualToArray:after])
3421 _assert(pkgDistUpgrade(cache_));
3425 [self updateWithStatus:status_];
3428 - (void) setVisible {
3429 for (Package *package in packages_)
3430 [package setVisible];
3433 - (NSString *) updateWithStatus:(Status &)status {
3435 _assert(list.ReadMainList());
3438 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3440 if (_error->PendingError()) error: {
3442 if (!_error->PopMessage(error))
3445 return [NSString stringWithUTF8String:error.c_str()];
3448 if (!ListUpdate(status, list, PulseInterval_))
3451 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3457 - (void) setDelegate:(id)delegate {
3458 delegate_ = delegate;
3459 status_.setDelegate(delegate);
3460 progress_.setDelegate(delegate);
3463 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3464 SourceMap::const_iterator i(sources_.find(file->ID));
3465 return i == sources_.end() ? nil : i->second;
3471 /* Confirmation View {{{ */
3472 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3473 if (!iterator.end())
3474 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3475 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3477 pkgCache::PkgIterator package(dep.TargetPkg());
3480 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3487 /* Web Scripting {{{ */
3488 @interface CydiaObject : NSObject {
3492 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3495 @implementation CydiaObject
3498 [indirect_ release];
3502 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3503 if ((self = [super init]) != nil) {
3504 indirect_ = [indirect retain];
3508 + (NSArray *) _attributeKeys {
3509 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3512 - (NSArray *) attributeKeys {
3513 return [[self class] _attributeKeys];
3516 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3517 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3520 - (NSString *) device {
3521 return [[UIDevice currentDevice] uniqueIdentifier];
3524 #if 0 // XXX: implement!
3525 - (NSString *) mac {
3526 if (![indirect_ promptForSensitive:@"Mac Address"])
3530 - (NSString *) serial {
3531 if (![indirect_ promptForSensitive:@"Serial #"])
3535 - (NSString *) firewire {
3536 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3540 - (NSString *) imei {
3541 if (![indirect_ promptForSensitive:@"IMEI"])
3546 + (NSString *) webScriptNameForSelector:(SEL)selector {
3547 if (selector == @selector(close))
3549 else if (selector == @selector(getPackageById:))
3550 return @"getPackageById";
3551 else if (selector == @selector(setAutoPopup:))
3552 return @"setAutoPopup";
3553 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3554 return @"setButtonImage";
3555 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3556 return @"setButtonTitle";
3557 else if (selector == @selector(setFinishHook:))
3558 return @"setFinishHook";
3559 else if (selector == @selector(setPopupHook:))
3560 return @"setPopupHook";
3561 else if (selector == @selector(setSpecial:))
3562 return @"setSpecial";
3563 else if (selector == @selector(setViewportWidth:))
3564 return @"setViewportWidth";
3565 else if (selector == @selector(supports:))
3567 else if (selector == @selector(stringWithFormat:arguments:))
3569 else if (selector == @selector(localizedStringForKey:value:table:))
3571 else if (selector == @selector(du:))
3573 else if (selector == @selector(statfs:))
3579 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3580 return [self webScriptNameForSelector:selector] == nil;
3583 - (BOOL) supports:(NSString *)feature {
3584 return [feature isEqualToString:@"window.open"];
3587 - (Package *) getPackageById:(NSString *)id {
3588 Package *package([[Database sharedInstance] packageWithName:id]);
3593 - (NSArray *) statfs:(NSString *)path {
3596 if (path == nil || statfs([path UTF8String], &stat) == -1)
3599 return [NSArray arrayWithObjects:
3600 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3601 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3602 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3606 - (NSNumber *) du:(NSString *)path {
3607 NSNumber *value(nil);
3610 _assert(pipe(fds) != -1);
3612 pid_t pid(ExecFork());
3614 _assert(dup2(fds[1], 1) != -1);
3615 _assert(close(fds[0]) != -1);
3616 _assert(close(fds[1]) != -1);
3617 /* XXX: this should probably not use du */
3618 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3623 _assert(close(fds[1]) != -1);
3625 if (FILE *du = fdopen(fds[0], "r")) {
3627 while (fgets(line, sizeof(line), du) != NULL) {
3628 size_t length(strlen(line));
3629 while (length != 0 && line[length - 1] == '\n')
3630 line[--length] = '\0';
3631 if (char *tab = strchr(line, '\t')) {
3633 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3638 } else _assert(close(fds[0]));
3642 if (waitpid(pid, &status, 0) == -1)
3645 else _assert(false);
3654 - (void) setAutoPopup:(BOOL)popup {
3655 [indirect_ setAutoPopup:popup];
3658 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3659 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3662 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3663 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3666 - (void) setSpecial:(id)function {
3667 [indirect_ setSpecial:function];
3670 - (void) setFinishHook:(id)function {
3671 [indirect_ setFinishHook:function];
3674 - (void) setPopupHook:(id)function {
3675 [indirect_ setPopupHook:function];
3678 - (void) setViewportWidth:(float)width {
3679 [indirect_ setViewportWidth:width];
3682 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3683 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3684 unsigned count([arguments count]);
3686 for (unsigned i(0); i != count; ++i)
3687 values[i] = [arguments objectAtIndex:i];
3688 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3691 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3692 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3694 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3696 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3702 @interface CydiaBrowserView : BrowserView {
3703 CydiaObject *cydia_;
3708 @implementation CydiaBrowserView
3715 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3716 [super webView:sender didClearWindowObject:window forFrame:frame];
3717 [window setValue:cydia_ forKey:@"cydia"];
3720 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3721 if (System_ != NULL)
3722 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3723 if (Machine_ != NULL)
3724 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3725 if (UniqueID_ != nil)
3726 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
3728 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3731 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3732 NSMutableURLRequest *copy = [request mutableCopy];
3733 [self _setMoreHeaders:copy];
3737 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
3738 if ((self = [super initWithBook:book forWidth:width ofClass:[CydiaBrowserView class]]) != nil) {
3739 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3741 WebView *webview([webview_ webView]);
3743 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3745 NSString *application = package == nil ? @"Cydia" : [NSString
3746 stringWithFormat:@"Cydia/%@",
3751 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3753 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3754 if (Product_ != nil)
3755 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3757 [webview setApplicationNameForUserAgent:application];
3763 @protocol ConfirmationViewDelegate
3769 @interface ConfirmationView : CydiaBrowserView {
3770 _transient Database *database_;
3771 UIActionSheet *essential_;
3778 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3782 @implementation ConfirmationView
3789 if (essential_ != nil)
3790 [essential_ release];
3796 [book_ popFromSuperviewAnimated:YES];
3799 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3800 NSString *context([sheet context]);
3802 if ([context isEqualToString:@"remove"]) {
3810 [delegate_ confirm];
3817 } else if ([context isEqualToString:@"unable"]) {
3821 [super alertSheet:sheet buttonClicked:button];
3824 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3825 [super webView:sender didClearWindowObject:window forFrame:frame];
3826 [window setValue:changes_ forKey:@"changes"];
3827 [window setValue:issues_ forKey:@"issues"];
3828 [window setValue:sizes_ forKey:@"sizes"];
3831 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3832 if ((self = [super initWithBook:book]) != nil) {
3833 database_ = database;
3835 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3836 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3837 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3838 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3839 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3843 pkgDepCache::Policy *policy([database_ policy]);
3845 pkgCacheFile &cache([database_ cache]);
3846 NSArray *packages = [database_ packages];
3847 for (Package *package in packages) {
3848 pkgCache::PkgIterator iterator = [package iterator];
3849 pkgDepCache::StateCache &state(cache[iterator]);
3851 NSString *name([package name]);
3853 if (state.NewInstall())
3854 [installing addObject:name];
3855 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3856 [reinstalling addObject:name];
3857 else if (state.Upgrade())
3858 [upgrading addObject:name];
3859 else if (state.Downgrade())
3860 [downgrading addObject:name];
3861 else if (state.Delete()) {
3862 if ([package essential])
3864 [removing addObject:name];
3867 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3868 substrate_ |= DepSubstrate(iterator.CurrentVer());
3873 else if (Advanced_) {
3874 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
3876 essential_ = [[UIActionSheet alloc]
3877 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
3878 buttons:[NSArray arrayWithObjects:
3879 [NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")],
3880 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
3882 defaultButtonIndex:0
3887 [essential_ setDestructiveButtonIndex:1];
3888 [essential_ setBodyText:UCLocalize("REMOVING_ESSENTIALS_EX")];
3890 essential_ = [[UIActionSheet alloc]
3891 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
3892 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
3893 defaultButtonIndex:0
3898 [essential_ setBodyText:UCLocalize("UNABLE_TO_COMPLY_EX")];
3901 changes_ = [[NSArray alloc] initWithObjects:
3909 issues_ = [database_ issues];
3911 issues_ = [issues_ retain];
3913 sizes_ = [[NSArray alloc] initWithObjects:
3914 SizeString([database_ fetcher].FetchNeeded()),
3915 SizeString([database_ fetcher].PartialPresent()),
3916 SizeString([database_ cache]->UsrSize()),
3919 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3923 - (NSString *) backButtonTitle {
3924 return UCLocalize("CONFIRM");
3927 - (NSString *) leftButtonTitle {
3928 return [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")];
3931 - (id) rightButtonTitle {
3932 return issues_ != nil ? nil : [super rightButtonTitle];
3935 - (id) _rightButtonTitle {
3936 #if AlwaysReload || IgnoreInstall
3937 return [super _rightButtonTitle];
3939 return UCLocalize("CONFIRM");
3943 - (void) _leftButtonClicked {
3948 - (void) _rightButtonClicked {
3950 return [super _rightButtonClicked];
3952 if (essential_ != nil)
3953 [essential_ popupAlertAnimated:YES];
3957 [delegate_ confirm];
3965 /* Progress Data {{{ */
3966 @interface ProgressData : NSObject {
3972 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3979 @implementation ProgressData
3981 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3982 if ((self = [super init]) != nil) {
3983 selector_ = selector;
4003 /* Progress View {{{ */
4004 @interface ProgressView : UIView <
4005 ConfigurationDelegate,
4008 _transient Database *database_;
4010 UIView *background_;
4011 UITransitionView *transition_;
4013 UINavigationBar *navbar_;
4014 UIProgressBar *progress_;
4015 UITextView *output_;
4016 UITextLabel *status_;
4017 UIPushButton *close_;
4020 SHA1SumValue springlist_;
4021 SHA1SumValue notifyconf_;
4024 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
4025 - (void) setContentView:(UIView *)view;
4028 - (void) _retachThread;
4029 - (void) _detachNewThreadData:(ProgressData *)data;
4030 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4036 @protocol ProgressViewDelegate
4037 - (void) progressViewIsComplete:(ProgressView *)sender;
4040 @implementation ProgressView
4043 [transition_ setDelegate:nil];
4044 [navbar_ setDelegate:nil];
4047 if (background_ != nil)
4048 [background_ release];
4049 [transition_ release];
4052 [progress_ release];
4059 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
4060 if ((self = [super initWithFrame:frame]) != nil) {
4061 database_ = database;
4062 delegate_ = delegate;
4064 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
4065 [transition_ setDelegate:self];
4067 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
4069 background_ = [[UIView alloc] initWithFrame:[self bounds]];
4070 [background_ setBackgroundColor:[UIColor blackColor]];
4071 [self addSubview:background_];
4073 [self addSubview:transition_];
4075 CGSize navsize = [UINavigationBar defaultSize];
4076 CGRect navrect = {{0, 0}, navsize};
4078 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
4079 [overlay_ addSubview:navbar_];
4081 [navbar_ setBarStyle:1];
4082 [navbar_ setDelegate:self];
4084 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
4085 [navbar_ pushNavigationItem:navitem];
4087 CGRect bounds = [overlay_ bounds];
4088 CGSize prgsize = [UIProgressBar defaultSize];
4091 (bounds.size.width - prgsize.width) / 2,
4092 bounds.size.height - prgsize.height - 20
4095 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
4096 [progress_ setStyle:0];
4098 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
4100 bounds.size.height - prgsize.height - 50,
4101 bounds.size.width - 20,
4105 [status_ setColor:[UIColor whiteColor]];
4106 [status_ setBackgroundColor:[UIColor clearColor]];
4108 [status_ setCentersHorizontally:YES];
4109 //[status_ setFont:font];
4111 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
4113 navrect.size.height + 20,
4114 bounds.size.width - 20,
4115 bounds.size.height - navsize.height - 62 - navrect.size.height
4118 //[output_ setTextFont:@"Courier New"];
4119 [output_ setFont:[[output_ font] fontWithSize:12]];
4121 [output_ setTextColor:[UIColor whiteColor]];
4122 [output_ setBackgroundColor:[UIColor clearColor]];
4124 [output_ setMarginTop:0];
4125 [output_ setAllowsRubberBanding:YES];
4126 [output_ setEditable:NO];
4128 [overlay_ addSubview:output_];
4130 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
4132 bounds.size.height - prgsize.height - 50,
4133 bounds.size.width - 20,
4137 [close_ setAutosizesToFit:NO];
4138 [close_ setDrawsShadow:YES];
4139 [close_ setStretchBackground:YES];
4140 [close_ setEnabled:YES];
4142 UIFont *bold = [UIFont boldSystemFontOfSize:22];
4143 [close_ setTitleFont:bold];
4145 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4146 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4147 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4151 - (void) setContentView:(UIView *)view {
4152 view_ = [view retain];
4155 - (void) resetView {
4156 [transition_ transition:6 toView:view_];
4159 - (void) _checkError {
4160 if (_error->PendingError()) {
4162 if (!_error->PopMessage(error))
4165 UIActionSheet *sheet = [[[UIActionSheet alloc]
4166 initWithTitle:UCLocalize("ERROR")
4167 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4168 defaultButtonIndex:0
4173 [sheet setBodyText:[NSString stringWithUTF8String:error.c_str()]];
4174 [sheet popupAlertAnimated:YES];
4179 [delegate_ progressViewIsComplete:self];
4183 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4186 MMap mmap(file, MMap::ReadOnly);
4188 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4189 if (!(notifyconf_ == sha1.Result()))
4196 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4199 MMap mmap(file, MMap::ReadOnly);
4201 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4202 if (!(springlist_ == sha1.Result()))
4208 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break;
4209 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4210 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4211 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4212 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4215 #define ListCache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4216 #define IconCache_ "/User/Library/Caches/com.apple.springboard-imagecache-icons.plist"
4220 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ListCache_]) {
4221 [cache autorelease];
4223 NSFileManager *manager = [NSFileManager defaultManager];
4224 NSError *error = nil;
4226 id system = [cache objectForKey:@"System"];
4231 if (stat(ListCache_, &info) == -1)
4234 [system removeAllObjects];
4236 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4237 for (NSString *app in apps)
4238 if ([app hasSuffix:@".app"]) {
4239 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4240 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4241 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4243 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4244 [info setObject:path forKey:@"Path"];
4245 [info setObject:@"System" forKey:@"ApplicationType"];
4246 [system addInfoDictionary:info];
4252 [cache writeToFile:@ListCache_ atomically:YES];
4254 if (chown(ListCache_, info.st_uid, info.st_gid) == -1)
4256 if (chmod(ListCache_, info.st_mode) == -1)
4260 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4263 notify_post("com.apple.mobile.application_installed");
4265 [delegate_ setStatusBarShowsProgress:NO];
4268 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4269 NSString *context([sheet context]);
4271 if ([context isEqualToString:@"error"])
4273 else if ([context isEqualToString:@"_error"]) {
4276 } else if ([context isEqualToString:@"conffile"]) {
4277 FILE *input = [database_ input];
4281 fprintf(input, "N\n");
4285 fprintf(input, "Y\n");
4296 - (void) closeButtonPushed {
4305 [delegate_ suspendWithAnimation:YES];
4309 system("launchctl stop com.apple.SpringBoard");
4313 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4322 - (void) _retachThread {
4323 UINavigationItem *item = [navbar_ topItem];
4324 [item setTitle:UCLocalize("COMPLETE")];
4326 [overlay_ addSubview:close_];
4327 [progress_ removeFromSuperview];
4328 [status_ removeFromSuperview];
4333 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4334 [[data target] performSelector:[data selector] withObject:[data object]];
4337 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4340 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4341 UINavigationItem *item = [navbar_ topItem];
4342 [item setTitle:title];
4344 [status_ setText:nil];
4345 [output_ setText:@""];
4346 [progress_ setProgress:0];
4348 [close_ removeFromSuperview];
4349 [overlay_ addSubview:progress_];
4350 [overlay_ addSubview:status_];
4352 [delegate_ setStatusBarShowsProgress:YES];
4357 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4360 MMap mmap(file, MMap::ReadOnly);
4362 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4363 notifyconf_ = sha1.Result();
4369 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4372 MMap mmap(file, MMap::ReadOnly);
4374 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4375 springlist_ = sha1.Result();
4379 [transition_ transition:6 toView:overlay_];
4382 detachNewThreadSelector:@selector(_detachNewThreadData:)
4384 withObject:[[ProgressData alloc]
4385 initWithSelector:selector
4392 - (void) repairWithSelector:(SEL)selector {
4394 detachNewThreadSelector:selector
4397 title:UCLocalize("REPAIRING")
4401 - (void) setConfigurationData:(NSString *)data {
4403 performSelectorOnMainThread:@selector(_setConfigurationData:)
4409 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4410 Package *package = id == nil ? nil : [database_ packageWithName:id];
4412 UIActionSheet *sheet = [[[UIActionSheet alloc]
4413 initWithTitle:(package == nil ? id : [package name])
4414 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4415 defaultButtonIndex:0
4420 [sheet setBodyText:error];
4421 [sheet popupAlertAnimated:YES];
4424 - (void) setProgressTitle:(NSString *)title {
4426 performSelectorOnMainThread:@selector(_setProgressTitle:)
4432 - (void) setProgressPercent:(float)percent {
4434 performSelectorOnMainThread:@selector(_setProgressPercent:)
4435 withObject:[NSNumber numberWithFloat:percent]
4440 - (void) startProgress {
4443 - (void) addProgressOutput:(NSString *)output {
4445 performSelectorOnMainThread:@selector(_addProgressOutput:)
4451 - (bool) isCancelling:(size_t)received {
4455 - (void) _setConfigurationData:(NSString *)data {
4456 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4458 _assert(conffile_r(data));
4460 NSString *ofile = conffile_r[1];
4461 //NSString *nfile = conffile_r[2];
4463 UIActionSheet *sheet = [[[UIActionSheet alloc]
4464 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4465 buttons:[NSArray arrayWithObjects:
4466 UCLocalize("KEEP_OLD_COPY"),
4467 UCLocalize("ACCEPT_NEW_COPY"),
4468 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4470 defaultButtonIndex:0
4475 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4476 [sheet popupAlertAnimated:YES];
4479 - (void) _setProgressTitle:(NSString *)title {
4480 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4481 for (size_t i(0), e([words count]); i != e; ++i) {
4482 NSString *word([words objectAtIndex:i]);
4483 if (Package *package = [database_ packageWithName:word])
4484 [words replaceObjectAtIndex:i withObject:[package name]];
4487 [status_ setText:[words componentsJoinedByString:@" "]];
4490 - (void) _setProgressPercent:(NSNumber *)percent {
4491 [progress_ setProgress:[percent floatValue]];
4494 - (void) _addProgressOutput:(NSString *)output {
4495 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4496 CGSize size = [output_ contentSize];
4497 CGRect rect = {{0, size.height}, {size.width, 0}};
4498 [output_ scrollRectToVisible:rect animated:YES];
4501 - (BOOL) isRunning {
4508 /* Package Cell {{{ */
4509 @interface ContentView : UIView {
4510 _transient id delegate_;
4515 @interface PackageCell : UITableViewCell {
4518 NSString *description_;
4524 ContentView *content_;
4529 - (PackageCell *) init;
4530 - (void) setPackage:(Package *)package;
4532 + (int) heightForPackage:(Package *)package;
4533 - (void) drawContentRect:(CGRect)rect;
4537 @implementation ContentView
4539 - (id) initWithFrame:(CGRect)frame {
4540 if ((self = [super initWithFrame:frame]) != nil) {
4544 - (void) setDelegate:(id)delegate {
4545 delegate_ = delegate;
4548 - (void) drawRect:(CGRect)rect {
4549 [super drawRect:rect];
4550 [delegate_ drawContentRect:rect];
4555 @implementation PackageCell
4557 - (void) clearPackage {
4568 if (description_ != nil) {
4569 [description_ release];
4573 if (source_ != nil) {
4578 if (badge_ != nil) {
4588 [self clearPackage];
4595 return faded_ ? [self selectionPercent] : fade_;
4598 - (PackageCell *) init {
4599 CGRect frame(CGRectMake(0, 0, 320, 74));
4600 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4601 UIView *content([self contentView]);
4602 CGRect bounds([content bounds]);
4603 content_ = [[ContentView alloc] initWithFrame:bounds];
4604 [content_ setDelegate:self];
4605 [content_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
4606 [content_ setOpaque:YES];
4607 [content addSubview:content_];
4608 if ([self respondsToSelector:@selector(selectionPercent)])
4613 - (void) _setBackgroundColor {
4615 if (NSString *mode = [package_ mode]) {
4616 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4617 color = remove ? RemovingColor_ : InstallingColor_;
4619 color = [UIColor whiteColor];
4621 [content_ setBackgroundColor:color];
4622 [self setNeedsDisplay];
4625 - (void) setPackage:(Package *)package {
4626 [self clearPackage];
4629 Source *source = [package source];
4631 icon_ = [[package icon] retain];
4632 name_ = [[package name] retain];
4633 description_ = [[package shortDescription] retain];
4634 commercial_ = [package isCommercial];
4636 package_ = [package retain];
4638 NSString *label = nil;
4639 bool trusted = false;
4641 if (source != nil) {
4642 label = [source label];
4643 trusted = [source trusted];
4644 } else if ([[package id] isEqualToString:@"firmware"])
4645 label = UCLocalize("APPLE");
4647 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4649 NSString *from(label);
4651 NSString *section = [package simpleSection];
4652 if (section != nil && ![section isEqualToString:label]) {
4653 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4654 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4657 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4658 source_ = [from retain];
4660 if (NSString *purpose = [package primaryPurpose])
4661 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4662 badge_ = [badge_ retain];
4664 [self _setBackgroundColor];
4665 [content_ setNeedsDisplay];
4668 - (void) drawContentRect:(CGRect)rect {
4669 bool selected([self isSelected]);
4672 CGContextRef context(UIGraphicsGetCurrentContext());
4673 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4674 CGContextFillRect(context, rect);
4679 rect.size = [icon_ size];
4681 rect.size.width /= 2;
4682 rect.size.height /= 2;
4684 rect.origin.x = 25 - rect.size.width / 2;
4685 rect.origin.y = 25 - rect.size.height / 2;
4687 [icon_ drawInRect:rect];
4690 if (badge_ != nil) {
4691 CGSize size = [badge_ size];
4693 [badge_ drawAtPoint:CGPointMake(
4694 36 - size.width / 2,
4695 36 - size.height / 2
4703 UISetColor(commercial_ ? Purple_ : Black_);
4704 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4705 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4708 UISetColor(commercial_ ? Purplish_ : Gray_);
4709 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4712 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4713 //[self _setBackgroundColor];
4714 [super setSelected:selected animated:fade];
4715 [content_ setNeedsDisplay];
4718 + (int) heightForPackage:(Package *)package {
4724 /* Section Cell {{{ */
4725 @interface SectionCell : UISimpleTableCell {
4730 _UISwitchSlider *switch_;
4735 - (void) setSection:(Section *)section editing:(BOOL)editing;
4739 @implementation SectionCell
4741 - (void) clearSection {
4742 if (section_ != nil) {
4752 if (count_ != nil) {
4759 [self clearSection];
4766 if ((self = [super init]) != nil) {
4767 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4769 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4770 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventTouchUpInside];
4774 - (void) onSwitch:(id)sender {
4775 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4776 if (metadata == nil) {
4777 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4778 [Sections_ setObject:metadata forKey:section_];
4782 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4785 - (void) setSection:(Section *)section editing:(BOOL)editing {
4786 if (editing != editing_) {
4788 [switch_ removeFromSuperview];
4790 [self addSubview:switch_];
4794 [self clearSection];
4796 if (section == nil) {
4797 name_ = [UCLocalize("ALL_PACKAGES") retain];
4800 section_ = [section localized];
4801 if (section_ != nil)
4802 section_ = [section_ retain];
4803 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4804 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4807 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4811 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4812 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4819 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4821 CGSize size = [count_ sizeWithFont:Font14_];
4825 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4827 [super drawContentInRect:rect selected:selected];
4833 /* File Table {{{ */
4834 @interface FileTable : RVPage {
4835 _transient Database *database_;
4838 NSMutableArray *files_;
4842 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4843 - (void) setPackage:(Package *)package;
4847 @implementation FileTable
4850 if (package_ != nil)
4859 - (int) numberOfRowsInTable:(UITable *)table {
4860 return files_ == nil ? 0 : [files_ count];
4863 - (float) table:(UITable *)table heightForRow:(int)row {
4867 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4868 if (reusing == nil) {
4869 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4870 UIFont *font = [UIFont systemFontOfSize:16];
4871 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4873 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4877 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4881 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4882 if ((self = [super initWithBook:book]) != nil) {
4883 database_ = database;
4885 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4887 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4888 [self addSubview:list_];
4890 UITableColumn *column = [[[UITableColumn alloc]
4891 initWithTitle:UCLocalize("NAME")
4893 width:[self frame].size.width
4896 [list_ setDataSource:self];
4897 [list_ setSeparatorStyle:1];
4898 [list_ addTableColumn:column];
4899 [list_ setDelegate:self];
4900 [list_ setReusesTableCells:YES];
4904 - (void) setPackage:(Package *)package {
4905 if (package_ != nil) {
4906 [package_ autorelease];
4915 [files_ removeAllObjects];
4917 if (package != nil) {
4918 package_ = [package retain];
4919 name_ = [[package id] retain];
4921 if (NSArray *files = [package files])
4922 [files_ addObjectsFromArray:files];
4924 if ([files_ count] != 0) {
4925 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4926 [files_ removeObjectAtIndex:0];
4927 [files_ sortUsingSelector:@selector(compareByPath:)];
4929 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4930 [stack addObject:@"/"];
4932 for (int i(0), e([files_ count]); i != e; ++i) {
4933 NSString *file = [files_ objectAtIndex:i];
4934 while (![file hasPrefix:[stack lastObject]])
4935 [stack removeLastObject];
4936 NSString *directory = [stack lastObject];
4937 [stack addObject:[file stringByAppendingString:@"/"]];
4938 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4939 ([stack count] - 2) * 3, "",
4940 [file substringFromIndex:[directory length]]
4949 - (void) resetViewAnimated:(BOOL)animated {
4950 [list_ resetViewAnimated:animated];
4953 - (void) reloadData {
4954 [self setPackage:[database_ packageWithName:name_]];
4955 [self reloadButtons];
4958 - (NSString *) title {
4959 return UCLocalize("INSTALLED_FILES");
4962 - (NSString *) backButtonTitle {
4963 return UCLocalize("FILES");
4968 /* Package View {{{ */
4969 @interface PackageView : CydiaBrowserView {
4970 _transient Database *database_;
4974 NSMutableArray *buttons_;
4977 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4978 - (void) setPackage:(Package *)package;
4982 @implementation PackageView
4985 if (package_ != nil)
4994 if ([self retainCount] == 1)
4995 [delegate_ setPackageView:self];
4999 /* XXX: this is not safe at all... localization of /fail/ */
5000 - (void) _clickButtonWithName:(NSString *)name {
5001 if ([name isEqualToString:UCLocalize("CLEAR")])
5002 [delegate_ clearPackage:package_];
5003 else if ([name isEqualToString:UCLocalize("INSTALL")])
5004 [delegate_ installPackage:package_];
5005 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5006 [delegate_ installPackage:package_];
5007 else if ([name isEqualToString:UCLocalize("REMOVE")])
5008 [delegate_ removePackage:package_];
5009 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5010 [delegate_ installPackage:package_];
5011 else _assert(false);
5014 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5015 NSString *context([sheet context]);
5017 if ([context isEqualToString:@"modify"]) {
5018 int count = [buttons_ count];
5019 _assert(count != 0);
5020 _assert(button <= count + 1);
5022 if (count != button - 1)
5023 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
5027 [super alertSheet:sheet buttonClicked:button];
5030 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5031 return [super webView:sender didFinishLoadForFrame:frame];
5034 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5035 [super webView:sender didClearWindowObject:window forFrame:frame];
5036 [window setValue:package_ forKey:@"package"];
5039 - (bool) _allowJavaScriptPanel {
5044 - (void) __rightButtonClicked {
5045 int count = [buttons_ count];
5046 _assert(count != 0);
5049 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5051 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
5052 [buttons addObjectsFromArray:buttons_];
5053 [buttons addObject:UCLocalize("CANCEL")];
5055 [delegate_ slideUp:[[[UIActionSheet alloc]
5058 defaultButtonIndex:([buttons count] - 1)
5065 - (void) _rightButtonClicked {
5067 [super _rightButtonClicked];
5069 [self __rightButtonClicked];
5073 - (id) _rightButtonTitle {
5074 int count = [buttons_ count];
5075 return count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0];
5078 - (NSString *) backButtonTitle {
5082 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5083 if ((self = [super initWithBook:book]) != nil) {
5084 database_ = database;
5085 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5086 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5090 - (void) setPackage:(Package *)package {
5091 if (package_ != nil) {
5092 [package_ autorelease];
5101 [buttons_ removeAllObjects];
5103 if (package != nil) {
5106 package_ = [package retain];
5107 name_ = [[package id] retain];
5108 commercial_ = [package isCommercial];
5110 if ([package_ mode] != nil)
5111 [buttons_ addObject:UCLocalize("CLEAR")];
5112 if ([package_ source] == nil);
5113 else if ([package_ upgradableAndEssential:NO])
5114 [buttons_ addObject:UCLocalize("UPGRADE")];
5115 else if ([package_ uninstalled])
5116 [buttons_ addObject:UCLocalize("INSTALL")];
5118 [buttons_ addObject:UCLocalize("REINSTALL")];
5119 if (![package_ uninstalled])
5120 [buttons_ addObject:UCLocalize("REMOVE")];
5122 if (special_ != NULL) {
5123 CGRect frame([webview_ frame]);
5124 frame.size.width = 320;
5125 frame.size.height = 0;
5126 [webview_ setFrame:frame];
5128 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5131 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5133 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5135 [self setFinishHook:nil];
5136 [self setPopupHook:nil];
5139 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5140 [super callFunction:special_];
5144 [self reloadButtons];
5147 - (bool) isLoading {
5148 return commercial_ ? [super isLoading] : false;
5151 - (void) reloadData {
5152 [self setPackage:[database_ packageWithName:name_]];
5157 /* Package Table {{{ */
5158 @interface PackageTable : RVPage {
5159 _transient Database *database_;
5161 NSMutableArray *packages_;
5162 NSMutableArray *sections_;
5164 NSMutableArray *index_;
5165 NSMutableDictionary *indices_;
5168 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5170 - (void) setDelegate:(id)delegate;
5172 - (void) reloadData;
5173 - (void) resetCursor;
5175 - (UITableView *) list;
5177 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5181 @implementation PackageTable
5184 [list_ setDataSource:nil];
5187 [packages_ release];
5188 [sections_ release];
5195 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5196 NSInteger count([sections_ count]);
5197 return count == 0 ? 1 : count;
5200 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5201 if ([sections_ count] == 0)
5203 return [[sections_ objectAtIndex:section] name];
5206 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5207 if ([sections_ count] == 0)
5209 return [[sections_ objectAtIndex:section] count];
5212 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5213 Section *section([sections_ objectAtIndex:[path section]]);
5214 NSInteger row([path row]);
5215 Package *package([packages_ objectAtIndex:([section row] + row)]);
5219 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5220 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
5222 cell = [[[PackageCell alloc] init] autorelease];
5223 [cell setPackage:[self packageAtIndexPath:path]];
5227 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5229 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5232 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5233 Package *package([self packageAtIndexPath:path]);
5234 package = [database_ packageWithName:[package id]];
5235 PackageView *view([delegate_ packageView]);
5236 [view setPackage:package];
5237 [view setDelegate:delegate_];
5238 [book_ pushPage:view];
5242 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5243 return [packages_ count] > 20 ? index_ : nil;
5246 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5250 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5251 if ((self = [super initWithBook:book]) != nil) {
5252 database_ = database;
5253 title_ = [title retain];
5255 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5256 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5258 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5259 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5261 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5262 [list_ setDataSource:self];
5263 [list_ setDelegate:self];
5265 [self addSubview:list_];
5267 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5268 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5272 - (void) setDelegate:(id)delegate {
5273 delegate_ = delegate;
5276 - (bool) hasPackage:(Package *)package {
5280 - (void) reloadData {
5281 NSArray *packages = [database_ packages];
5283 [packages_ removeAllObjects];
5284 [sections_ removeAllObjects];
5286 _profile(PackageTable$reloadData$Filter)
5287 for (Package *package in packages)
5288 if ([self hasPackage:package])
5289 [packages_ addObject:package];
5292 [index_ removeAllObjects];
5293 [indices_ removeAllObjects];
5295 Section *section = nil;
5297 _profile(PackageTable$reloadData$Section)
5298 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5302 _profile(PackageTable$reloadData$Section$Package)
5303 package = [packages_ objectAtIndex:offset];
5304 index = [package index];
5307 if (section == nil || [section index] != index) {
5308 _profile(PackageTable$reloadData$Section$Allocate)
5309 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5312 [index_ addObject:[section name]];
5313 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5315 _profile(PackageTable$reloadData$Section$Add)
5316 [sections_ addObject:section];
5320 [section addToCount];
5324 _profile(PackageTable$reloadData$List)
5329 - (NSString *) title {
5333 - (void) resetViewAnimated:(BOOL)animated {
5334 [list_ resetViewAnimated:animated];
5337 - (void) resetCursor {
5338 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5341 - (UITableView *) list {
5345 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5346 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5351 /* Filtered Package Table {{{ */
5352 @interface FilteredPackageTable : PackageTable {
5358 - (void) setObject:(id)object;
5360 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5364 @implementation FilteredPackageTable
5372 - (void) setObject:(id)object {
5378 object_ = [object retain];
5381 - (bool) hasPackage:(Package *)package {
5382 _profile(FilteredPackageTable$hasPackage)
5383 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5387 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5388 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5390 object_ = object == nil ? nil : [object retain];
5392 /* XXX: this is an unsafe optimization of doomy hell */
5393 Method method = class_getInstanceMethod([Package class], filter);
5394 _assert(method != NULL);
5395 imp_ = method_getImplementation(method);
5396 _assert(imp_ != NULL);
5405 /* Add Source View {{{ */
5406 @interface AddSourceView : RVPage {
5407 _transient Database *database_;
5410 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5414 @implementation AddSourceView
5416 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5417 if ((self = [super initWithBook:book]) != nil) {
5418 database_ = database;
5424 /* Source Cell {{{ */
5425 @interface SourceCell : UITableCell {
5428 NSString *description_;
5434 - (SourceCell *) initWithSource:(Source *)source;
5438 @implementation SourceCell
5443 [description_ release];
5448 - (SourceCell *) initWithSource:(Source *)source {
5449 if ((self = [super init]) != nil) {
5451 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5453 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5454 icon_ = [icon_ retain];
5456 origin_ = [[source name] retain];
5457 label_ = [[source uri] retain];
5458 description_ = [[source description] retain];
5462 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5464 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5471 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5475 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5479 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5481 [super drawContentInRect:rect selected:selected];
5486 /* Source Table {{{ */
5487 @interface SourceTable : RVPage {
5488 _transient Database *database_;
5489 UISectionList *list_;
5490 NSMutableArray *sources_;
5491 UIActionSheet *alert_;
5495 UIProgressHUD *hud_;
5498 //NSURLConnection *installer_;
5499 NSURLConnection *trivial_bz2_;
5500 NSURLConnection *trivial_gz_;
5501 //NSURLConnection *automatic_;
5506 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5510 @implementation SourceTable
5512 - (void) _deallocConnection:(NSURLConnection *)connection {
5513 if (connection != nil) {
5514 [connection cancel];
5515 //[connection setDelegate:nil];
5516 [connection release];
5521 [[list_ table] setDelegate:nil];
5522 [list_ setDataSource:nil];
5531 //[self _deallocConnection:installer_];
5532 [self _deallocConnection:trivial_gz_];
5533 [self _deallocConnection:trivial_bz2_];
5534 //[self _deallocConnection:automatic_];
5541 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5542 return offset_ == 0 ? 1 : 2;
5545 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5546 switch (section + (offset_ == 0 ? 1 : 0)) {
5547 case 0: return UCLocalize("ENTERED_BY_USER");
5548 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5556 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5557 switch (section + (offset_ == 0 ? 1 : 0)) {
5559 case 1: return offset_;
5567 - (int) numberOfRowsInTable:(UITable *)table {
5568 return [sources_ count];
5571 - (float) table:(UITable *)table heightForRow:(int)row {
5572 Source *source = [sources_ objectAtIndex:row];
5573 return [source description] == nil ? 56 : 73;
5576 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5577 Source *source = [sources_ objectAtIndex:row];
5578 // XXX: weird warning, stupid selectors ;P
5579 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5582 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5586 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5590 - (void) tableRowSelected:(NSNotification*)notification {
5591 UITable *table([list_ table]);
5592 int row([table selectedRow]);
5596 Source *source = [sources_ objectAtIndex:row];
5598 PackageTable *packages = [[[FilteredPackageTable alloc]
5601 title:[source label]
5602 filter:@selector(isVisibleInSource:)
5606 [packages setDelegate:delegate_];
5608 [book_ pushPage:packages];
5611 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5612 Source *source = [sources_ objectAtIndex:row];
5613 return [source record] != nil;
5616 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5617 [[list_ table] setDeleteConfirmationRow:row];
5620 - (void) table:(UITable *)table deleteRow:(int)row {
5621 Source *source = [sources_ objectAtIndex:row];
5622 [Sources_ removeObjectForKey:[source key]];
5623 [delegate_ syncData];
5627 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5630 @"./", @"Distribution",
5631 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5633 [delegate_ syncData];
5636 - (NSString *) getWarning {
5637 NSString *href(href_);
5638 NSRange colon([href rangeOfString:@"://"]);
5639 if (colon.location != NSNotFound)
5640 href = [href substringFromIndex:(colon.location + 3)];
5641 href = [href stringByAddingPercentEscapes];
5642 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5643 href = [href stringByCachingURLWithCurrentCDN];
5645 NSURL *url([NSURL URLWithString:href]);
5647 NSStringEncoding encoding;
5648 NSError *error(nil);
5650 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5651 return [warning length] == 0 ? nil : warning;
5655 - (void) _endConnection:(NSURLConnection *)connection {
5656 NSURLConnection **field = NULL;
5657 if (connection == trivial_bz2_)
5658 field = &trivial_bz2_;
5659 else if (connection == trivial_gz_)
5660 field = &trivial_gz_;
5661 _assert(field != NULL);
5662 [connection release];
5666 trivial_bz2_ == nil &&
5672 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5675 UIActionSheet *sheet = [[[UIActionSheet alloc]
5676 initWithTitle:UCLocalize("SOURCE_WARNING")
5677 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_ANYWAY"), UCLocalize("CANCEL"), nil]
5678 defaultButtonIndex:0
5683 [sheet setNumberOfRows:1];
5685 [sheet setBodyText:warning];
5686 [sheet popupAlertAnimated:YES];
5689 } else if (error_ != nil) {
5690 UIActionSheet *sheet = [[[UIActionSheet alloc]
5691 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5692 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5693 defaultButtonIndex:0
5698 [sheet setBodyText:[error_ localizedDescription]];
5699 [sheet popupAlertAnimated:YES];
5701 UIActionSheet *sheet = [[[UIActionSheet alloc]
5702 initWithTitle:UCLocalize("NOT_REPOSITORY")
5703 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5704 defaultButtonIndex:0
5709 [sheet setBodyText:UCLocalize("NOT_REPOSITORY_EX")];
5710 [sheet popupAlertAnimated:YES];
5713 [delegate_ setStatusBarShowsProgress:NO];
5714 [delegate_ removeProgressHUD:hud_];
5724 if (error_ != nil) {
5731 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5732 switch ([response statusCode]) {
5738 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5739 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5741 error_ = [error retain];
5742 [self _endConnection:connection];
5745 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5746 [self _endConnection:connection];
5749 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5750 NSMutableURLRequest *request = [NSMutableURLRequest
5751 requestWithURL:[NSURL URLWithString:href]
5752 cachePolicy:NSURLRequestUseProtocolCachePolicy
5753 timeoutInterval:20.0
5756 [request setHTTPMethod:method];
5758 if (Machine_ != NULL)
5759 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5760 if (UniqueID_ != nil)
5761 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5764 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5766 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5769 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5770 NSString *context([sheet context]);
5772 if ([context isEqualToString:@"source"]) {
5775 NSString *href = [[sheet textField] text];
5777 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5779 if (![href hasSuffix:@"/"])
5780 href_ = [href stringByAppendingString:@"/"];
5783 href_ = [href_ retain];
5785 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
5786 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5787 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5788 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5792 hud_ = [[delegate_ addProgressHUD] retain];
5793 [hud_ setText:UCLocalize("VERIFYING_URL")];
5804 } else if ([context isEqualToString:@"trivial"])
5806 else if ([context isEqualToString:@"urlerror"])
5808 else if ([context isEqualToString:@"warning"]) {
5828 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5829 if ((self = [super initWithBook:book]) != nil) {
5830 database_ = database;
5831 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5833 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5834 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5835 [list_ setShouldHideHeaderInShortLists:NO];
5837 [self addSubview:list_];
5838 [list_ setDataSource:self];
5840 UITableColumn *column = [[UITableColumn alloc]
5841 initWithTitle:UCLocalize("NAME")
5843 width:[self frame].size.width
5846 UITable *table = [list_ table];
5847 [table setSeparatorStyle:1];
5848 [table addTableColumn:column];
5849 [table setDelegate:self];
5853 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5854 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5858 - (void) reloadData {
5860 _assert(list.ReadMainList());
5862 [sources_ removeAllObjects];
5863 [sources_ addObjectsFromArray:[database_ sources]];
5865 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5868 int count = [sources_ count];
5869 for (offset_ = 0; offset_ != count; ++offset_) {
5870 Source *source = [sources_ objectAtIndex:offset_];
5871 if ([source record] == nil)
5878 - (void) resetViewAnimated:(BOOL)animated {
5879 [list_ resetViewAnimated:animated];
5882 - (void) _leftButtonClicked {
5883 /*[book_ pushPage:[[[AddSourceView alloc]
5888 UIActionSheet *sheet = [[[UIActionSheet alloc]
5889 initWithTitle:UCLocalize("ENTER_APT_URL")
5890 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_SOURCE"), UCLocalize("CANCEL"), nil]
5891 defaultButtonIndex:0
5896 [sheet setNumberOfRows:1];
5898 [sheet addTextFieldWithValue:@"http://" label:@""];
5900 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5901 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5902 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5903 [traits setKeyboardType:UIKeyboardTypeURL];
5904 // XXX: UIReturnKeyDone
5905 [traits setReturnKeyType:UIReturnKeyNext];
5907 [sheet popupAlertAnimated:YES];
5910 - (void) _rightButtonClicked {
5911 UITable *table = [list_ table];
5912 BOOL editing = [table isRowDeletionEnabled];
5913 [table enableRowDeletion:!editing animated:YES];
5914 [book_ reloadButtonsForPage:self];
5917 - (NSString *) title {
5918 return UCLocalize("SOURCES");
5921 - (NSString *) leftButtonTitle {
5922 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("ADD") : nil;
5925 - (id) rightButtonTitle {
5926 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("DONE") : UCLocalize("EDIT");
5929 - (UINavigationButtonStyle) rightButtonStyle {
5930 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5936 /* Installed View {{{ */
5937 @interface InstalledView : RVPage {
5938 _transient Database *database_;
5939 FilteredPackageTable *packages_;
5943 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5947 @implementation InstalledView
5950 [packages_ release];
5954 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5955 if ((self = [super initWithBook:book]) != nil) {
5956 database_ = database;
5958 packages_ = [[FilteredPackageTable alloc]
5962 filter:@selector(isInstalledAndVisible:)
5963 with:[NSNumber numberWithBool:YES]
5966 [self addSubview:packages_];
5968 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5969 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5973 - (void) resetViewAnimated:(BOOL)animated {
5974 [packages_ resetViewAnimated:animated];
5977 - (void) reloadData {
5978 [packages_ reloadData];
5981 - (void) _rightButtonClicked {
5982 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5983 [packages_ reloadData];
5985 [book_ reloadButtonsForPage:self];
5988 - (NSString *) title {
5989 return UCLocalize("INSTALLED");
5992 - (NSString *) backButtonTitle {
5993 return UCLocalize("PACKAGES");
5996 - (id) rightButtonTitle {
5997 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE");
6000 - (UINavigationButtonStyle) rightButtonStyle {
6001 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6004 - (void) setDelegate:(id)delegate {
6005 [super setDelegate:delegate];
6006 [packages_ setDelegate:delegate];
6013 @interface HomeView : CydiaBrowserView {
6018 @implementation HomeView
6020 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6021 NSString *context([sheet context]);
6023 if ([context isEqualToString:@"about"])
6026 [super alertSheet:sheet buttonClicked:button];
6029 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6030 [super _setMoreHeaders:request];
6032 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6035 - (void) _leftButtonClicked {
6036 UIActionSheet *sheet = [[[UIActionSheet alloc]
6037 initWithTitle:UCLocalize("ABOUT_CYDIA")
6038 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
6039 defaultButtonIndex:0
6045 @"Copyright (C) 2008-2009\n"
6046 "Jay Freeman (saurik)\n"
6047 "saurik@saurik.com\n"
6048 "http://www.saurik.com/\n"
6051 "http://www.theokorigroup.com/\n"
6053 "College of Creative Studies,\n"
6054 "University of California,\n"
6056 "http://www.ccs.ucsb.edu/"
6059 [sheet popupAlertAnimated:YES];
6062 - (NSString *) leftButtonTitle {
6063 return UCLocalize("ABOUT");
6068 /* Manage View {{{ */
6069 @interface ManageView : CydiaBrowserView {
6074 @implementation ManageView
6076 - (NSString *) title {
6077 return UCLocalize("MANAGE");
6080 - (void) _leftButtonClicked {
6081 [delegate_ askForSettings];
6084 - (NSString *) leftButtonTitle {
6085 return UCLocalize("SETTINGS");
6089 - (id) _rightButtonTitle {
6090 return Queuing_ ? UCLocalize("QUEUE") : nil;
6093 - (UINavigationButtonStyle) rightButtonStyle {
6094 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6097 - (void) _rightButtonClicked {
6102 - (bool) isLoading {
6109 /* Cydia Book {{{ */
6110 @interface CYBook : RVBook <
6113 _transient Database *database_;
6114 UINavigationBar *overlay_;
6115 UINavigationBar *underlay_;
6116 UIProgressIndicator *indicator_;
6117 UITextLabel *prompt_;
6118 UIProgressBar *progress_;
6119 UINavigationButton *cancel_;
6123 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
6129 @implementation CYBook
6133 [indicator_ release];
6135 [progress_ release];
6140 - (NSString *) getTitleForPage:(RVPage *)page {
6141 return [super getTitleForPage:page];
6149 [UIView beginAnimations:nil context:NULL];
6151 CGRect ovrframe = [overlay_ frame];
6152 ovrframe.origin.y = 0;
6153 [overlay_ setFrame:ovrframe];
6155 CGRect barframe = [navbar_ frame];
6156 barframe.origin.y += ovrframe.size.height;
6157 [navbar_ setFrame:barframe];
6159 CGRect trnframe = [transition_ frame];
6160 trnframe.origin.y += ovrframe.size.height;
6161 trnframe.size.height -= ovrframe.size.height;
6162 [transition_ setFrame:trnframe];
6164 [UIView endAnimations];
6166 [indicator_ startAnimation];
6167 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6168 [progress_ setProgress:0];
6171 [overlay_ addSubview:cancel_];
6174 detachNewThreadSelector:@selector(_update)
6180 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6181 NSString *context([sheet context]);
6183 if ([context isEqualToString:@"refresh"])
6187 - (void) _update_:(NSString *)error {
6190 [indicator_ stopAnimation];
6192 [UIView beginAnimations:nil context:NULL];
6194 CGRect ovrframe = [overlay_ frame];
6195 ovrframe.origin.y = -ovrframe.size.height;
6196 [overlay_ setFrame:ovrframe];
6198 CGRect barframe = [navbar_ frame];
6199 barframe.origin.y -= ovrframe.size.height;
6200 [navbar_ setFrame:barframe];
6202 CGRect trnframe = [transition_ frame];
6203 trnframe.origin.y -= ovrframe.size.height;
6204 trnframe.size.height += ovrframe.size.height;
6205 [transition_ setFrame:trnframe];
6207 [UIView commitAnimations];
6210 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6212 UIActionSheet *sheet = [[[UIActionSheet alloc]
6213 initWithTitle:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), UCLocalize("REFRESH")]
6214 buttons:[NSArray arrayWithObjects:
6217 defaultButtonIndex:0
6222 [sheet setBodyText:error];
6223 [sheet popupAlertAnimated:YES];
6225 [self reloadButtons];
6229 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6230 if ((self = [super initWithFrame:frame]) != nil) {
6231 database_ = database;
6233 CGRect ovrrect = [navbar_ bounds];
6234 ovrrect.size.height = [UINavigationBar defaultSize].height;
6235 ovrrect.origin.y = -ovrrect.size.height;
6237 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6238 [self addSubview:overlay_];
6240 ovrrect.origin.y = frame.size.height;
6241 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6242 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6243 [self addSubview:underlay_];
6245 [overlay_ setBarStyle:1];
6246 [underlay_ setBarStyle:1];
6248 int barstyle = [overlay_ _barStyle:NO];
6249 bool ugly = barstyle == 0;
6251 UIProgressIndicatorStyle style = ugly ?
6252 UIProgressIndicatorStyleMediumBrown :
6253 UIProgressIndicatorStyleMediumWhite;
6255 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
6256 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6257 CGRect indrect = {{indoffset, indoffset}, indsize};
6259 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6260 [indicator_ setStyle:style];
6261 [overlay_ addSubview:indicator_];
6263 CGSize prmsize = {215, indsize.height + 4};
6266 indoffset * 2 + indsize.width,
6267 unsigned(ovrrect.size.height - prmsize.height) / 2 - 1
6270 UIFont *font = [UIFont systemFontOfSize:15];
6272 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6274 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6275 [prompt_ setBackgroundColor:[UIColor clearColor]];
6276 [prompt_ setFont:font];
6278 [overlay_ addSubview:prompt_];
6280 CGSize prgsize = {75, 100};
6283 ovrrect.size.width - prgsize.width - 10,
6284 (ovrrect.size.height - prgsize.height) / 2
6287 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6288 [progress_ setStyle:0];
6289 [overlay_ addSubview:progress_];
6291 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6292 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6294 CGRect frame = [cancel_ frame];
6295 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6296 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6297 [cancel_ setFrame:frame];
6299 [cancel_ setBarStyle:barstyle];
6303 - (void) _onCancel {
6305 [cancel_ removeFromSuperview];
6308 - (void) _update { _pooled
6310 status.setDelegate(self);
6312 NSString *error([database_ updateWithStatus:status]);
6315 performSelectorOnMainThread:@selector(_update_:)
6321 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
6322 [prompt_ setText:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6325 - (void) setProgressTitle:(NSString *)title {
6327 performSelectorOnMainThread:@selector(_setProgressTitle:)
6333 - (void) setProgressPercent:(float)percent {
6335 performSelectorOnMainThread:@selector(_setProgressPercent:)
6336 withObject:[NSNumber numberWithFloat:percent]
6341 - (void) startProgress {
6344 - (void) addProgressOutput:(NSString *)output {
6346 performSelectorOnMainThread:@selector(_addProgressOutput:)
6352 - (bool) isCancelling:(size_t)received {
6356 - (void) _setProgressTitle:(NSString *)title {
6357 [prompt_ setText:title];
6360 - (void) _setProgressPercent:(NSNumber *)percent {
6361 [progress_ setProgress:[percent floatValue]];
6364 - (void) _addProgressOutput:(NSString *)output {
6369 /* Cydia:// Protocol {{{ */
6370 @interface CydiaURLProtocol : NSURLProtocol {
6375 @implementation CydiaURLProtocol
6377 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6378 NSURL *url([request URL]);
6381 NSString *scheme([[url scheme] lowercaseString]);
6382 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6387 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6391 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6392 id<NSURLProtocolClient> client([self client]);
6394 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6396 NSData *data(UIImagePNGRepresentation(icon));
6398 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6399 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6400 [client URLProtocol:self didLoadData:data];
6401 [client URLProtocolDidFinishLoading:self];
6405 - (void) startLoading {
6406 id<NSURLProtocolClient> client([self client]);
6407 NSURLRequest *request([self request]);
6409 NSURL *url([request URL]);
6410 NSString *href([url absoluteString]);
6412 NSString *path([href substringFromIndex:8]);
6413 NSRange slash([path rangeOfString:@"/"]);
6416 if (slash.location == NSNotFound) {
6420 command = [path substringToIndex:slash.location];
6421 path = [path substringFromIndex:(slash.location + 1)];
6424 Database *database([Database sharedInstance]);
6426 if ([command isEqualToString:@"package-icon"]) {
6429 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6430 Package *package([database packageWithName:path]);
6433 UIImage *icon([package icon]);
6434 [self _returnPNGWithImage:icon forRequest:request];
6435 } else if ([command isEqualToString:@"source-icon"]) {
6438 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6439 NSString *source(Simplify(path));
6440 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6442 icon = [UIImage applicationImageNamed:@"unknown.png"];
6443 [self _returnPNGWithImage:icon forRequest:request];
6444 } else if ([command isEqualToString:@"uikit-image"]) {
6447 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6448 UIImage *icon(_UIImageWithName(path));
6449 [self _returnPNGWithImage:icon forRequest:request];
6450 } else if ([command isEqualToString:@"section-icon"]) {
6453 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6454 NSString *section(Simplify(path));
6455 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6457 icon = [UIImage applicationImageNamed:@"unknown.png"];
6458 [self _returnPNGWithImage:icon forRequest:request];
6460 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6464 - (void) stopLoading {
6470 /* Sections View {{{ */
6471 @interface SectionsView : RVPage {
6472 _transient Database *database_;
6473 NSMutableArray *sections_;
6474 NSMutableArray *filtered_;
6475 UITransitionView *transition_;
6481 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6482 - (void) reloadData;
6487 @implementation SectionsView
6490 [list_ setDataSource:nil];
6491 [list_ setDelegate:nil];
6493 [sections_ release];
6494 [filtered_ release];
6495 [transition_ release];
6497 [accessory_ release];
6501 - (int) numberOfRowsInTable:(UITable *)table {
6502 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6505 - (float) table:(UITable *)table heightForRow:(int)row {
6509 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6511 reusing = [[[SectionCell alloc] init] autorelease];
6512 [(SectionCell *)reusing setSection:(editing_ ?
6513 [sections_ objectAtIndex:row] :
6514 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6515 ) editing:editing_];
6519 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6523 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6527 - (void) tableRowSelected:(NSNotification *)notification {
6528 int row = [[notification object] selectedRow];
6539 title = UCLocalize("ALL_PACKAGES");
6541 section = [filtered_ objectAtIndex:(row - 1)];
6542 name = [section name];
6545 name = [NSString stringWithString:name];
6546 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6549 title = UCLocalize("NO_SECTION");
6553 PackageTable *table = [[[FilteredPackageTable alloc]
6557 filter:@selector(isVisiblyUninstalledInSection:)
6561 [table setDelegate:delegate_];
6563 [book_ pushPage:table];
6566 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6567 if ((self = [super initWithBook:book]) != nil) {
6568 database_ = database;
6570 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6571 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6573 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6574 [self addSubview:transition_];
6576 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6577 [transition_ transition:0 toView:list_];
6579 UITableColumn *column = [[[UITableColumn alloc]
6580 initWithTitle:UCLocalize("NAME")
6582 width:[self frame].size.width
6585 [list_ setDataSource:self];
6586 [list_ setSeparatorStyle:1];
6587 [list_ addTableColumn:column];
6588 [list_ setDelegate:self];
6589 [list_ setReusesTableCells:YES];
6593 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6594 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6598 - (void) reloadData {
6599 NSArray *packages = [database_ packages];
6601 [sections_ removeAllObjects];
6602 [filtered_ removeAllObjects];
6605 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6606 SectionMap sections;
6607 sections.resize(64);
6609 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6613 for (Package *package in packages) {
6614 NSString *name([package section]);
6615 NSString *key(name == nil ? @"" : name);
6620 _profile(SectionsView$reloadData$Section)
6621 section = §ions[key];
6622 if (*section == nil) {
6623 _profile(SectionsView$reloadData$Section$Allocate)
6624 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6629 [*section addToCount];
6631 _profile(SectionsView$reloadData$Filter)
6632 if (![package valid] || ![package uninstalled] || ![package visible])
6636 [*section addToRow];
6640 _profile(SectionsView$reloadData$Section)
6641 section = [sections objectForKey:key];
6642 if (section == nil) {
6643 _profile(SectionsView$reloadData$Section$Allocate)
6644 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6645 [sections setObject:section forKey:key];
6650 [section addToCount];
6652 _profile(SectionsView$reloadData$Filter)
6653 if (![package valid] || ![package uninstalled] || ![package visible])
6663 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6664 [sections_ addObject:i->second];
6666 [sections_ addObjectsFromArray:[sections allValues]];
6669 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6671 for (Section *section in sections_) {
6672 size_t count([section row]);
6676 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6677 [section setCount:count];
6678 [filtered_ addObject:section];
6685 - (void) resetView {
6687 [self _rightButtonClicked];
6690 - (void) resetViewAnimated:(BOOL)animated {
6691 [list_ resetViewAnimated:animated];
6694 - (void) _rightButtonClicked {
6695 if ((editing_ = !editing_))
6698 [delegate_ updateData];
6699 [book_ reloadTitleForPage:self];
6700 [book_ reloadButtonsForPage:self];
6703 - (NSString *) title {
6704 return editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("INSTALL_BY_SECTION");
6707 - (NSString *) backButtonTitle {
6708 return UCLocalize("SECTIONS");
6711 - (id) rightButtonTitle {
6712 return [sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT");
6715 - (UINavigationButtonStyle) rightButtonStyle {
6716 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6719 - (UIView *) accessoryView {
6725 /* Changes View {{{ */
6726 @interface ChangesView : RVPage {
6727 _transient Database *database_;
6728 NSMutableArray *packages_;
6729 NSMutableArray *sections_;
6734 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6735 - (void) reloadData;
6739 @implementation ChangesView
6742 [list_ setDelegate:nil];
6743 [list_ setDataSource:nil];
6745 [packages_ release];
6746 [sections_ release];
6751 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6752 NSInteger count([sections_ count]);
6753 return count == 0 ? 1 : count;
6756 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6757 if ([sections_ count] == 0)
6759 return [[sections_ objectAtIndex:section] name];
6762 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6763 if ([sections_ count] == 0)
6765 return [[sections_ objectAtIndex:section] count];
6768 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6769 Section *section([sections_ objectAtIndex:[path section]]);
6770 NSInteger row([path row]);
6771 return [packages_ objectAtIndex:([section row] + row)];
6774 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6775 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
6777 cell = [[[PackageCell alloc] init] autorelease];
6778 [cell setPackage:[self packageAtIndexPath:path]];
6782 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6784 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6787 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6788 Package *package([self packageAtIndexPath:path]);
6789 PackageView *view([delegate_ packageView]);
6790 [view setDelegate:delegate_];
6791 [view setPackage:package];
6792 [book_ pushPage:view];
6796 - (void) _leftButtonClicked {
6797 [(CYBook *)book_ update];
6798 [self reloadButtons];
6801 - (void) _rightButtonClicked {
6802 [delegate_ distUpgrade];
6805 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6806 if ((self = [super initWithBook:book]) != nil) {
6807 database_ = database;
6809 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6810 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6812 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
6813 [self addSubview:list_];
6815 //XXX:[list_ setShouldHideHeaderInShortLists:NO];
6816 [list_ setDataSource:self];
6817 [list_ setDelegate:self];
6818 //[list_ setSectionListStyle:1];
6822 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6823 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6827 - (void) reloadData {
6828 NSArray *packages = [database_ packages];
6830 [packages_ removeAllObjects];
6831 [sections_ removeAllObjects];
6834 for (Package *package in packages)
6836 [package uninstalled] && [package valid] && [package visible] ||
6837 [package upgradableAndEssential:YES]
6839 [packages_ addObject:package];
6842 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6845 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6846 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6847 Section *section = nil;
6851 bool unseens = false;
6853 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6855 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6856 Package *package = [packages_ objectAtIndex:offset];
6858 BOOL uae = [package upgradableAndEssential:YES];
6864 _profile(ChangesView$reloadData$Remember)
6865 seen = [package seen];
6868 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6873 name = UCLocalize("UNKNOWN");
6875 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6879 _profile(ChangesView$reloadData$Allocate)
6880 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
6881 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6882 [sections_ addObject:section];
6886 [section addToCount];
6887 } else if ([package ignored])
6888 [ignored addToCount];
6891 [upgradable addToCount];
6896 CFRelease(formatter);
6899 Section *last = [sections_ lastObject];
6900 size_t count = [last count];
6901 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6902 [sections_ removeLastObject];
6905 if ([ignored count] != 0)
6906 [sections_ insertObject:ignored atIndex:0];
6908 [sections_ insertObject:upgradable atIndex:0];
6911 [self reloadButtons];
6914 - (void) resetViewAnimated:(BOOL)animated {
6915 [list_ resetViewAnimated:animated];
6918 - (NSString *) leftButtonTitle {
6919 return [(CYBook *)book_ updating] ? nil : UCLocalize("REFRESH");
6922 - (id) rightButtonTitle {
6923 return upgrades_ == 0 ? nil : [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6926 - (NSString *) title {
6927 return UCLocalize("CHANGES");
6932 /* Search View {{{ */
6933 @protocol SearchViewDelegate
6934 - (void) showKeyboard:(BOOL)show;
6937 @interface SearchView : RVPage {
6939 UISearchField *field_;
6940 FilteredPackageTable *table_;
6945 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6946 - (void) reloadData;
6950 @implementation SearchView
6953 [field_ setDelegate:nil];
6955 [accessory_ release];
6962 - (void) _showKeyboard:(BOOL)show {
6963 CGSize keysize = [UIKeyboard defaultSize];
6964 CGRect keydown = [book_ pageBounds];
6965 CGRect keyup = keydown;
6966 keyup.size.height -= keysize.height - ButtonBarHeight_;
6968 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6970 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6971 [animation setSignificantRectFields:8];
6974 [animation setStartFrame:keydown];
6975 [animation setEndFrame:keyup];
6977 [animation setStartFrame:keyup];
6978 [animation setEndFrame:keydown];
6981 UIAnimator *animator = [UIAnimator sharedAnimator];
6984 addAnimations:[NSArray arrayWithObjects:animation, nil]
6985 withDuration:(KeyboardTime_ - delay)
6990 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6992 [delegate_ showKeyboard:show];
6995 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6996 [self _showKeyboard:YES];
6999 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
7000 [self _showKeyboard:NO];
7003 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
7005 NSString *text([field_ text]);
7006 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
7012 - (void) textFieldClearButtonPressed:(UITextField *)field {
7016 - (void) keyboardInputShouldDelete:(id)input {
7020 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
7021 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
7025 [field_ resignFirstResponder];
7030 - (id) initWithBook:(RVBook *)book database:(Database *)database {
7031 if ((self = [super initWithBook:book]) != nil) {
7032 CGRect pageBounds = [book_ pageBounds];
7034 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
7035 CGColor dimmed(space_, 0, 0, 0, 0.5);
7036 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
7038 table_ = [[FilteredPackageTable alloc]
7042 filter:@selector(isUnfilteredAndSearchedForBy:)
7046 [table_ setShouldHideHeaderInShortLists:NO];
7047 [self addSubview:table_];
7049 CGRect cnfrect = {{7, 38}, {17, 18}};
7056 area.size.width = [self bounds].size.width - area.origin.x * 2;
7057 area.size.height = [UISearchField defaultHeight];
7059 field_ = [[UISearchField alloc] initWithFrame:area];
7061 UIFont *font = [UIFont systemFontOfSize:16];
7062 [field_ setFont:font];
7064 [field_ setPlaceholder:UCLocalize("SEARCH_EX")];
7065 [field_ setDelegate:self];
7067 [field_ setPaddingTop:5];
7069 UITextInputTraits *traits([field_ textInputTraits]);
7070 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7071 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7072 [traits setReturnKeyType:UIReturnKeySearch];
7074 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
7076 accessory_ = [[UIView alloc] initWithFrame:accrect];
7077 [accessory_ addSubview:field_];
7079 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7080 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7084 - (void) resetViewAnimated:(BOOL)animated {
7085 [table_ resetViewAnimated:animated];
7088 - (void) _reloadData {
7091 - (void) reloadData {
7092 [table_ setObject:[field_ text]];
7093 _profile(SearchView$reloadData)
7094 [table_ reloadData];
7097 [table_ resetCursor];
7100 - (UIView *) accessoryView {
7104 - (NSString *) title {
7108 - (NSString *) backButtonTitle {
7109 return UCLocalize("SEARCH");
7112 - (void) setDelegate:(id)delegate {
7113 [table_ setDelegate:delegate];
7114 [super setDelegate:delegate];
7119 /* Settings View {{{ */
7120 @interface SettingsView : RVPage {
7121 _transient Database *database_;
7124 UIPreferencesTable *table_;
7125 _UISwitchSlider *subscribedSwitch_;
7126 _UISwitchSlider *ignoredSwitch_;
7127 UIPreferencesControlTableCell *subscribedCell_;
7128 UIPreferencesControlTableCell *ignoredCell_;
7131 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7135 @implementation SettingsView
7138 [table_ setDataSource:nil];
7141 if (package_ != nil)
7144 [subscribedSwitch_ release];
7145 [ignoredSwitch_ release];
7146 [subscribedCell_ release];
7147 [ignoredCell_ release];
7151 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7152 if (package_ == nil)
7158 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7159 if (package_ == nil)
7166 default: _assert(false);
7172 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7173 if (package_ == nil)
7180 default: _assert(false);
7186 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7187 if (package_ == nil)
7194 default: _assert(false);
7200 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7201 if (package_ == nil)
7204 _UISwitchSlider *slider([cell control]);
7205 BOOL value([slider value] != 0);
7206 NSMutableDictionary *metadata([package_ metadata]);
7209 if (NSNumber *number = [metadata objectForKey:key])
7210 before = [number boolValue];
7214 if (value != before) {
7215 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7217 [delegate_ updateData];
7221 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7222 [self onSomething:cell withKey:@"IsSubscribed"];
7225 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7226 [self onSomething:cell withKey:@"IsIgnored"];
7229 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7230 if (package_ == nil)
7234 case 0: switch (row) {
7236 return subscribedCell_;
7238 return ignoredCell_;
7239 default: _assert(false);
7242 case 1: switch (row) {
7244 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7245 [cell setShowSelection:NO];
7246 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7250 default: _assert(false);
7253 default: _assert(false);
7259 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7260 if ((self = [super initWithBook:book])) {
7261 database_ = database;
7262 name_ = [package retain];
7264 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7265 [self addSubview:table_];
7267 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7268 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
7270 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7271 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
7273 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7274 [subscribedCell_ setShowSelection:NO];
7275 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7276 [subscribedCell_ setControl:subscribedSwitch_];
7278 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7279 [ignoredCell_ setShowSelection:NO];
7280 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7281 [ignoredCell_ setControl:ignoredSwitch_];
7283 [table_ setDataSource:self];
7288 - (void) resetViewAnimated:(BOOL)animated {
7289 [table_ resetViewAnimated:animated];
7292 - (void) reloadData {
7293 if (package_ != nil)
7294 [package_ autorelease];
7295 package_ = [database_ packageWithName:name_];
7296 if (package_ != nil) {
7298 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7299 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7302 [table_ reloadData];
7305 - (NSString *) title {
7306 return UCLocalize("SETTINGS");
7312 /* Signature View {{{ */
7313 @interface SignatureView : CydiaBrowserView {
7314 _transient Database *database_;
7318 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7322 @implementation SignatureView
7329 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7331 [super webView:sender didClearWindowObject:window forFrame:frame];
7334 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7335 if ((self = [super initWithBook:book]) != nil) {
7336 database_ = database;
7337 package_ = [package retain];
7342 - (void) resetViewAnimated:(BOOL)animated {
7345 - (void) reloadData {
7346 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7352 @interface Cydia : UIApplication <
7353 ConfirmationViewDelegate,
7354 ProgressViewDelegate,
7363 UIToolbar *toolbar_;
7367 NSMutableArray *essential_;
7368 NSMutableArray *broken_;
7370 Database *database_;
7371 ProgressView *progress_;
7375 UIKeyboard *keyboard_;
7376 UIProgressHUD *hud_;
7378 SectionsView *sections_;
7379 ChangesView *changes_;
7380 ManageView *manage_;
7381 SearchView *search_;
7383 #if RecyclePackageViews
7384 NSMutableArray *details_;
7390 @implementation Cydia
7393 if ([broken_ count] != 0) {
7394 int count = [broken_ count];
7396 UIActionSheet *sheet = [[[UIActionSheet alloc]
7397 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7398 buttons:[NSArray arrayWithObjects:
7399 UCLocalize("FORCIBLY_CLEAR"),
7400 UCLocalize("TEMPORARY_IGNORE"),
7402 defaultButtonIndex:0
7407 [sheet setBodyText:UCLocalize("HALFINSTALLED_PACKAGE_EX")];
7408 [sheet popupAlertAnimated:YES];
7409 } else if (!Ignored_ && [essential_ count] != 0) {
7410 int count = [essential_ count];
7412 UIActionSheet *sheet = [[[UIActionSheet alloc]
7413 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7414 buttons:[NSArray arrayWithObjects:
7415 UCLocalize("UPGRADE_ESSENTIAL"),
7416 UCLocalize("COMPLETE_UPGRADE"),
7417 UCLocalize("TEMPORARY_IGNORE"),
7419 defaultButtonIndex:0
7424 [sheet setBodyText:UCLocalize("ESSENTIAL_UPGRADE_EX")];
7425 [sheet popupAlertAnimated:YES];
7429 - (void) _saveConfig {
7432 NSString *error(nil);
7433 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7435 NSError *error(nil);
7436 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7437 NSLog(@"failure to save metadata data: %@", error);
7440 NSLog(@"failure to serialize metadata: %@", error);
7448 - (void) _updateData {
7451 /* XXX: this is just stupid */
7452 if (tag_ != 2 && sections_ != nil)
7453 [sections_ reloadData];
7454 if (tag_ != 3 && changes_ != nil)
7455 [changes_ reloadData];
7456 if (tag_ != 5 && search_ != nil)
7457 [search_ reloadData];
7462 - (void) _reloadData {
7465 static bool loaded(false);
7466 UIProgressHUD *hud([self addProgressHUD]);
7467 [hud setText:(loaded ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7470 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7473 [self removeProgressHUD:hud];
7477 [essential_ removeAllObjects];
7478 [broken_ removeAllObjects];
7480 NSArray *packages = [database_ packages];
7481 for (Package *package in packages) {
7483 [broken_ addObject:package];
7484 if ([package upgradableAndEssential:NO]) {
7485 if ([package essential])
7486 [essential_ addObject:package];
7492 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7493 [toolbar_ setBadgeValue:badge forButton:3];
7494 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7495 [toolbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7496 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7497 [self setApplicationBadge:badge];
7499 [self setApplicationBadgeString:badge];
7501 [toolbar_ setBadgeValue:nil forButton:3];
7502 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7503 [toolbar_ setBadgeAnimated:NO forButton:3];
7504 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7505 [self removeApplicationBadge];
7506 else // XXX: maybe use setApplicationBadgeString also?
7507 [self setApplicationIconBadgeNumber:0];
7511 [toolbar_ setBadgeValue:nil forButton:4];
7515 // XXX: what is this line of code for?
7516 if ([packages count] == 0);
7517 else if (Loaded_ || ManualRefresh) loaded:
7522 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7523 NSTimeInterval interval([update timeIntervalSinceNow]);
7524 if (interval <= 0 && interval > -600)
7532 - (void) updateData {
7533 [database_ setVisible];
7542 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7543 _assert(file != NULL);
7545 NSArray *keys = [Sources_ allKeys];
7547 for (NSString *key in keys) {
7548 NSDictionary *source = [Sources_ objectForKey:key];
7550 fprintf(file, "%s %s %s\n",
7551 [[source objectForKey:@"Type"] UTF8String],
7552 [[source objectForKey:@"URI"] UTF8String],
7553 [[source objectForKey:@"Distribution"] UTF8String]
7562 detachNewThreadSelector:@selector(update_)
7565 title:UCLocalize("UPDATING_SOURCES")
7569 - (void) reloadData {
7570 @synchronized (self) {
7571 if (confirm_ == nil)
7577 pkgProblemResolver *resolver = [database_ resolver];
7579 resolver->InstallProtect();
7580 if (!resolver->Resolve(true))
7584 - (void) popUpBook:(RVBook *)book {
7585 [underlay_ popSubview:book];
7588 - (CGRect) popUpBounds {
7589 return [underlay_ bounds];
7593 [database_ prepare];
7595 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7596 [confirm_ setDelegate:self];
7598 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7599 [page setDelegate:self];
7601 [confirm_ setPage:page];
7602 [self popUpBook:confirm_];
7606 @synchronized (self) {
7611 - (void) clearPackage:(Package *)package {
7612 @synchronized (self) {
7619 - (void) installPackage:(Package *)package {
7620 @synchronized (self) {
7627 - (void) removePackage:(Package *)package {
7628 @synchronized (self) {
7635 - (void) distUpgrade {
7636 @synchronized (self) {
7637 [database_ upgrade];
7643 [self slideUp:[[[UIActionSheet alloc]
7645 buttons:[NSArray arrayWithObjects:UCLocalize("CONTINUE_QUEUING"), UCLocalize("CANCEL_CLEAR"), nil]
7646 defaultButtonIndex:1
7653 @synchronized (self) {
7656 if (confirm_ != nil) {
7664 [overlay_ removeFromSuperview];
7668 detachNewThreadSelector:@selector(perform)
7671 title:UCLocalize("RUNNING")
7675 - (void) progressViewIsComplete:(ProgressView *)progress {
7676 if (confirm_ != nil) {
7677 [underlay_ addSubview:overlay_];
7678 [confirm_ popFromSuperviewAnimated:NO];
7684 - (void) setPage:(RVPage *)page {
7685 [page resetViewAnimated:NO];
7686 [page setDelegate:self];
7687 [book_ setPage:page];
7690 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7691 CydiaBrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7692 [browser loadURL:url];
7696 - (void) _setHomePage {
7697 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7700 - (SectionsView *) sectionsView {
7701 if (sections_ == nil)
7702 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7706 - (void) buttonBarItemTapped:(id)sender {
7707 unsigned tag = [sender tag];
7709 [book_ resetViewAnimated:YES];
7711 } else if (tag_ == 2 && tag != 2)
7712 [[self sectionsView] resetView];
7715 case 1: [self _setHomePage]; break;
7717 case 2: [self setPage:[self sectionsView]]; break;
7718 case 3: [self setPage:changes_]; break;
7719 case 4: [self setPage:manage_]; break;
7720 case 5: [self setPage:search_]; break;
7722 default: _assert(false);
7728 - (void) applicationWillSuspend {
7730 [super applicationWillSuspend];
7733 - (void) askForSettings {
7734 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
7736 UIActionSheet *role = [[[UIActionSheet alloc]
7737 initWithTitle:UCLocalize("WHO_ARE_YOU")
7738 buttons:[NSArray arrayWithObjects:
7739 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
7740 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
7741 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
7743 defaultButtonIndex:-1
7748 [role setBodyText:UCLocalize("ROLE_EX")];
7749 [role popupAlertAnimated:YES];
7752 - (void) setPackageView:(PackageView *)view {
7754 [view setPackage:nil];
7755 #if RecyclePackageViews
7756 if ([details_ count] < 3)
7757 [details_ addObject:view];
7762 - (PackageView *) _packageView {
7763 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7766 - (PackageView *) packageView {
7767 #if RecyclePackageViews
7769 size_t count([details_ count]);
7772 view = [self _packageView];
7774 [details_ addObject:[self _packageView]];
7776 view = [[[details_ lastObject] retain] autorelease];
7777 [details_ removeLastObject];
7784 return [self _packageView];
7790 [self setStatusBarShowsProgress:NO];
7791 [self removeProgressHUD:hud_];
7796 pid_t pid = ExecFork();
7798 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7799 perror("launchctl stop");
7806 [self askForSettings];
7811 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7813 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7814 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7815 0, 0, screenrect.size.width, screenrect.size.height - 48
7816 ) database:database_];
7818 [book_ setDelegate:self];
7820 [overlay_ addSubview:book_];
7822 NSArray *buttonitems = [NSArray arrayWithObjects:
7823 [NSDictionary dictionaryWithObjectsAndKeys:
7824 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7825 @"home-up.png", kUIButtonBarButtonInfo,
7826 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7827 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7828 self, kUIButtonBarButtonTarget,
7829 @"Cydia", kUIButtonBarButtonTitle,
7830 @"0", kUIButtonBarButtonType,
7833 [NSDictionary dictionaryWithObjectsAndKeys:
7834 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7835 @"install-up.png", kUIButtonBarButtonInfo,
7836 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7837 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7838 self, kUIButtonBarButtonTarget,
7839 UCLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7840 @"0", kUIButtonBarButtonType,
7843 [NSDictionary dictionaryWithObjectsAndKeys:
7844 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7845 @"changes-up.png", kUIButtonBarButtonInfo,
7846 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7847 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7848 self, kUIButtonBarButtonTarget,
7849 UCLocalize("CHANGES"), kUIButtonBarButtonTitle,
7850 @"0", kUIButtonBarButtonType,
7853 [NSDictionary dictionaryWithObjectsAndKeys:
7854 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7855 @"manage-up.png", kUIButtonBarButtonInfo,
7856 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7857 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7858 self, kUIButtonBarButtonTarget,
7859 UCLocalize("MANAGE"), kUIButtonBarButtonTitle,
7860 @"0", kUIButtonBarButtonType,
7863 [NSDictionary dictionaryWithObjectsAndKeys:
7864 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7865 @"search-up.png", kUIButtonBarButtonInfo,
7866 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7867 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7868 self, kUIButtonBarButtonTarget,
7869 UCLocalize("SEARCH"), kUIButtonBarButtonTitle,
7870 @"0", kUIButtonBarButtonType,
7874 toolbar_ = [[UIToolbar alloc]
7876 withFrame:CGRectMake(
7877 0, screenrect.size.height - ButtonBarHeight_,
7878 screenrect.size.width, ButtonBarHeight_
7880 withItemList:buttonitems
7883 [toolbar_ setDelegate:self];
7884 [toolbar_ setBarStyle:1];
7885 [toolbar_ setButtonBarTrackingMode:2];
7887 int buttons[5] = {1, 2, 3, 4, 5};
7888 [toolbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7889 [toolbar_ showButtonGroup:0 withDuration:0];
7891 for (int i = 0; i != 5; ++i)
7892 [[toolbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7893 i * 64 + 2, 1, 60, ButtonBarHeight_
7896 [toolbar_ showSelectionForButton:1];
7897 [overlay_ addSubview:toolbar_];
7899 [UIKeyboard initImplementationNow];
7900 CGSize keysize = [UIKeyboard defaultSize];
7901 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7902 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7903 [overlay_ addSubview:keyboard_];
7905 [underlay_ addSubview:overlay_];
7909 [self sectionsView];
7910 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7911 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7913 manage_ = (ManageView *) [[self
7914 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7915 withClass:[ManageView class]
7918 #if RecyclePackageViews
7919 details_ = [[NSMutableArray alloc] initWithCapacity:4];
7920 [details_ addObject:[self _packageView]];
7921 [details_ addObject:[self _packageView]];
7926 [self _setHomePage];
7929 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7930 NSString *context([sheet context]);
7932 if ([context isEqualToString:@"missing"])
7934 else if ([context isEqualToString:@"cancel"]) {
7952 @synchronized (self) {
7957 [toolbar_ setBadgeValue:UCLocalize("Q_D") forButton:4];
7961 if (confirm_ != nil) {
7966 } else if ([context isEqualToString:@"fixhalf"]) {
7969 @synchronized (self) {
7970 for (Package *broken in broken_) {
7973 NSString *id = [broken id];
7974 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7975 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7976 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7977 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7986 [broken_ removeAllObjects];
7995 } else if ([context isEqualToString:@"role"]) {
7997 case 1: Role_ = @"User"; break;
7998 case 2: Role_ = @"Hacker"; break;
7999 case 3: Role_ = @"Developer"; break;
8006 bool reset = Settings_ != nil;
8008 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8012 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8022 } else if ([context isEqualToString:@"upgrade"]) {
8025 @synchronized (self) {
8026 for (Package *essential in essential_)
8027 [essential install];
8050 - (void) reorganize { _pooled
8051 system("/usr/libexec/cydia/free.sh");
8052 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
8055 - (void) applicationSuspend:(__GSEvent *)event {
8056 if (hud_ == nil && ![progress_ isRunning])
8057 [super applicationSuspend:event];
8060 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8062 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8065 - (void) _setSuspended:(BOOL)value {
8067 [super _setSuspended:value];
8070 - (UIProgressHUD *) addProgressHUD {
8071 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8072 [window_ setUserInteractionEnabled:NO];
8074 [progress_ addSubview:hud];
8078 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8080 [hud removeFromSuperview];
8081 [window_ setUserInteractionEnabled:YES];
8084 - (RVPage *) pageForPackage:(NSString *)name {
8085 if (Package *package = [database_ packageWithName:name]) {
8086 PackageView *view([self packageView]);
8087 [view setPackage:package];
8090 UIActionSheet *sheet = [[[UIActionSheet alloc]
8091 initWithTitle:UCLocalize("CANNOT_LOCATE_PACKAGE")
8092 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
8093 defaultButtonIndex:0
8098 [sheet setBodyText:[NSString stringWithFormat:UCLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
8100 [sheet popupAlertAnimated:YES];
8105 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8109 NSString *href([url absoluteString]);
8110 if ([href hasPrefix:@"apptapp://package/"])
8111 return [self pageForPackage:[href substringFromIndex:18]];
8113 NSString *scheme([[url scheme] lowercaseString]);
8114 if (![scheme isEqualToString:@"cydia"])
8116 NSString *path([url absoluteString]);
8117 if ([path length] < 8)
8119 path = [path substringFromIndex:8];
8120 if (![path hasPrefix:@"/"])
8121 path = [@"/" stringByAppendingString:path];
8123 if ([path isEqualToString:@"/add-source"])
8124 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8125 else if ([path isEqualToString:@"/storage"])
8126 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CydiaBrowserView class]];
8127 else if ([path isEqualToString:@"/sources"])
8128 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8129 else if ([path isEqualToString:@"/packages"])
8130 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8131 else if ([path hasPrefix:@"/url/"])
8132 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CydiaBrowserView class]];
8133 else if ([path hasPrefix:@"/launch/"])
8134 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8135 else if ([path hasPrefix:@"/package-settings/"])
8136 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8137 else if ([path hasPrefix:@"/package-signature/"])
8138 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8139 else if ([path hasPrefix:@"/package/"])
8140 return [self pageForPackage:[path substringFromIndex:9]];
8141 else if ([path hasPrefix:@"/files/"]) {
8142 NSString *name = [path substringFromIndex:7];
8144 if (Package *package = [database_ packageWithName:name]) {
8145 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8146 [files setPackage:package];
8154 - (void) applicationOpenURL:(NSURL *)url {
8155 [super applicationOpenURL:url];
8157 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8158 [self setPage:page];
8159 [toolbar_ showSelectionForButton:tag];
8164 - (void) applicationDidFinishLaunching:(id)unused {
8165 [BrowserView _initialize];
8167 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8169 Font12_ = [[UIFont systemFontOfSize:12] retain];
8170 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8171 Font14_ = [[UIFont systemFontOfSize:14] retain];
8172 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8173 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8177 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8178 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8180 window_ = [[UIWindow alloc] initWithContentRect:[UIHardware fullScreenApplicationContentRect]];
8181 [window_ orderFront:self];
8182 [window_ makeKey:self];
8183 [window_ setHidden:NO];
8185 database_ = [Database sharedInstance];
8187 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8188 [database_ setDelegate:progress_];
8189 [window_ setContentView:progress_];
8191 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8192 [progress_ setContentView:underlay_];
8194 [progress_ resetView];
8197 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8198 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8199 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8200 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8201 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8202 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8203 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8204 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8205 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8208 [self setIdleTimerDisabled:YES];
8210 hud_ = [[self addProgressHUD] retain];
8211 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8213 [self setStatusBarShowsProgress:YES];
8216 detachNewThreadSelector:@selector(reorganize)
8224 - (void) showKeyboard:(BOOL)show {
8225 CGSize keysize([UIKeyboard defaultSize]);
8226 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8227 CGRect keyup(keydown);
8228 keyup.origin.y -= keysize.height;
8230 UIFrameAnimation *animation([[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease]);
8231 [animation setSignificantRectFields:2];
8234 [animation setStartFrame:keydown];
8235 [animation setEndFrame:keyup];
8236 [keyboard_ activate];
8238 [animation setStartFrame:keyup];
8239 [animation setEndFrame:keydown];
8240 [keyboard_ deactivate];
8243 [[UIAnimator sharedAnimator]
8244 addAnimations:[NSArray arrayWithObjects:animation, nil]
8245 withDuration:KeyboardTime_
8250 - (void) slideUp:(UIActionSheet *)alert {
8251 [alert presentSheetInView:overlay_];
8257 id Alloc_(id self, SEL selector) {
8258 id object = alloc_(self, selector);
8259 lprintf("[%s]A-%p\n", self->isa->name, object);
8264 id Dealloc_(id self, SEL selector) {
8265 id object = dealloc_(self, selector);
8266 lprintf("[%s]D-%p\n", self->isa->name, object);
8270 Class $WebDefaultUIKitDelegate;
8272 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8273 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8274 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8275 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8278 int main(int argc, char *argv[]) { _pooled
8281 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8283 /* Library Hacks {{{ */
8284 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8286 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8287 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8288 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8289 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8290 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8293 /* Set Locale {{{ */
8294 Locale_ = CFLocaleCopyCurrent();
8295 Languages_ = [NSLocale preferredLanguages];
8296 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8297 //NSLog(@"%@", [Languages_ description]);
8299 if (Languages_ == nil || [Languages_ count] == 0)
8302 lang = [[Languages_ objectAtIndex:0] UTF8String];
8303 setenv("LANG", lang, true);
8304 //std::setlocale(LC_ALL, lang);
8305 NSLog(@"Setting Language: %s", lang);
8308 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8310 /* Parse Arguments {{{ */
8311 bool substrate(false);
8317 for (int argi(1); argi != argc; ++argi)
8318 if (strcmp(argv[argi], "--") == 0) {
8320 argv[argi] = argv[0];
8326 for (int argi(1); argi != arge; ++argi)
8327 if (strcmp(args[argi], "--substrate") == 0)
8330 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8334 App_ = [[NSBundle mainBundle] bundlePath];
8335 Home_ = NSHomeDirectory();
8341 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8342 alloc_ = alloc->method_imp;
8343 alloc->method_imp = (IMP) &Alloc_;*/
8345 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8346 dealloc_ = dealloc->method_imp;
8347 dealloc->method_imp = (IMP) &Dealloc_;*/
8349 /* System Information {{{ */
8353 size = sizeof(maxproc);
8354 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8355 perror("sysctlbyname(\"kern.maxproc\", ?)");
8356 else if (maxproc < 64) {
8358 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8359 perror("sysctlbyname(\"kern.maxproc\", #)");
8362 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8363 char *osversion = new char[size];
8364 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8365 perror("sysctlbyname(\"kern.osversion\", ?)");
8367 System_ = [NSString stringWithUTF8String:osversion];
8369 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8370 char *machine = new char[size];
8371 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8372 perror("sysctlbyname(\"hw.machine\", ?)");
8376 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8377 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8378 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8379 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8383 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8384 NSData *data((NSData *) ecid);
8385 size_t length([data length]);
8386 uint8_t bytes[length];
8387 [data getBytes:bytes];
8388 char string[length * 2 + 1];
8389 for (size_t i(0); i != length; ++i)
8390 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8391 ChipID_ = [NSString stringWithUTF8String:string];
8395 IOObjectRelease(service);
8399 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8401 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8402 Build_ = [system objectForKey:@"ProductBuildVersion"];
8403 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8404 Product_ = [info objectForKey:@"SafariProductVersion"];
8405 Safari_ = [info objectForKey:@"CFBundleVersion"];
8408 /* Load Database {{{ */
8410 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8412 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8415 if (Metadata_ == NULL)
8416 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8418 Settings_ = [Metadata_ objectForKey:@"Settings"];
8420 Packages_ = [Metadata_ objectForKey:@"Packages"];
8421 Sections_ = [Metadata_ objectForKey:@"Sections"];
8422 Sources_ = [Metadata_ objectForKey:@"Sources"];
8425 if (Settings_ != nil)
8426 Role_ = [Settings_ objectForKey:@"Role"];
8428 if (Packages_ == nil) {
8429 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8430 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8433 if (Sections_ == nil) {
8434 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8435 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8438 if (Sources_ == nil) {
8439 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8440 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8445 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8448 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8450 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8451 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8452 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8453 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8455 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8456 unlink("/tmp/.cydia.fw");
8458 } else if (access("/User", F_OK) != 0) {
8461 system("/usr/libexec/cydia/firmware.sh");
8465 _assert([[NSFileManager defaultManager]
8466 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8467 withIntermediateDirectories:YES
8472 if (access("/tmp/cydia.chk", F_OK) == 0) {
8473 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8474 _assert(errno == ENOENT);
8475 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8476 _assert(errno == ENOENT);
8479 /* APT Initialization {{{ */
8480 _assert(pkgInitConfig(*_config));
8481 _assert(pkgInitSystem(*_config, _system));
8484 _config->Set("APT::Acquire::Translation", lang);
8485 _config->Set("Acquire::http::Timeout", 15);
8486 _config->Set("Acquire::http::MaxParallel", 3);
8488 /* Color Choices {{{ */
8489 space_ = CGColorSpaceCreateDeviceRGB();
8491 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8492 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8493 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8494 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8495 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8496 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8497 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8498 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8499 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8501 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8502 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8504 /* UIKit Configuration {{{ */
8505 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8506 if ($GSFontSetUseLegacyFontMetrics != NULL)
8507 $GSFontSetUseLegacyFontMetrics(YES);
8509 UIKeyboardDisableAutomaticAppearance();
8513 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8515 CGColorSpaceRelease(space_);