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 static _finline NSString *CydiaURL(NSString *path) {
255 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
256 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
257 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
258 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
259 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
260 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
263 /* [NSObject yieldToSelector:(withObject:)] {{{*/
264 @interface NSObject (Cydia)
265 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
266 - (id) yieldToSelector:(SEL)selector;
269 @implementation NSObject (Cydia)
274 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
275 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
276 id object([[context objectAtIndex:1] nonretainedObjectValue]);
277 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
279 /* XXX: deal with exceptions */
280 id value([self performSelector:selector withObject:object]);
282 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
283 [context removeAllObjects];
284 if ([signature methodReturnLength] != 0 && value != nil)
285 [context addObject:value];
290 performSelectorOnMainThread:@selector(doNothing)
296 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
297 /*return [self performSelector:selector withObject:object];*/
299 volatile bool stopped(false);
301 NSMutableArray *context([NSMutableArray arrayWithObjects:
302 [NSValue valueWithPointer:selector],
303 [NSValue valueWithNonretainedObject:object],
304 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
307 NSThread *thread([[[NSThread alloc]
309 selector:@selector(_yieldToContext:)
315 NSRunLoop *loop([NSRunLoop currentRunLoop]);
316 NSDate *future([NSDate distantFuture]);
318 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
320 return [context count] == 0 ? nil : [context objectAtIndex:0];
323 - (id) yieldToSelector:(SEL)selector {
324 return [self yieldToSelector:selector withObject:nil];
330 @interface CYActionSheet : UIActionSheet {
334 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
337 @implementation CYActionSheet
339 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
340 if ((self = [super initWithTitle:title buttons:buttons defaultButtonIndex:index delegate:self context:nil]) != nil) {
344 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
348 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
350 [self popupAlertAnimated:animated];
351 NSRunLoop *loop([NSRunLoop currentRunLoop]);
352 NSDate *future([NSDate distantFuture]);
353 while (button_ == 0 && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
359 /* NSForcedOrderingSearch doesn't work on the iPhone */
360 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
361 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
362 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
364 /* Information Dictionaries {{{ */
365 @interface NSMutableArray (Cydia)
366 - (void) addInfoDictionary:(NSDictionary *)info;
369 @implementation NSMutableArray (Cydia)
371 - (void) addInfoDictionary:(NSDictionary *)info {
372 [self addObject:info];
377 @interface NSMutableDictionary (Cydia)
378 - (void) addInfoDictionary:(NSDictionary *)info;
381 @implementation NSMutableDictionary (Cydia)
383 - (void) addInfoDictionary:(NSDictionary *)info {
384 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
389 /* Pop Transitions {{{ */
390 @interface PopTransitionView : UITransitionView {
395 @implementation PopTransitionView
397 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
398 if (from != nil && to == nil)
399 [self removeFromSuperview];
404 @implementation UIView (PopUpView)
406 - (void) popFromSuperviewAnimated:(BOOL)animated {
407 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
410 - (void) popSubview:(UIView *)view {
411 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
412 [transition setDelegate:transition];
413 [self addSubview:transition];
415 UIView *blank = [[[UIView alloc] initWithFrame:[transition bounds]] autorelease];
416 [transition transition:UITransitionNone toView:blank];
417 [transition transition:UITransitionPushFromBottom toView:view];
423 #define lprintf(args...) fprintf(stderr, args)
426 #define TraceLogging (1 && !ForRelease)
427 #define HistogramInsertionSort (0 && !ForRelease)
428 #define ProfileTimes (0 && !ForRelease)
429 #define ForSaurik (0 && !ForRelease)
430 #define LogBrowser (0 && !ForRelease)
431 #define TrackResize (0 && !ForRelease)
432 #define ManualRefresh (0 && !ForRelease)
433 #define ShowInternals (0 && !ForRelease)
434 #define IgnoreInstall (0 && !ForRelease)
435 #define RecycleWebViews 0
436 #define RecyclePackageViews 1
437 #define AlwaysReload (0 && !ForRelease)
441 #define _trace(args...)
446 #define _profile(name) {
449 #define PrintTimes() do {} while (false)
453 typedef uint32_t (*SKRadixFunction)(id, void *);
455 @interface NSMutableArray (Radix)
456 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
457 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
465 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
466 struct RadixItem_ *lhs(swap), *rhs(swap + count);
468 static const size_t width = 32;
469 static const size_t bits = 11;
470 static const size_t slots = 1 << bits;
471 static const size_t passes = (width + (bits - 1)) / bits;
473 size_t *hist(new size_t[slots]);
475 for (size_t pass(0); pass != passes; ++pass) {
476 memset(hist, 0, sizeof(size_t) * slots);
478 for (size_t i(0); i != count; ++i) {
479 uint32_t key(lhs[i].key);
481 key &= _not(uint32_t) >> width - bits;
486 for (size_t i(0); i != slots; ++i) {
487 size_t local(offset);
492 for (size_t i(0); i != count; ++i) {
493 uint32_t key(lhs[i].key);
495 key &= _not(uint32_t) >> width - bits;
496 rhs[hist[key]++] = lhs[i];
499 RadixItem_ *tmp(lhs);
506 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
507 for (size_t i(0); i != count; ++i)
508 [values addObject:[self objectAtIndex:lhs[i].index]];
509 [self setArray:values];
514 @implementation NSMutableArray (Radix)
516 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
517 size_t count([self count]);
522 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
523 [invocation setSelector:selector];
524 [invocation setArgument:&object atIndex:2];
526 /* XXX: this is an unsafe optimization of doomy hell */
527 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
528 _assert(method != NULL);
529 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
530 _assert(imp != NULL);
533 struct RadixItem_ *swap(new RadixItem_[count * 2]);
535 for (size_t i(0); i != count; ++i) {
536 RadixItem_ &item(swap[i]);
539 id object([self objectAtIndex:i]);
542 [invocation setTarget:object];
544 [invocation getReturnValue:&item.key];
546 item.key = imp(object, selector, object);
550 RadixSort_(self, count, swap);
553 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
554 size_t count([self count]);
555 struct RadixItem_ *swap(new RadixItem_[count * 2]);
557 for (size_t i(0); i != count; ++i) {
558 RadixItem_ &item(swap[i]);
561 id object([self objectAtIndex:i]);
562 item.key = function(object, argument);
565 RadixSort_(self, count, swap);
570 /* Insertion Sort {{{ */
572 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
573 const char *ptr = (const char *)list;
575 CFIndex half = count / 2;
576 const char *probe = ptr + elementSize * half;
577 CFComparisonResult cr = comparator(element, probe, context);
578 if (0 == cr) return (probe - (const char *)list) / elementSize;
579 ptr = (cr < 0) ? ptr : probe + elementSize;
580 count = (cr < 0) ? half : (half + (count & 1) - 1);
582 return (ptr - (const char *)list) / elementSize;
585 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
586 const char *ptr = (const char *)list;
588 CFIndex half = count / 2;
589 const char *probe = ptr + elementSize * half;
590 CFComparisonResult cr = comparator(element, probe, context);
591 if (0 == cr) return (probe - (const char *)list) / elementSize;
592 ptr = (cr < 0) ? ptr : probe + elementSize;
593 count = (cr < 0) ? half : (half + (count & 1) - 1);
595 return (ptr - (const char *)list) / elementSize;
598 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
599 if (range.length == 0)
601 const void **values(new const void *[range.length]);
602 CFArrayGetValues(array, range, values);
604 #if HistogramInsertionSort
605 uint32_t total(0), *offsets(new uint32_t[range.length]);
608 for (CFIndex index(1); index != range.length; ++index) {
609 const void *value(values[index]);
610 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
611 CFIndex correct(index);
612 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
615 if (correct != index) {
616 size_t offset(index - correct);
617 #if HistogramInsertionSort
621 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
623 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
624 values[correct] = value;
628 CFArrayReplaceValues(array, range, values, range.length);
631 #if HistogramInsertionSort
632 for (CFIndex index(0); index != range.length; ++index)
633 if (offsets[index] != 0)
634 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
635 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
642 /* Apple Bug Fixes {{{ */
643 @implementation UIWebDocumentView (Cydia)
645 - (void) _setScrollerOffset:(CGPoint)offset {
646 UIScroller *scroller([self _scroller]);
648 CGSize size([scroller contentSize]);
649 CGSize bounds([scroller bounds].size);
652 max.x = size.width - bounds.width;
653 max.y = size.height - bounds.height;
661 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
662 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
664 [scroller setOffset:offset];
670 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
671 size_t length([self length] - state->state);
674 else if (length > count)
676 for (size_t i(0); i != length; ++i)
677 objects[i] = [self item:state->state++];
678 state->itemsPtr = objects;
679 state->mutationsPtr = (unsigned long *) self;
683 @interface NSString (UIKit)
684 - (NSString *) stringByAddingPercentEscapes;
687 /* Cydia NSString Additions {{{ */
688 @interface NSString (Cydia)
689 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
690 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
691 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
692 - (NSComparisonResult) compareByPath:(NSString *)other;
693 - (NSString *) stringByCachingURLWithCurrentCDN;
694 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
697 @implementation NSString (Cydia)
699 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
700 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
703 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
704 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
705 memcpy(data, bytes, length);
706 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
709 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
710 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
713 - (NSComparisonResult) compareByPath:(NSString *)other {
714 NSString *prefix = [self commonPrefixWithString:other options:0];
715 size_t length = [prefix length];
717 NSRange lrange = NSMakeRange(length, [self length] - length);
718 NSRange rrange = NSMakeRange(length, [other length] - length);
720 lrange = [self rangeOfString:@"/" options:0 range:lrange];
721 rrange = [other rangeOfString:@"/" options:0 range:rrange];
723 NSComparisonResult value;
725 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
726 value = NSOrderedSame;
727 else if (lrange.location == NSNotFound)
728 value = NSOrderedAscending;
729 else if (rrange.location == NSNotFound)
730 value = NSOrderedDescending;
732 value = NSOrderedSame;
734 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
735 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
736 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
737 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
739 NSComparisonResult result = [lpath compare:rpath];
740 return result == NSOrderedSame ? value : result;
743 - (NSString *) stringByCachingURLWithCurrentCDN {
745 stringByReplacingOccurrencesOfString:@"://"
746 withString:@"://ne.edgecastcdn.net/8003A4/"
748 /* XXX: this is somewhat inaccurate */
749 range:NSMakeRange(0, 10)
753 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
754 return [(id)CFURLCreateStringByAddingPercentEscapes(
759 kCFStringEncodingUTF8
766 /* C++ NSString Wrapper Cache {{{ */
773 _finline void clear_() {
774 if (cache_ != NULL) {
781 _finline bool empty() const {
785 _finline size_t size() const {
789 _finline char *data() const {
793 _finline void clear() {
798 _finline CYString() :
805 _finline ~CYString() {
809 void operator =(const CYString &rhs) {
813 if (rhs.cache_ == nil)
816 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
819 void set(apr_pool_t *pool, const char *data, size_t size) {
825 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
826 memcpy(temp, data, size);
833 _finline void set(apr_pool_t *pool, const char *data) {
834 set(pool, data, data == NULL ? 0 : strlen(data));
837 _finline void set(apr_pool_t *pool, const std::string &rhs) {
838 set(pool, rhs.data(), rhs.size());
841 bool operator ==(const CYString &rhs) const {
842 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
845 operator CFStringRef() {
846 if (cache_ == NULL) {
849 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
853 _finline operator id() {
854 return (NSString *) static_cast<CFStringRef>(*this);
858 /* C++ NSString Algorithm Adapters {{{ */
860 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
863 struct NSStringMapHash :
864 std::unary_function<NSString *, size_t>
866 _finline size_t operator ()(NSString *value) const {
867 return CFStringHashNSString((CFStringRef) value);
871 struct NSStringMapLess :
872 std::binary_function<NSString *, NSString *, bool>
874 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
875 return [lhs compare:rhs] == NSOrderedAscending;
879 struct NSStringMapEqual :
880 std::binary_function<NSString *, NSString *, bool>
882 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
883 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
884 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
885 //[lhs isEqualToString:rhs];
890 /* Perl-Compatible RegEx {{{ */
900 Pcre(const char *regex) :
905 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
908 lprintf("%d:%s\n", offset, error);
912 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
913 matches_ = new int[(capture_ + 1) * 3];
921 NSString *operator [](size_t match) {
922 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
925 bool operator ()(NSString *data) {
926 // XXX: length is for characters, not for bytes
927 return operator ()([data UTF8String], [data length]);
930 bool operator ()(const char *data, size_t size) {
932 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
936 /* Mime Addresses {{{ */
937 @interface Address : NSObject {
943 - (NSString *) address;
945 - (void) setAddress:(NSString *)address;
947 + (Address *) addressWithString:(NSString *)string;
948 - (Address *) initWithString:(NSString *)string;
951 @implementation Address
960 - (NSString *) name {
964 - (NSString *) address {
968 - (void) setAddress:(NSString *)address {
970 [address_ autorelease];
974 address_ = [address retain];
977 + (Address *) addressWithString:(NSString *)string {
978 return [[[Address alloc] initWithString:string] autorelease];
981 + (NSArray *) _attributeKeys {
982 return [NSArray arrayWithObjects:@"address", @"name", nil];
985 - (NSArray *) attributeKeys {
986 return [[self class] _attributeKeys];
989 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
990 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
993 - (Address *) initWithString:(NSString *)string {
994 if ((self = [super init]) != nil) {
995 const char *data = [string UTF8String];
996 size_t size = [string length];
998 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
1000 if (address_r(data, size)) {
1001 name_ = [address_r[1] retain];
1002 address_ = [address_r[2] retain];
1004 name_ = [string retain];
1012 /* CoreGraphics Primitives {{{ */
1023 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
1026 Set(space, red, green, blue, alpha);
1031 CGColorRelease(color_);
1038 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1040 float color[] = {red, green, blue, alpha};
1041 color_ = CGColorCreate(space, color);
1044 operator CGColorRef() {
1050 /* Random Global Variables {{{ */
1051 static const int PulseInterval_ = 50000;
1052 static const int ButtonBarHeight_ = 48;
1053 static const float KeyboardTime_ = 0.3f;
1056 static NSArray *Finishes_;
1058 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1059 #define NotifyConfig_ "/etc/notify.conf"
1061 static bool Queuing_;
1063 static CGColor Blue_;
1064 static CGColor Blueish_;
1065 static CGColor Black_;
1066 static CGColor Off_;
1067 static CGColor White_;
1068 static CGColor Gray_;
1069 static CGColor Green_;
1070 static CGColor Purple_;
1071 static CGColor Purplish_;
1073 static UIColor *InstallingColor_;
1074 static UIColor *RemovingColor_;
1076 static NSString *App_;
1077 static NSString *Home_;
1079 static BOOL Advanced_;
1080 static BOOL Ignored_;
1082 static UIFont *Font12_;
1083 static UIFont *Font12Bold_;
1084 static UIFont *Font14_;
1085 static UIFont *Font18Bold_;
1086 static UIFont *Font22Bold_;
1088 static const char *Machine_ = NULL;
1089 static const NSString *System_ = NULL;
1090 static const NSString *SerialNumber_ = nil;
1091 static const NSString *ChipID_ = nil;
1092 static const NSString *UniqueID_ = nil;
1093 static const NSString *Build_ = nil;
1094 static const NSString *Product_ = nil;
1095 static const NSString *Safari_ = nil;
1097 static CFLocaleRef Locale_;
1098 static NSArray *Languages_;
1099 static CGColorSpaceRef space_;
1101 static bool reload_;
1103 static NSDictionary *SectionMap_;
1104 static NSMutableDictionary *Metadata_;
1105 static _transient NSMutableDictionary *Settings_;
1106 static _transient NSString *Role_;
1107 static _transient NSMutableDictionary *Packages_;
1108 static _transient NSMutableDictionary *Sections_;
1109 static _transient NSMutableDictionary *Sources_;
1110 static bool Changed_;
1111 static NSDate *now_;
1114 static NSMutableArray *Documents_;
1118 /* Display Helpers {{{ */
1119 inline float Interpolate(float begin, float end, float fraction) {
1120 return (end - begin) * fraction + begin;
1123 /* XXX: localize this! */
1124 NSString *SizeString(double size) {
1125 bool negative = size < 0;
1130 while (size > 1024) {
1135 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1137 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1140 static _finline CFStringRef CFCString(const char *value) {
1141 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1144 const char *StripVersion_(const char *version) {
1145 const char *colon(strchr(version, ':'));
1147 version = colon + 1;
1151 CFStringRef StripVersion(const char *version) {
1152 const char *colon(strchr(version, ':'));
1154 version = colon + 1;
1155 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1157 return CFCString(version);
1160 NSString *LocalizeSection(NSString *section) {
1161 static Pcre title_r("^(.*?) \\((.*)\\)$");
1162 if (title_r(section)) {
1163 NSString *parent(title_r[1]);
1164 NSString *child(title_r[2]);
1166 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1167 LocalizeSection(parent),
1168 LocalizeSection(child)
1172 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1175 NSString *Simplify(NSString *title) {
1176 const char *data = [title UTF8String];
1177 size_t size = [title length];
1179 static Pcre square_r("^\\[(.*)\\]$");
1180 if (square_r(data, size))
1181 return Simplify(square_r[1]);
1183 static Pcre paren_r("^\\((.*)\\)$");
1184 if (paren_r(data, size))
1185 return Simplify(paren_r[1]);
1187 static Pcre title_r("^(.*?) \\((.*)\\)$");
1188 if (title_r(data, size))
1189 return Simplify(title_r[1]);
1195 NSString *GetLastUpdate() {
1196 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1199 return UCLocalize("NEVER_OR_UNKNOWN");
1201 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1202 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1204 CFRelease(formatter);
1206 return [(NSString *) formatted autorelease];
1209 bool isSectionVisible(NSString *section) {
1210 NSDictionary *metadata([Sections_ objectForKey:section]);
1211 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1212 return hidden == nil || ![hidden boolValue];
1215 /* Delegate Prototypes {{{ */
1219 @interface NSObject (ProgressDelegate)
1222 @protocol ProgressDelegate
1223 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1224 - (void) setProgressTitle:(NSString *)title;
1225 - (void) setProgressPercent:(float)percent;
1226 - (void) startProgress;
1227 - (void) addProgressOutput:(NSString *)output;
1228 - (bool) isCancelling:(size_t)received;
1231 @protocol ConfigurationDelegate
1232 - (void) repairWithSelector:(SEL)selector;
1233 - (void) setConfigurationData:(NSString *)data;
1238 @protocol CydiaDelegate
1239 - (void) setPackageView:(PackageView *)view;
1240 - (void) clearPackage:(Package *)package;
1241 - (void) installPackage:(Package *)package;
1242 - (void) removePackage:(Package *)package;
1243 - (void) slideUp:(UIActionSheet *)alert;
1244 - (void) distUpgrade;
1245 - (void) updateData;
1247 - (void) askForSettings;
1248 - (UIProgressHUD *) addProgressHUD;
1249 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1250 - (RVPage *) pageForPackage:(NSString *)name;
1251 - (PackageView *) packageView;
1255 /* Status Delegation {{{ */
1257 public pkgAcquireStatus
1260 _transient NSObject<ProgressDelegate> *delegate_;
1268 void setDelegate(id delegate) {
1269 delegate_ = delegate;
1272 NSObject<ProgressDelegate> *getDelegate() const {
1276 virtual bool MediaChange(std::string media, std::string drive) {
1280 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1283 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1284 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1285 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1288 virtual void Done(pkgAcquire::ItemDesc &item) {
1291 virtual void Fail(pkgAcquire::ItemDesc &item) {
1293 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1294 item.Owner->Status == pkgAcquire::Item::StatDone
1298 std::string &error(item.Owner->ErrorText);
1302 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1303 NSArray *fields([description componentsSeparatedByString:@" "]);
1304 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1306 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1307 withObject:[NSArray arrayWithObjects:
1308 [NSString stringWithUTF8String:error.c_str()],
1315 virtual bool Pulse(pkgAcquire *Owner) {
1316 bool value = pkgAcquireStatus::Pulse(Owner);
1319 double(CurrentBytes + CurrentItems) /
1320 double(TotalBytes + TotalItems)
1323 [delegate_ setProgressPercent:percent];
1324 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1327 virtual void Start() {
1328 [delegate_ startProgress];
1331 virtual void Stop() {
1335 /* Progress Delegation {{{ */
1340 _transient id<ProgressDelegate> delegate_;
1344 virtual void Update() {
1345 /*if (abs(Percent - percent_) > 2)
1346 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1350 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1351 [delegate_ setProgressPercent:(Percent / 100)];*/
1361 void setDelegate(id delegate) {
1362 delegate_ = delegate;
1365 id getDelegate() const {
1369 virtual void Done() {
1371 //[delegate_ setProgressPercent:1];
1376 /* Database Interface {{{ */
1377 typedef std::map< unsigned long, _H<Source> > SourceMap;
1379 @interface Database : NSObject {
1385 pkgCacheFile cache_;
1386 pkgDepCache::Policy *policy_;
1387 pkgRecords *records_;
1388 pkgProblemResolver *resolver_;
1389 pkgAcquire *fetcher_;
1391 SPtr<pkgPackageManager> manager_;
1392 pkgSourceList *list_;
1395 NSMutableArray *packages_;
1397 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1406 + (Database *) sharedInstance;
1409 - (void) _readCydia:(NSNumber *)fd;
1410 - (void) _readStatus:(NSNumber *)fd;
1411 - (void) _readOutput:(NSNumber *)fd;
1415 - (Package *) packageWithName:(NSString *)name;
1417 - (pkgCacheFile &) cache;
1418 - (pkgDepCache::Policy *) policy;
1419 - (pkgRecords *) records;
1420 - (pkgProblemResolver *) resolver;
1421 - (pkgAcquire &) fetcher;
1422 - (pkgSourceList &) list;
1423 - (NSArray *) packages;
1424 - (NSArray *) sources;
1425 - (void) reloadData;
1433 - (void) setVisible;
1435 - (void) updateWithStatus:(Status &)status;
1437 - (void) setDelegate:(id)delegate;
1438 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1441 /* Delegate Helpers {{{ */
1442 @implementation NSObject(ProgressDelegate)
1444 - (void) _setProgressErrorPackage:(NSArray *)args {
1445 [self performSelector:@selector(setProgressError:forPackage:)
1446 withObject:[args objectAtIndex:0]
1447 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1451 - (void) _setProgressErrorTitle:(NSArray *)args {
1452 [self performSelector:@selector(setProgressError:withTitle:)
1453 withObject:[args objectAtIndex:0]
1454 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1458 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1459 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1460 withObject:[NSArray arrayWithObjects:error, title, nil]
1465 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1466 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1467 // XXX: holy typecast batman!
1468 [(id<ProgressDelegate>)self setProgressError:error withTitle:(package == nil ? id : [package name])];
1474 /* Source Class {{{ */
1475 @interface Source : NSObject {
1476 CYString depiction_;
1477 CYString description_;
1483 CYString distribution_;
1488 NSString *authority_;
1490 CYString defaultIcon_;
1492 NSDictionary *record_;
1496 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1498 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1500 - (NSString *) depictionForPackage:(NSString *)package;
1501 - (NSString *) supportForPackage:(NSString *)package;
1503 - (NSDictionary *) record;
1507 - (NSString *) distribution;
1508 - (NSString *) type;
1510 - (NSString *) host;
1512 - (NSString *) name;
1513 - (NSString *) description;
1514 - (NSString *) label;
1515 - (NSString *) origin;
1516 - (NSString *) version;
1518 - (NSString *) defaultIcon;
1522 @implementation Source
1526 distribution_.clear();
1529 description_.clear();
1535 defaultIcon_.clear();
1537 if (record_ != nil) {
1547 if (authority_ != nil) {
1548 [authority_ release];
1558 + (NSArray *) _attributeKeys {
1559 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1562 - (NSArray *) attributeKeys {
1563 return [[self class] _attributeKeys];
1566 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1567 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1570 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1573 trusted_ = index->IsTrusted();
1575 uri_.set(pool, index->GetURI());
1576 distribution_.set(pool, index->GetDist());
1577 type_.set(pool, index->GetType());
1579 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1580 if (dindex != NULL) {
1582 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1585 pkgTagFile tags(&fd);
1587 pkgTagSection section;
1594 {"default-icon", &defaultIcon_},
1595 {"depiction", &depiction_},
1596 {"description", &description_},
1598 {"origin", &origin_},
1599 {"support", &support_},
1600 {"version", &version_},
1603 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1604 const char *start, *end;
1606 if (section.Find(names[i].name_, start, end)) {
1607 CYString &value(*names[i].value_);
1608 value.set(pool, start, end - start);
1614 record_ = [Sources_ objectForKey:[self key]];
1616 record_ = [record_ retain];
1618 NSURL *url([NSURL URLWithString:uri_]);
1622 host_ = [[host_ lowercaseString] retain];
1627 authority_ = [url path];
1629 if (authority_ != nil)
1630 authority_ = [authority_ retain];
1633 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1634 if ((self = [super init]) != nil) {
1635 [self setMetaIndex:index inPool:pool];
1639 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1640 NSDictionary *lhr = [self record];
1641 NSDictionary *rhr = [source record];
1644 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1646 NSString *lhs = [self name];
1647 NSString *rhs = [source name];
1649 if ([lhs length] != 0 && [rhs length] != 0) {
1650 unichar lhc = [lhs characterAtIndex:0];
1651 unichar rhc = [rhs characterAtIndex:0];
1653 if (isalpha(lhc) && !isalpha(rhc))
1654 return NSOrderedAscending;
1655 else if (!isalpha(lhc) && isalpha(rhc))
1656 return NSOrderedDescending;
1659 return [lhs compare:rhs options:LaxCompareOptions_];
1662 - (NSString *) depictionForPackage:(NSString *)package {
1663 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1666 - (NSString *) supportForPackage:(NSString *)package {
1667 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1670 - (NSDictionary *) record {
1678 - (NSString *) uri {
1682 - (NSString *) distribution {
1683 return distribution_;
1686 - (NSString *) type {
1690 - (NSString *) key {
1691 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1694 - (NSString *) host {
1698 - (NSString *) name {
1699 return origin_.empty() ? authority_ : origin_;
1702 - (NSString *) description {
1703 return description_;
1706 - (NSString *) label {
1707 return label_.empty() ? authority_ : label_;
1710 - (NSString *) origin {
1714 - (NSString *) version {
1718 - (NSString *) defaultIcon {
1719 return defaultIcon_;
1724 /* Relationship Class {{{ */
1725 @interface Relationship : NSObject {
1730 - (NSString *) type;
1732 - (NSString *) name;
1736 @implementation Relationship
1744 - (NSString *) type {
1752 - (NSString *) name {
1759 /* Package Class {{{ */
1760 @interface Package : NSObject {
1764 pkgCache::VerIterator version_;
1765 pkgCache::PkgIterator iterator_;
1766 _transient Database *database_;
1767 pkgCache::VerFileIterator file_;
1774 NSString *section$_;
1780 CYString installed_;
1786 CYString depiction_;
1797 NSMutableArray *tags_;
1800 NSArray *relationships_;
1802 NSMutableDictionary *metadata_;
1803 _transient NSDate *firstSeen_;
1804 _transient NSDate *lastSeen_;
1808 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1809 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1811 - (pkgCache::PkgIterator) iterator;
1814 - (NSString *) section;
1815 - (NSString *) simpleSection;
1817 - (NSString *) longSection;
1818 - (NSString *) shortSection;
1822 - (Address *) maintainer;
1824 - (NSString *) longDescription;
1825 - (NSString *) shortDescription;
1828 - (NSMutableDictionary *) metadata;
1830 - (BOOL) subscribed;
1833 - (NSString *) latest;
1834 - (NSString *) installed;
1835 - (BOOL) uninstalled;
1838 - (BOOL) upgradableAndEssential:(BOOL)essential;
1841 - (BOOL) unfiltered;
1845 - (BOOL) halfConfigured;
1846 - (BOOL) halfInstalled;
1848 - (NSString *) mode;
1850 - (void) setVisible;
1853 - (NSString *) name;
1855 - (NSString *) homepage;
1856 - (NSString *) depiction;
1857 - (Address *) author;
1859 - (NSString *) support;
1861 - (NSArray *) files;
1862 - (NSArray *) relationships;
1863 - (NSArray *) warnings;
1864 - (NSArray *) applications;
1866 - (Source *) source;
1867 - (NSString *) role;
1869 - (BOOL) matches:(NSString *)text;
1871 - (bool) hasSupportingRole;
1872 - (BOOL) hasTag:(NSString *)tag;
1873 - (NSString *) primaryPurpose;
1874 - (NSArray *) purposes;
1875 - (bool) isCommercial;
1877 - (CYString &) cyname;
1879 - (uint32_t) compareBySection:(NSArray *)sections;
1881 - (uint32_t) compareForChanges;
1886 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1887 - (bool) isInstalledAndVisible:(NSNumber *)number;
1888 - (bool) isVisibleInSection:(NSString *)section;
1889 - (bool) isVisibleInSource:(Source *)source;
1893 uint32_t PackageChangesRadix(Package *self, void *) {
1898 uint32_t timestamp : 30;
1899 uint32_t ignored : 1;
1900 uint32_t upgradable : 1;
1904 bool upgradable([self upgradableAndEssential:YES]);
1905 value.bits.upgradable = upgradable ? 1 : 0;
1908 value.bits.timestamp = 0;
1909 value.bits.ignored = [self ignored] ? 0 : 1;
1910 value.bits.upgradable = 1;
1912 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1913 value.bits.ignored = 0;
1914 value.bits.upgradable = 0;
1917 return _not(uint32_t) - value.key;
1920 _finline static void Stifle(uint8_t &value) {
1923 uint32_t PackagePrefixRadix(Package *self, void *context) {
1924 size_t offset(reinterpret_cast<size_t>(context));
1925 CYString &name([self cyname]);
1927 size_t size(name.size());
1930 char *text(name.data());
1933 if (!isdigit(text[0]))
1937 while (size != digits && isdigit(text[digits]))
1947 if (offset == 0 && zeros != 0) {
1948 memset(data, '0', zeros);
1949 memcpy(data + zeros, text, 4 - zeros);
1951 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1952 if (size <= offset - zeros)
1955 text += offset - zeros;
1956 size -= offset - zeros;
1959 memcpy(data, text, 4);
1961 memcpy(data, text, size);
1962 memset(data + size, 0, 4 - size);
1965 for (size_t i(0); i != 4; ++i)
1966 if (isalpha(data[i]))
1971 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1973 /* XXX: ntohl may be more honest */
1974 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1977 CYString &(*PackageName)(Package *self, SEL sel);
1979 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1980 _profile(PackageNameCompare)
1981 CYString &lhi(PackageName(lhs, @selector(cyname)));
1982 CYString &rhi(PackageName(rhs, @selector(cyname)));
1983 CFStringRef lhn(lhi), rhn(rhi);
1985 _profile(PackageNameCompare$NumbersLast)
1986 if (!lhi.empty() && !rhi.empty()) {
1987 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1988 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1989 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1990 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1991 return lha ? NSOrderedAscending : NSOrderedDescending;
1995 CFIndex length = CFStringGetLength(lhn);
1997 _profile(PackageNameCompare$Compare)
1998 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2003 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2004 return PackageNameCompare(*lhs, *rhs, context);
2007 struct PackageNameOrdering :
2008 std::binary_function<Package *, Package *, bool>
2010 _finline bool operator ()(Package *lhs, Package *rhs) const {
2011 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2015 @implementation Package
2017 - (NSString *) description {
2018 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2024 if (section$_ != nil)
2025 [section$_ release];
2030 if (sponsor$_ != nil)
2031 [sponsor$_ release];
2032 if (author$_ != nil)
2039 if (relationships_ != nil)
2040 [relationships_ release];
2041 if (metadata_ != nil)
2042 [metadata_ release];
2047 + (NSString *) webScriptNameForSelector:(SEL)selector {
2048 if (selector == @selector(hasTag:))
2054 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2055 return [self webScriptNameForSelector:selector] == nil;
2058 + (NSArray *) _attributeKeys {
2059 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];
2062 - (NSArray *) attributeKeys {
2063 return [[self class] _attributeKeys];
2066 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2067 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2077 _profile(Package$parse)
2078 pkgRecords::Parser *parser;
2080 _profile(Package$parse$Lookup)
2081 parser = &[database_ records]->Lookup(file_);
2086 _profile(Package$parse$Find)
2092 {"depiction", &depiction_},
2093 {"homepage", &homepage_},
2094 {"website", &website},
2096 {"support", &support_},
2097 {"sponsor", &sponsor_},
2098 {"author", &author_},
2101 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2102 const char *start, *end;
2104 if (parser->Find(names[i].name_, start, end)) {
2105 CYString &value(*names[i].value_);
2106 _profile(Package$parse$Value)
2107 value.set(pool_, start, end - start);
2113 _profile(Package$parse$Tagline)
2114 const char *start, *end;
2115 if (parser->ShortDesc(start, end)) {
2116 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2119 while (stop != start && stop[-1] == '\r')
2121 tagline_.set(pool_, start, stop - start);
2125 _profile(Package$parse$Retain)
2126 if (homepage_.empty())
2127 homepage_ = website;
2128 if (homepage_ == depiction_)
2134 - (void) setVisible {
2135 visible_ = required_ && [self hasSupportingRole] && [self unfiltered];
2138 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2139 if ((self = [super init]) != nil) {
2140 _profile(Package$initWithVersion)
2141 @synchronized (database) {
2142 era_ = [database era];
2146 iterator_ = version.ParentPkg();
2147 database_ = database;
2149 _profile(Package$initWithVersion$Latest)
2150 latest_ = (NSString *) StripVersion(version_.VerStr());
2153 pkgCache::VerIterator current;
2154 _profile(Package$initWithVersion$Versions)
2155 current = iterator_.CurrentVer();
2157 installed_.set(pool_, StripVersion_(current.VerStr()));
2159 if (!version_.end())
2160 file_ = version_.FileList();
2162 pkgCache &cache([database_ cache]);
2163 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2167 _profile(Package$initWithVersion$Name)
2168 id_.set(pool_, iterator_.Name());
2169 name_.set(pool, iterator_.Display());
2173 _profile(Package$initWithVersion$Source)
2174 source_ = [database_ getSource:file_.File()];
2183 _profile(Package$initWithVersion$Tags)
2184 pkgCache::TagIterator tag(iterator_.TagList());
2186 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2188 const char *name(tag.Name());
2189 [tags_ addObject:(NSString *)CFCString(name)];
2190 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2191 role_ = (NSString *) CFCString(name + 6);
2192 if (required_ && strncmp(name, "require::", 9) == 0 && (
2197 } while (!tag.end());
2201 bool changed(false);
2202 NSString *key([id_ lowercaseString]);
2204 _profile(Package$initWithVersion$Metadata)
2205 metadata_ = [Packages_ objectForKey:key];
2207 if (metadata_ == nil) {
2210 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2211 firstSeen_, @"FirstSeen",
2212 latest_, @"LastVersion",
2217 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2218 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2220 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2221 subscribed_ = [subscribed boolValue];
2223 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2225 if (firstSeen_ == nil) {
2226 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2227 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2231 if (version == nil) {
2232 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2235 if (![version isEqualToString:latest_]) {
2236 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2238 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2243 metadata_ = [metadata_ retain];
2246 [Packages_ setObject:metadata_ forKey:key];
2251 _profile(Package$initWithVersion$Section)
2252 section_.set(pool_, iterator_.Section());
2255 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2257 } _end } return self;
2260 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2261 @synchronized ([Database class]) {
2262 pkgCache::VerIterator version;
2264 _profile(Package$packageWithIterator$GetCandidateVer)
2265 version = [database policy]->GetCandidateVer(iterator);
2271 return [[[Package alloc]
2272 initWithVersion:version
2279 - (pkgCache::PkgIterator) iterator {
2283 - (NSString *) section {
2284 if (section$_ == nil) {
2285 if (section_.empty())
2288 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2289 NSString *name(section_);
2292 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2293 if (NSString *rename = [value objectForKey:@"Rename"]) {
2298 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2302 - (NSString *) simpleSection {
2303 if (NSString *section = [self section])
2304 return Simplify(section);
2309 - (NSString *) longSection {
2310 return LocalizeSection([self section]);
2313 - (NSString *) shortSection {
2314 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2317 - (NSString *) uri {
2320 pkgIndexFile *index;
2321 pkgCache::PkgFileIterator file(file_.File());
2322 if (![database_ list].FindIndex(file, index))
2324 return [NSString stringWithUTF8String:iterator_->Path];
2325 //return [NSString stringWithUTF8String:file.Site()];
2326 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2330 - (Address *) maintainer {
2333 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2334 const std::string &maintainer(parser->Maintainer());
2335 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2339 return version_.end() ? 0 : version_->InstalledSize;
2342 - (NSString *) longDescription {
2345 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2346 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2348 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2349 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2350 if ([lines count] < 2)
2353 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2354 for (size_t i(1), e([lines count]); i != e; ++i) {
2355 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2356 [trimmed addObject:trim];
2359 return [trimmed componentsJoinedByString:@"\n"];
2362 - (NSString *) shortDescription {
2367 _profile(Package$index)
2368 CFStringRef name((CFStringRef) [self name]);
2369 if (CFStringGetLength(name) == 0)
2371 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2372 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2374 return toupper(character);
2378 - (NSMutableDictionary *) metadata {
2383 if (subscribed_ && lastSeen_ != nil)
2388 - (BOOL) subscribed {
2393 NSDictionary *metadata([self metadata]);
2394 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2395 return [ignored boolValue];
2400 - (NSString *) latest {
2404 - (NSString *) installed {
2408 - (BOOL) uninstalled {
2409 return installed_.empty();
2413 return !version_.end();
2416 - (BOOL) upgradableAndEssential:(BOOL)essential {
2417 _profile(Package$upgradableAndEssential)
2418 pkgCache::VerIterator current(iterator_.CurrentVer());
2420 return essential && essential_ && visible_;
2422 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2426 - (BOOL) essential {
2431 return [database_ cache][iterator_].InstBroken();
2434 - (BOOL) unfiltered {
2435 NSString *section([self section]);
2436 return section == nil || isSectionVisible(section);
2444 unsigned char current(iterator_->CurrentState);
2445 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2448 - (BOOL) halfConfigured {
2449 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2452 - (BOOL) halfInstalled {
2453 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2457 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2458 return state.Mode != pkgDepCache::ModeKeep;
2461 - (NSString *) mode {
2462 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2464 switch (state.Mode) {
2465 case pkgDepCache::ModeDelete:
2466 if ((state.iFlags & pkgDepCache::Purge) != 0)
2470 case pkgDepCache::ModeKeep:
2471 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2472 return @"REINSTALL";
2473 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2477 case pkgDepCache::ModeInstall:
2478 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2479 return @"REINSTALL";
2480 else*/ switch (state.Status) {
2482 return @"DOWNGRADE";
2488 return @"NEW_INSTALL";
2499 - (NSString *) name {
2500 return name_.empty() ? id_ : name_;
2503 - (UIImage *) icon {
2504 NSString *section = [self simpleSection];
2508 if ([icon_ hasPrefix:@"file:///"])
2509 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2510 if (icon == nil) if (section != nil)
2511 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2512 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2513 if ([dicon hasPrefix:@"file:///"])
2514 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2516 icon = [UIImage applicationImageNamed:@"unknown.png"];
2520 - (NSString *) homepage {
2524 - (NSString *) depiction {
2525 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2528 - (Address *) sponsor {
2529 if (sponsor$_ == nil) {
2530 if (sponsor_.empty())
2532 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2536 - (Address *) author {
2537 if (author$_ == nil) {
2538 if (author_.empty())
2540 author$_ = [[Address addressWithString:author_] retain];
2544 - (NSString *) support {
2545 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2548 - (NSArray *) files {
2549 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2550 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2553 fin.open([path UTF8String]);
2558 while (std::getline(fin, line))
2559 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2564 - (NSArray *) relationships {
2565 return relationships_;
2568 - (NSArray *) warnings {
2569 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2570 const char *name(iterator_.Name());
2572 size_t length(strlen(name));
2573 if (length < 2) invalid:
2574 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2575 else for (size_t i(0); i != length; ++i)
2577 /* XXX: technically this is not allowed */
2578 (name[i] < 'A' || name[i] > 'Z') &&
2579 (name[i] < 'a' || name[i] > 'z') &&
2580 (name[i] < '0' || name[i] > '9') &&
2581 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2584 if (strcmp(name, "cydia") != 0) {
2587 bool _private = false;
2590 bool repository = [[self section] isEqualToString:@"Repositories"];
2592 if (NSArray *files = [self files])
2593 for (NSString *file in files)
2594 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2596 else if (!user && [file isEqualToString:@"/User"])
2598 else if (!_private && [file isEqualToString:@"/private"])
2600 else if (!stash && [file isEqualToString:@"/var/stash"])
2603 /* XXX: this is not sensitive enough. only some folders are valid. */
2604 if (cydia && !repository)
2605 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2607 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2609 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2611 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2614 return [warnings count] == 0 ? nil : warnings;
2617 - (NSArray *) applications {
2618 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2620 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2622 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2623 if (NSArray *files = [self files])
2624 for (NSString *file in files)
2625 if (application_r(file)) {
2626 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2627 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2628 if ([id isEqualToString:me])
2631 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2633 display = application_r[1];
2635 NSString *bundle([file stringByDeletingLastPathComponent]);
2636 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2637 if (icon == nil || [icon length] == 0)
2639 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2641 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2642 [applications addObject:application];
2644 [application addObject:id];
2645 [application addObject:display];
2646 [application addObject:url];
2649 return [applications count] == 0 ? nil : applications;
2652 - (Source *) source {
2654 @synchronized (database_) {
2655 if ([database_ era] != era_ || file_.end())
2658 source_ = [database_ getSource:file_.File()];
2670 - (NSString *) role {
2674 - (BOOL) matches:(NSString *)text {
2680 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2681 if (range.location != NSNotFound)
2684 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2685 if (range.location != NSNotFound)
2688 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2689 if (range.location != NSNotFound)
2695 - (bool) hasSupportingRole {
2698 if ([role_ isEqualToString:@"enduser"])
2700 if ([Role_ isEqualToString:@"User"])
2702 if ([role_ isEqualToString:@"hacker"])
2704 if ([Role_ isEqualToString:@"Hacker"])
2706 if ([role_ isEqualToString:@"developer"])
2708 if ([Role_ isEqualToString:@"Developer"])
2713 - (BOOL) hasTag:(NSString *)tag {
2714 return tags_ == nil ? NO : [tags_ containsObject:tag];
2717 - (NSString *) primaryPurpose {
2718 for (NSString *tag in tags_)
2719 if ([tag hasPrefix:@"purpose::"])
2720 return [tag substringFromIndex:9];
2724 - (NSArray *) purposes {
2725 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2726 for (NSString *tag in tags_)
2727 if ([tag hasPrefix:@"purpose::"])
2728 [purposes addObject:[tag substringFromIndex:9]];
2729 return [purposes count] == 0 ? nil : purposes;
2732 - (bool) isCommercial {
2733 return [self hasTag:@"cydia::commercial"];
2736 - (CYString &) cyname {
2737 return name_.empty() ? id_ : name_;
2740 - (uint32_t) compareBySection:(NSArray *)sections {
2741 NSString *section([self section]);
2742 for (size_t i(0), e([sections count]); i != e; ++i) {
2743 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2747 return _not(uint32_t);
2750 - (uint32_t) compareForChanges {
2755 uint32_t timestamp : 30;
2756 uint32_t ignored : 1;
2757 uint32_t upgradable : 1;
2761 bool upgradable([self upgradableAndEssential:YES]);
2762 value.bits.upgradable = upgradable ? 1 : 0;
2765 value.bits.timestamp = 0;
2766 value.bits.ignored = [self ignored] ? 0 : 1;
2767 value.bits.upgradable = 1;
2769 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2770 value.bits.ignored = 0;
2771 value.bits.upgradable = 0;
2774 return _not(uint32_t) - value.key;
2778 pkgProblemResolver *resolver = [database_ resolver];
2779 resolver->Clear(iterator_);
2780 resolver->Protect(iterator_);
2784 pkgProblemResolver *resolver = [database_ resolver];
2785 resolver->Clear(iterator_);
2786 resolver->Protect(iterator_);
2787 pkgCacheFile &cache([database_ cache]);
2788 cache->MarkInstall(iterator_, false);
2789 pkgDepCache::StateCache &state((*cache)[iterator_]);
2790 if (!state.Install())
2791 cache->SetReInstall(iterator_, true);
2795 pkgProblemResolver *resolver = [database_ resolver];
2796 resolver->Clear(iterator_);
2797 resolver->Protect(iterator_);
2798 resolver->Remove(iterator_);
2799 [database_ cache]->MarkDelete(iterator_, true);
2802 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2803 _profile(Package$isUnfilteredAndSearchedForBy)
2806 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2807 value &= [self unfiltered];
2810 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2811 value &= [self matches:search];
2818 - (bool) isInstalledAndVisible:(NSNumber *)number {
2819 return (![number boolValue] || [self visible]) && ![self uninstalled];
2822 - (bool) isVisibleInSection:(NSString *)name {
2823 NSString *section = [self section];
2828 section == nil && [name length] == 0 ||
2829 [name isEqualToString:section]
2833 - (bool) isVisibleInSource:(Source *)source {
2834 return [self source] == source && [self visible];
2839 /* Section Class {{{ */
2840 @interface Section : NSObject {
2845 NSString *localized_;
2848 - (NSComparisonResult) compareByLocalized:(Section *)section;
2849 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2850 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2851 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2852 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2853 - (NSString *) name;
2860 - (void) addToCount;
2862 - (void) setCount:(size_t)count;
2863 - (NSString *) localized;
2867 @implementation Section
2871 if (localized_ != nil)
2872 [localized_ release];
2876 - (NSComparisonResult) compareByLocalized:(Section *)section {
2877 NSString *lhs(localized_);
2878 NSString *rhs([section localized]);
2880 /*if ([lhs length] != 0 && [rhs length] != 0) {
2881 unichar lhc = [lhs characterAtIndex:0];
2882 unichar rhc = [rhs characterAtIndex:0];
2884 if (isalpha(lhc) && !isalpha(rhc))
2885 return NSOrderedAscending;
2886 else if (!isalpha(lhc) && isalpha(rhc))
2887 return NSOrderedDescending;
2890 return [lhs compare:rhs options:LaxCompareOptions_];
2893 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2894 if ((self = [self initWithName:name localize:NO]) != nil) {
2895 if (localized != nil)
2896 localized_ = [localized retain];
2900 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2901 return [self initWithName:name row:0 localize:localize];
2904 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2905 if ((self = [super init]) != nil) {
2906 name_ = [name retain];
2910 localized_ = [LocalizeSection(name_) retain];
2914 /* XXX: localize the index thingees */
2915 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2916 if ((self = [super init]) != nil) {
2917 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2923 - (NSString *) name {
2943 - (void) addToCount {
2947 - (void) setCount:(size_t)count {
2951 - (NSString *) localized {
2958 static NSString *Colon_;
2959 static NSString *Error_;
2960 static NSString *Warning_;
2962 /* Database Implementation {{{ */
2963 @implementation Database
2965 + (Database *) sharedInstance {
2966 static Database *instance;
2967 if (instance == nil)
2968 instance = [[Database alloc] init];
2978 NSRecycleZone(zone_);
2979 // XXX: malloc_destroy_zone(zone_);
2980 apr_pool_destroy(pool_);
2984 - (void) _readCydia:(NSNumber *)fd { _pooled
2985 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2986 std::istream is(&ib);
2989 static Pcre finish_r("^finish:([^:]*)$");
2991 while (std::getline(is, line)) {
2992 const char *data(line.c_str());
2993 size_t size = line.size();
2994 lprintf("C:%s\n", data);
2996 if (finish_r(data, size)) {
2997 NSString *finish = finish_r[1];
2998 int index = [Finishes_ indexOfObject:finish];
2999 if (index != INT_MAX && index > Finish_)
3007 - (void) _readStatus:(NSNumber *)fd { _pooled
3008 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3009 std::istream is(&ib);
3012 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3013 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3015 while (std::getline(is, line)) {
3016 const char *data(line.c_str());
3017 size_t size(line.size());
3018 lprintf("S:%s\n", data);
3020 if (conffile_r(data, size)) {
3021 [delegate_ setConfigurationData:conffile_r[1]];
3022 } else if (strncmp(data, "status: ", 8) == 0) {
3023 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3024 [delegate_ setProgressTitle:string];
3025 } else if (pmstatus_r(data, size)) {
3026 std::string type([pmstatus_r[1] UTF8String]);
3027 NSString *id = pmstatus_r[2];
3029 float percent([pmstatus_r[3] floatValue]);
3030 [delegate_ setProgressPercent:(percent / 100)];
3032 NSString *string = pmstatus_r[4];
3034 if (type == "pmerror")
3035 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3036 withObject:[NSArray arrayWithObjects:string, id, nil]
3039 else if (type == "pmstatus") {
3040 [delegate_ setProgressTitle:string];
3041 } else if (type == "pmconffile")
3042 [delegate_ setConfigurationData:string];
3044 lprintf("E:unknown pmstatus\n");
3046 lprintf("E:unknown status\n");
3052 - (void) _readOutput:(NSNumber *)fd { _pooled
3053 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3054 std::istream is(&ib);
3057 while (std::getline(is, line)) {
3058 lprintf("O:%s\n", line.c_str());
3059 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3069 - (Package *) packageWithName:(NSString *)name {
3070 @synchronized ([Database class]) {
3071 if (static_cast<pkgDepCache *>(cache_) == NULL)
3073 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3074 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3077 - (Database *) init {
3078 if ((self = [super init]) != nil) {
3085 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3086 apr_pool_create(&pool_, NULL);
3088 packages_ = [[NSMutableArray alloc] init];
3092 _assert(pipe(fds) != -1);
3095 _config->Set("APT::Keep-Fds::", cydiafd_);
3096 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3099 detachNewThreadSelector:@selector(_readCydia:)
3101 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3104 _assert(pipe(fds) != -1);
3108 detachNewThreadSelector:@selector(_readStatus:)
3110 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3113 _assert(pipe(fds) != -1);
3114 _assert(dup2(fds[0], 0) != -1);
3115 _assert(close(fds[0]) != -1);
3117 input_ = fdopen(fds[1], "a");
3119 _assert(pipe(fds) != -1);
3120 _assert(dup2(fds[1], 1) != -1);
3121 _assert(close(fds[1]) != -1);
3124 detachNewThreadSelector:@selector(_readOutput:)
3126 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3131 - (pkgCacheFile &) cache {
3135 - (pkgDepCache::Policy *) policy {
3139 - (pkgRecords *) records {
3143 - (pkgProblemResolver *) resolver {
3147 - (pkgAcquire &) fetcher {
3151 - (pkgSourceList &) list {
3155 - (NSArray *) packages {
3159 - (NSArray *) sources {
3160 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3161 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3162 [sources addObject:i->second];
3166 - (NSArray *) issues {
3167 if (cache_->BrokenCount() == 0)
3170 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3172 for (Package *package in packages_) {
3173 if (![package broken])
3175 pkgCache::PkgIterator pkg([package iterator]);
3177 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3178 [entry addObject:[package name]];
3179 [issues addObject:entry];
3181 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3185 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3186 pkgCache::DepIterator start;
3187 pkgCache::DepIterator end;
3188 dep.GlobOr(start, end); // ++dep
3190 if (!cache_->IsImportantDep(end))
3192 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3195 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3196 [entry addObject:failure];
3197 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3199 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3200 if (Package *package = [self packageWithName:name])
3201 name = [package name];
3202 [failure addObject:name];
3204 pkgCache::PkgIterator target(start.TargetPkg());
3205 if (target->ProvidesList != 0)
3206 [failure addObject:@"?"];
3208 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3210 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3211 else if (!cache_[target].CandidateVerIter(cache_).end())
3212 [failure addObject:@"-"];
3213 else if (target->ProvidesList == 0)
3214 [failure addObject:@"!"];
3216 [failure addObject:@"%"];
3220 if (start.TargetVer() != 0)
3221 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3232 - (bool) popErrorWithTitle:(NSString *)title {
3234 std::string message;
3236 while (!_error->empty()) {
3238 bool warning(!_error->PopMessage(error));
3242 size_t size(error.size());
3243 if (size == 0 || error[size - 1] != '\n')
3245 error.resize(size - 1);
3247 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3249 if (!message.empty())
3254 if (fatal && !message.empty())
3255 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3260 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3261 return [self popErrorWithTitle:title] || !success;
3264 - (void) reloadData { _pooled
3265 @synchronized ([Database class]) {
3266 @synchronized (self) {
3270 [packages_ removeAllObjects];
3296 apr_pool_clear(pool_);
3297 NSRecycleZone(zone_);
3299 int chk(creat("/tmp/cydia.chk", 0644));
3303 NSString *title(UCLocalize("DATABASE"));
3306 if (!cache_.Open(progress_, true)) { pop:
3308 bool warning(!_error->PopMessage(error));
3309 lprintf("cache_.Open():[%s]\n", error.c_str());
3311 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3312 [delegate_ repairWithSelector:@selector(configure)];
3313 else if (error == "The package lists or status file could not be parsed or opened.")
3314 [delegate_ repairWithSelector:@selector(update)];
3315 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3316 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3317 // else if (error == "The list of sources could not be read.")
3319 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3328 unlink("/tmp/cydia.chk");
3330 now_ = [[NSDate date] retain];
3332 policy_ = new pkgDepCache::Policy();
3333 records_ = new pkgRecords(cache_);
3334 resolver_ = new pkgProblemResolver(cache_);
3335 fetcher_ = new pkgAcquire(&status_);
3338 list_ = new pkgSourceList();
3339 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3342 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3343 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3347 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3350 if (cache_->BrokenCount() != 0) {
3351 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3354 if (cache_->BrokenCount() != 0) {
3355 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3359 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3365 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3366 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3367 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3368 // XXX: this could be more intelligent
3369 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3370 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3372 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3379 /*std::vector<Package *> packages;
3380 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3381 [packages_ release];
3386 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3387 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3388 //packages.push_back(package);
3389 [packages_ addObject:package];
3393 /*if (packages.empty())
3394 packages_ = [[NSArray alloc] init];
3396 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3399 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3400 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3401 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3409 /*if (!packages.empty())
3410 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3411 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3413 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3415 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3417 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3423 - (void) configure {
3424 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3425 system([dpkg UTF8String]);
3429 // XXX: I don't remember this condition
3434 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3436 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3438 if ([self popErrorWithTitle:title])
3442 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3445 public pkgArchiveCleaner
3448 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3453 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3460 fetcher_->Shutdown();
3462 pkgRecords records(cache_);
3464 lock_ = new FileFd();
3465 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3467 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3469 if ([self popErrorWithTitle:title])
3473 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3476 manager_ = (_system->CreatePM(cache_));
3477 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3484 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3486 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3488 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3490 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3491 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3494 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3499 bool failed = false;
3500 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3501 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3503 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3506 std::string uri = (*item)->DescURI();
3507 std::string error = (*item)->ErrorText;
3509 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3512 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3513 withObject:[NSArray arrayWithObjects:
3514 [NSString stringWithUTF8String:error.c_str()],
3526 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3528 if (_error->PendingError()) {
3533 if (result == pkgPackageManager::Failed) {
3538 if (result != pkgPackageManager::Completed) {
3543 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3545 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3547 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3548 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3551 if (![before isEqualToArray:after])
3556 NSString *title(UCLocalize("UPGRADE"));
3557 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3563 [self updateWithStatus:status_];
3566 - (void) setVisible {
3567 for (Package *package in packages_)
3568 [package setVisible];
3571 - (void) updateWithStatus:(Status &)status {
3572 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3573 NSString *title(UCLocalize("REFRESHING_DATA"));
3576 if (!list.ReadMainList())
3577 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3580 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3581 if ([self popErrorWithTitle:title])
3584 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3585 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */;
3587 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3591 - (void) setDelegate:(id)delegate {
3592 delegate_ = delegate;
3593 status_.setDelegate(delegate);
3594 progress_.setDelegate(delegate);
3597 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3598 SourceMap::const_iterator i(sources_.find(file->ID));
3599 return i == sources_.end() ? nil : i->second;
3605 /* Confirmation View {{{ */
3606 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3607 if (!iterator.end())
3608 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3609 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3611 pkgCache::PkgIterator package(dep.TargetPkg());
3614 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3621 /* Web Scripting {{{ */
3622 @interface CydiaObject : NSObject {
3626 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3629 @implementation CydiaObject
3632 [indirect_ release];
3636 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3637 if ((self = [super init]) != nil) {
3638 indirect_ = [indirect retain];
3642 + (NSArray *) _attributeKeys {
3643 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3646 - (NSArray *) attributeKeys {
3647 return [[self class] _attributeKeys];
3650 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3651 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3654 - (NSString *) device {
3655 return [[UIDevice currentDevice] uniqueIdentifier];
3658 #if 0 // XXX: implement!
3659 - (NSString *) mac {
3660 if (![indirect_ promptForSensitive:@"Mac Address"])
3664 - (NSString *) serial {
3665 if (![indirect_ promptForSensitive:@"Serial #"])
3669 - (NSString *) firewire {
3670 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3674 - (NSString *) imei {
3675 if (![indirect_ promptForSensitive:@"IMEI"])
3680 + (NSString *) webScriptNameForSelector:(SEL)selector {
3681 if (selector == @selector(close))
3683 else if (selector == @selector(getPackageById:))
3684 return @"getPackageById";
3685 else if (selector == @selector(setAutoPopup:))
3686 return @"setAutoPopup";
3687 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3688 return @"setButtonImage";
3689 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3690 return @"setButtonTitle";
3691 else if (selector == @selector(setFinishHook:))
3692 return @"setFinishHook";
3693 else if (selector == @selector(setPopupHook:))
3694 return @"setPopupHook";
3695 else if (selector == @selector(setSpecial:))
3696 return @"setSpecial";
3697 else if (selector == @selector(setViewportWidth:))
3698 return @"setViewportWidth";
3699 else if (selector == @selector(supports:))
3701 else if (selector == @selector(stringWithFormat:arguments:))
3703 else if (selector == @selector(localizedStringForKey:value:table:))
3705 else if (selector == @selector(du:))
3707 else if (selector == @selector(statfs:))
3713 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3714 return [self webScriptNameForSelector:selector] == nil;
3717 - (BOOL) supports:(NSString *)feature {
3718 return [feature isEqualToString:@"window.open"];
3721 - (Package *) getPackageById:(NSString *)id {
3722 Package *package([[Database sharedInstance] packageWithName:id]);
3727 - (NSArray *) statfs:(NSString *)path {
3730 if (path == nil || statfs([path UTF8String], &stat) == -1)
3733 return [NSArray arrayWithObjects:
3734 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3735 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3736 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3740 - (NSNumber *) du:(NSString *)path {
3741 NSNumber *value(nil);
3744 _assert(pipe(fds) != -1);
3746 pid_t pid(ExecFork());
3748 _assert(dup2(fds[1], 1) != -1);
3749 _assert(close(fds[0]) != -1);
3750 _assert(close(fds[1]) != -1);
3751 /* XXX: this should probably not use du */
3752 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3757 _assert(close(fds[1]) != -1);
3759 if (FILE *du = fdopen(fds[0], "r")) {
3761 while (fgets(line, sizeof(line), du) != NULL) {
3762 size_t length(strlen(line));
3763 while (length != 0 && line[length - 1] == '\n')
3764 line[--length] = '\0';
3765 if (char *tab = strchr(line, '\t')) {
3767 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3772 } else _assert(close(fds[0]));
3776 if (waitpid(pid, &status, 0) == -1)
3779 else _assert(false);
3788 - (void) setAutoPopup:(BOOL)popup {
3789 [indirect_ setAutoPopup:popup];
3792 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3793 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3796 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3797 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3800 - (void) setSpecial:(id)function {
3801 [indirect_ setSpecial:function];
3804 - (void) setFinishHook:(id)function {
3805 [indirect_ setFinishHook:function];
3808 - (void) setPopupHook:(id)function {
3809 [indirect_ setPopupHook:function];
3812 - (void) setViewportWidth:(float)width {
3813 [indirect_ setViewportWidth:width];
3816 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3817 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3818 unsigned count([arguments count]);
3820 for (unsigned i(0); i != count; ++i)
3821 values[i] = [arguments objectAtIndex:i];
3822 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3825 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3826 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3828 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3830 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3836 @interface CydiaBrowserView : BrowserView {
3837 CydiaObject *cydia_;
3842 @implementation CydiaBrowserView
3849 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3850 [super webView:sender didClearWindowObject:window forFrame:frame];
3851 [window setValue:cydia_ forKey:@"cydia"];
3854 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3855 if (System_ != NULL)
3856 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3857 if (Machine_ != NULL)
3858 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3859 if (UniqueID_ != nil)
3860 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
3862 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3865 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3866 NSMutableURLRequest *copy = [request mutableCopy];
3867 [self _setMoreHeaders:copy];
3871 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
3872 if ((self = [super initWithBook:book forWidth:width ofClass:[CydiaBrowserView class]]) != nil) {
3873 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3875 WebView *webview([webview_ webView]);
3877 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3879 NSString *application = package == nil ? @"Cydia" : [NSString
3880 stringWithFormat:@"Cydia/%@",
3885 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3887 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3888 if (Product_ != nil)
3889 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3891 [webview setApplicationNameForUserAgent:application];
3897 @protocol ConfirmationViewDelegate
3903 @interface ConfirmationView : CydiaBrowserView {
3904 _transient Database *database_;
3905 UIActionSheet *essential_;
3912 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3916 @implementation ConfirmationView
3923 if (essential_ != nil)
3924 [essential_ release];
3930 [book_ popFromSuperviewAnimated:YES];
3933 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3934 NSString *context([sheet context]);
3936 if ([context isEqualToString:@"remove"]) {
3944 [delegate_ confirm];
3950 } else if ([context isEqualToString:@"unable"]) {
3954 [super alertSheet:sheet buttonClicked:button];
3957 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3958 [super webView:sender didClearWindowObject:window forFrame:frame];
3959 [window setValue:changes_ forKey:@"changes"];
3960 [window setValue:issues_ forKey:@"issues"];
3961 [window setValue:sizes_ forKey:@"sizes"];
3964 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3965 if ((self = [super initWithBook:book]) != nil) {
3966 database_ = database;
3968 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3969 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3970 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3971 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3972 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3976 pkgDepCache::Policy *policy([database_ policy]);
3978 pkgCacheFile &cache([database_ cache]);
3979 NSArray *packages = [database_ packages];
3980 for (Package *package in packages) {
3981 pkgCache::PkgIterator iterator = [package iterator];
3982 pkgDepCache::StateCache &state(cache[iterator]);
3984 NSString *name([package name]);
3986 if (state.NewInstall())
3987 [installing addObject:name];
3988 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3989 [reinstalling addObject:name];
3990 else if (state.Upgrade())
3991 [upgrading addObject:name];
3992 else if (state.Downgrade())
3993 [downgrading addObject:name];
3994 else if (state.Delete()) {
3995 if ([package essential])
3997 [removing addObject:name];
4000 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4001 substrate_ |= DepSubstrate(iterator.CurrentVer());
4006 else if (Advanced_) {
4007 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4009 essential_ = [[UIActionSheet alloc]
4010 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4011 buttons:[NSArray arrayWithObjects:
4012 [NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")],
4013 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4015 defaultButtonIndex:0
4020 [essential_ setDestructiveButtonIndex:1];
4021 [essential_ setBodyText:UCLocalize("REMOVING_ESSENTIALS_EX")];
4023 essential_ = [[UIActionSheet alloc]
4024 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4025 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4026 defaultButtonIndex:0
4031 [essential_ setBodyText:UCLocalize("UNABLE_TO_COMPLY_EX")];
4034 changes_ = [[NSArray alloc] initWithObjects:
4042 issues_ = [database_ issues];
4044 issues_ = [issues_ retain];
4046 sizes_ = [[NSArray alloc] initWithObjects:
4047 SizeString([database_ fetcher].FetchNeeded()),
4048 SizeString([database_ fetcher].PartialPresent()),
4049 SizeString([database_ cache]->UsrSize()),
4052 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4056 - (NSString *) backButtonTitle {
4057 return UCLocalize("CONFIRM");
4060 - (NSString *) leftButtonTitle {
4061 return [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")];
4064 - (id) rightButtonTitle {
4065 return issues_ != nil ? nil : [super rightButtonTitle];
4068 - (id) _rightButtonTitle {
4069 #if AlwaysReload || IgnoreInstall
4070 return [super _rightButtonTitle];
4072 return UCLocalize("CONFIRM");
4076 - (void) _leftButtonClicked {
4081 - (void) _rightButtonClicked {
4083 return [super _rightButtonClicked];
4085 if (essential_ != nil)
4086 [essential_ popupAlertAnimated:YES];
4090 [delegate_ confirm];
4098 /* Progress Data {{{ */
4099 @interface ProgressData : NSObject {
4105 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4112 @implementation ProgressData
4114 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4115 if ((self = [super init]) != nil) {
4116 selector_ = selector;
4136 /* Progress View {{{ */
4137 @interface ProgressView : UIView <
4138 ConfigurationDelegate,
4141 _transient Database *database_;
4143 UIView *background_;
4144 UITransitionView *transition_;
4146 UINavigationBar *navbar_;
4147 UIProgressBar *progress_;
4148 UITextView *output_;
4149 UITextLabel *status_;
4150 UIPushButton *close_;
4153 SHA1SumValue springlist_;
4154 SHA1SumValue notifyconf_;
4158 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
4159 - (void) setContentView:(UIView *)view;
4162 - (void) _retachThread;
4163 - (void) _detachNewThreadData:(ProgressData *)data;
4164 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4170 @protocol ProgressViewDelegate
4171 - (void) progressViewIsComplete:(ProgressView *)sender;
4174 @implementation ProgressView
4177 [transition_ setDelegate:nil];
4178 [navbar_ setDelegate:nil];
4181 if (background_ != nil)
4182 [background_ release];
4183 [transition_ release];
4186 [progress_ release];
4195 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
4196 if ((self = [super initWithFrame:frame]) != nil) {
4197 database_ = database;
4198 delegate_ = delegate;
4200 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
4201 [transition_ setDelegate:self];
4203 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
4205 background_ = [[UIView alloc] initWithFrame:[self bounds]];
4206 [background_ setBackgroundColor:[UIColor blackColor]];
4207 [self addSubview:background_];
4209 [self addSubview:transition_];
4211 CGSize navsize = [UINavigationBar defaultSize];
4212 CGRect navrect = {{0, 0}, navsize};
4214 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
4215 [overlay_ addSubview:navbar_];
4217 [navbar_ setBarStyle:1];
4218 [navbar_ setDelegate:self];
4220 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
4221 [navbar_ pushNavigationItem:navitem];
4223 CGRect bounds = [overlay_ bounds];
4224 CGSize prgsize = [UIProgressBar defaultSize];
4227 (bounds.size.width - prgsize.width) / 2,
4228 bounds.size.height - prgsize.height - 20
4231 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
4232 [progress_ setStyle:0];
4234 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
4236 bounds.size.height - prgsize.height - 50,
4237 bounds.size.width - 20,
4241 [status_ setColor:[UIColor whiteColor]];
4242 [status_ setBackgroundColor:[UIColor clearColor]];
4244 [status_ setCentersHorizontally:YES];
4245 //[status_ setFont:font];
4247 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
4249 navrect.size.height + 20,
4250 bounds.size.width - 20,
4251 bounds.size.height - navsize.height - 62 - navrect.size.height
4254 //[output_ setTextFont:@"Courier New"];
4255 [output_ setFont:[[output_ font] fontWithSize:12]];
4257 [output_ setTextColor:[UIColor whiteColor]];
4258 [output_ setBackgroundColor:[UIColor clearColor]];
4260 [output_ setMarginTop:0];
4261 [output_ setAllowsRubberBanding:YES];
4262 [output_ setEditable:NO];
4264 [overlay_ addSubview:output_];
4266 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
4268 bounds.size.height - prgsize.height - 50,
4269 bounds.size.width - 20,
4273 [close_ setAutosizesToFit:NO];
4274 [close_ setDrawsShadow:YES];
4275 [close_ setStretchBackground:YES];
4276 [close_ setEnabled:YES];
4278 UIFont *bold = [UIFont boldSystemFontOfSize:22];
4279 [close_ setTitleFont:bold];
4281 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4282 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4283 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4287 - (void) setContentView:(UIView *)view {
4288 view_ = [view retain];
4291 - (void) resetView {
4292 [transition_ transition:6 toView:view_];
4295 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4296 NSString *context([sheet context]);
4298 if ([context isEqualToString:@"conffile"]) {
4299 FILE *input = [database_ input];
4303 fprintf(input, "N\n");
4307 fprintf(input, "Y\n");
4317 - (void) closeButtonPushed {
4326 [delegate_ terminateWithSuccess];
4327 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4328 [delegate_ suspendWithAnimation:YES];
4330 [delegate_ suspend];*/
4334 system("launchctl stop com.apple.SpringBoard");
4338 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4347 - (void) _retachThread {
4348 UINavigationItem *item([navbar_ topItem]);
4349 [item setTitle:UCLocalize("COMPLETE")];
4351 [overlay_ addSubview:close_];
4352 [progress_ removeFromSuperview];
4353 [status_ removeFromSuperview];
4355 [database_ popErrorWithTitle:title_];
4356 [delegate_ progressViewIsComplete:self];
4360 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4363 MMap mmap(file, MMap::ReadOnly);
4365 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4366 if (!(notifyconf_ == sha1.Result()))
4373 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4376 MMap mmap(file, MMap::ReadOnly);
4378 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4379 if (!(springlist_ == sha1.Result()))
4385 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break;
4386 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4387 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4388 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4389 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4392 #define ListCache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4393 #define IconCache_ "/User/Library/Caches/com.apple.springboard-imagecache-icons.plist"
4397 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ListCache_]) {
4398 [cache autorelease];
4400 NSFileManager *manager([NSFileManager defaultManager]);
4401 NSError *error(nil);
4403 id system([cache objectForKey:@"System"]);
4408 if (stat(ListCache_, &info) == -1)
4411 [system removeAllObjects];
4413 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4414 for (NSString *app in apps)
4415 if ([app hasSuffix:@".app"]) {
4416 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4417 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4418 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4420 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4421 [info setObject:path forKey:@"Path"];
4422 [info setObject:@"System" forKey:@"ApplicationType"];
4423 [system addInfoDictionary:info];
4429 [cache writeToFile:@ListCache_ atomically:YES];
4431 if (chown(ListCache_, info.st_uid, info.st_gid) == -1)
4433 if (chmod(ListCache_, info.st_mode) == -1)
4437 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4440 notify_post("com.apple.mobile.application_installed");
4442 [delegate_ setStatusBarShowsProgress:NO];
4445 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4446 [[data target] performSelector:[data selector] withObject:[data object]];
4449 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4452 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4458 title_ = [title retain];
4460 UINavigationItem *item([navbar_ topItem]);
4461 [item setTitle:title_];
4463 [status_ setText:nil];
4464 [output_ setText:@""];
4465 [progress_ setProgress:0];
4467 [close_ removeFromSuperview];
4468 [overlay_ addSubview:progress_];
4469 [overlay_ addSubview:status_];
4471 [delegate_ setStatusBarShowsProgress:YES];
4476 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4479 MMap mmap(file, MMap::ReadOnly);
4481 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4482 notifyconf_ = sha1.Result();
4488 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4491 MMap mmap(file, MMap::ReadOnly);
4493 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4494 springlist_ = sha1.Result();
4498 [transition_ transition:6 toView:overlay_];
4501 detachNewThreadSelector:@selector(_detachNewThreadData:)
4503 withObject:[[ProgressData alloc]
4504 initWithSelector:selector
4511 - (void) repairWithSelector:(SEL)selector {
4513 detachNewThreadSelector:selector
4516 title:UCLocalize("REPAIRING")
4520 - (void) setConfigurationData:(NSString *)data {
4522 performSelectorOnMainThread:@selector(_setConfigurationData:)
4528 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4529 CYActionSheet *sheet([[[CYActionSheet alloc]
4531 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4532 defaultButtonIndex:0
4535 [sheet setBodyText:error];
4536 [sheet yieldToPopupAlertAnimated:YES];
4540 - (void) setProgressTitle:(NSString *)title {
4542 performSelectorOnMainThread:@selector(_setProgressTitle:)
4548 - (void) setProgressPercent:(float)percent {
4550 performSelectorOnMainThread:@selector(_setProgressPercent:)
4551 withObject:[NSNumber numberWithFloat:percent]
4556 - (void) startProgress {
4559 - (void) addProgressOutput:(NSString *)output {
4561 performSelectorOnMainThread:@selector(_addProgressOutput:)
4567 - (bool) isCancelling:(size_t)received {
4571 - (void) _setConfigurationData:(NSString *)data {
4572 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4574 if (!conffile_r(data)) {
4575 lprintf("E:invalid conffile\n");
4579 NSString *ofile = conffile_r[1];
4580 //NSString *nfile = conffile_r[2];
4582 UIActionSheet *sheet = [[[UIActionSheet alloc]
4583 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4584 buttons:[NSArray arrayWithObjects:
4585 UCLocalize("KEEP_OLD_COPY"),
4586 UCLocalize("ACCEPT_NEW_COPY"),
4587 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4589 defaultButtonIndex:0
4594 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4595 [sheet popupAlertAnimated:YES];
4598 - (void) _setProgressTitle:(NSString *)title {
4599 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4600 for (size_t i(0), e([words count]); i != e; ++i) {
4601 NSString *word([words objectAtIndex:i]);
4602 if (Package *package = [database_ packageWithName:word])
4603 [words replaceObjectAtIndex:i withObject:[package name]];
4606 [status_ setText:[words componentsJoinedByString:@" "]];
4609 - (void) _setProgressPercent:(NSNumber *)percent {
4610 [progress_ setProgress:[percent floatValue]];
4613 - (void) _addProgressOutput:(NSString *)output {
4614 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4615 CGSize size = [output_ contentSize];
4616 CGRect rect = {{0, size.height}, {size.width, 0}};
4617 [output_ scrollRectToVisible:rect animated:YES];
4620 - (BOOL) isRunning {
4627 /* Package Cell {{{ */
4628 @interface ContentView : UIView {
4629 _transient id delegate_;
4634 @interface PackageCell : UITableViewCell {
4637 NSString *description_;
4643 ContentView *content_;
4649 - (PackageCell *) init;
4650 - (void) setPackage:(Package *)package;
4652 + (int) heightForPackage:(Package *)package;
4653 - (void) drawContentRect:(CGRect)rect;
4657 @implementation ContentView
4659 - (id) initWithFrame:(CGRect)frame {
4660 if ((self = [super initWithFrame:frame]) != nil) {
4664 - (void) setDelegate:(id)delegate {
4665 delegate_ = delegate;
4668 - (void) drawRect:(CGRect)rect {
4669 [super drawRect:rect];
4670 [delegate_ drawContentRect:rect];
4675 @implementation PackageCell
4677 - (void) clearPackage {
4688 if (description_ != nil) {
4689 [description_ release];
4693 if (source_ != nil) {
4698 if (badge_ != nil) {
4703 if (placard_ != nil) {
4713 [self clearPackage];
4720 return faded_ ? [self selectionPercent] : fade_;
4723 - (PackageCell *) init {
4724 CGRect frame(CGRectMake(0, 0, 320, 74));
4725 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4726 UIView *content([self contentView]);
4727 CGRect bounds([content bounds]);
4728 content_ = [[ContentView alloc] initWithFrame:bounds];
4729 [content_ setDelegate:self];
4730 [content_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
4731 [content_ setOpaque:YES];
4732 [content addSubview:content_];
4733 if ([self respondsToSelector:@selector(selectionPercent)])
4738 - (void) _setBackgroundColor {
4740 if (NSString *mode = [package_ mode]) {
4741 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4742 color = remove ? RemovingColor_ : InstallingColor_;
4744 color = [UIColor whiteColor];
4746 [content_ setBackgroundColor:color];
4747 [self setNeedsDisplay];
4750 - (void) setPackage:(Package *)package {
4751 [self clearPackage];
4754 Source *source = [package source];
4756 icon_ = [[package icon] retain];
4757 name_ = [[package name] retain];
4758 description_ = [[package shortDescription] retain];
4759 commercial_ = [package isCommercial];
4761 package_ = [package retain];
4763 NSString *label = nil;
4764 bool trusted = false;
4766 if (source != nil) {
4767 label = [source label];
4768 trusted = [source trusted];
4769 } else if ([[package id] isEqualToString:@"firmware"])
4770 label = UCLocalize("APPLE");
4772 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4774 NSString *from(label);
4776 NSString *section = [package simpleSection];
4777 if (section != nil && ![section isEqualToString:label]) {
4778 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4779 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4782 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4783 source_ = [from retain];
4785 if (NSString *purpose = [package primaryPurpose])
4786 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4787 badge_ = [badge_ retain];
4789 if ([package installed] != nil)
4790 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4791 placard_ = [placard_ retain];
4793 [self _setBackgroundColor];
4794 [content_ setNeedsDisplay];
4797 - (void) drawContentRect:(CGRect)rect {
4798 bool selected([self isSelected]);
4801 CGContextRef context(UIGraphicsGetCurrentContext());
4802 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4803 CGContextFillRect(context, rect);
4808 rect.size = [icon_ size];
4810 rect.size.width /= 2;
4811 rect.size.height /= 2;
4813 rect.origin.x = 25 - rect.size.width / 2;
4814 rect.origin.y = 25 - rect.size.height / 2;
4816 [icon_ drawInRect:rect];
4819 if (badge_ != nil) {
4820 CGSize size = [badge_ size];
4822 [badge_ drawAtPoint:CGPointMake(
4823 36 - size.width / 2,
4824 36 - size.height / 2
4832 UISetColor(commercial_ ? Purple_ : Black_);
4833 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(placard_ == nil ? 240 : 214) withFont:Font18Bold_ ellipsis:2];
4834 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4837 UISetColor(commercial_ ? Purplish_ : Gray_);
4838 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:274 withFont:Font14_ ellipsis:2];
4840 if (placard_ != nil)
4841 [placard_ drawAtPoint:CGPointMake(268, 9)];
4844 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4845 //[self _setBackgroundColor];
4846 [super setSelected:selected animated:fade];
4847 [content_ setNeedsDisplay];
4850 + (int) heightForPackage:(Package *)package {
4856 /* Section Cell {{{ */
4857 @interface SectionCell : UISimpleTableCell {
4862 _UISwitchSlider *switch_;
4867 - (void) setSection:(Section *)section editing:(BOOL)editing;
4871 @implementation SectionCell
4873 - (void) clearSection {
4874 if (section_ != nil) {
4884 if (count_ != nil) {
4891 [self clearSection];
4898 if ((self = [super init]) != nil) {
4899 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4901 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4902 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventTouchUpInside];
4906 - (void) onSwitch:(id)sender {
4907 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4908 if (metadata == nil) {
4909 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4910 [Sections_ setObject:metadata forKey:section_];
4914 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4917 - (void) setSection:(Section *)section editing:(BOOL)editing {
4918 if (editing != editing_) {
4920 [switch_ removeFromSuperview];
4922 [self addSubview:switch_];
4926 [self clearSection];
4928 if (section == nil) {
4929 name_ = [UCLocalize("ALL_PACKAGES") retain];
4932 section_ = [section localized];
4933 if (section_ != nil)
4934 section_ = [section_ retain];
4935 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4936 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4939 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4943 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4944 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4951 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4953 CGSize size = [count_ sizeWithFont:Font14_];
4957 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4959 [super drawContentInRect:rect selected:selected];
4965 /* File Table {{{ */
4966 @interface FileTable : RVPage {
4967 _transient Database *database_;
4970 NSMutableArray *files_;
4974 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4975 - (void) setPackage:(Package *)package;
4979 @implementation FileTable
4982 if (package_ != nil)
4991 - (int) numberOfRowsInTable:(UITable *)table {
4992 return files_ == nil ? 0 : [files_ count];
4995 - (float) table:(UITable *)table heightForRow:(int)row {
4999 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
5000 if (reusing == nil) {
5001 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
5002 UIFont *font = [UIFont systemFontOfSize:16];
5003 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
5005 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
5009 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5013 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5014 if ((self = [super initWithBook:book]) != nil) {
5015 database_ = database;
5017 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5019 list_ = [[UITable alloc] initWithFrame:[self bounds]];
5020 [self addSubview:list_];
5022 UITableColumn *column = [[[UITableColumn alloc]
5023 initWithTitle:UCLocalize("NAME")
5025 width:[self frame].size.width
5028 [list_ setDataSource:self];
5029 [list_ setSeparatorStyle:1];
5030 [list_ addTableColumn:column];
5031 [list_ setDelegate:self];
5032 [list_ setReusesTableCells:YES];
5036 - (void) setPackage:(Package *)package {
5037 if (package_ != nil) {
5038 [package_ autorelease];
5047 [files_ removeAllObjects];
5049 if (package != nil) {
5050 package_ = [package retain];
5051 name_ = [[package id] retain];
5053 if (NSArray *files = [package files])
5054 [files_ addObjectsFromArray:files];
5056 if ([files_ count] != 0) {
5057 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5058 [files_ removeObjectAtIndex:0];
5059 [files_ sortUsingSelector:@selector(compareByPath:)];
5061 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5062 [stack addObject:@"/"];
5064 for (int i(0), e([files_ count]); i != e; ++i) {
5065 NSString *file = [files_ objectAtIndex:i];
5066 while (![file hasPrefix:[stack lastObject]])
5067 [stack removeLastObject];
5068 NSString *directory = [stack lastObject];
5069 [stack addObject:[file stringByAppendingString:@"/"]];
5070 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5071 ([stack count] - 2) * 3, "",
5072 [file substringFromIndex:[directory length]]
5081 - (void) resetViewAnimated:(BOOL)animated {
5082 [list_ resetViewAnimated:animated];
5085 - (void) reloadData {
5086 [self setPackage:[database_ packageWithName:name_]];
5087 [self reloadButtons];
5090 - (NSString *) title {
5091 return UCLocalize("INSTALLED_FILES");
5094 - (NSString *) backButtonTitle {
5095 return UCLocalize("FILES");
5100 /* Package View {{{ */
5101 @interface PackageView : CydiaBrowserView {
5102 _transient Database *database_;
5106 NSMutableArray *buttons_;
5109 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5110 - (void) setPackage:(Package *)package;
5114 @implementation PackageView
5117 if (package_ != nil)
5126 if ([self retainCount] == 1)
5127 [delegate_ setPackageView:self];
5131 /* XXX: this is not safe at all... localization of /fail/ */
5132 - (void) _clickButtonWithName:(NSString *)name {
5133 if ([name isEqualToString:UCLocalize("CLEAR")])
5134 [delegate_ clearPackage:package_];
5135 else if ([name isEqualToString:UCLocalize("INSTALL")])
5136 [delegate_ installPackage:package_];
5137 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5138 [delegate_ installPackage:package_];
5139 else if ([name isEqualToString:UCLocalize("REMOVE")])
5140 [delegate_ removePackage:package_];
5141 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5142 [delegate_ installPackage:package_];
5143 else _assert(false);
5146 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5147 NSString *context([sheet context]);
5149 if ([context isEqualToString:@"modify"]) {
5150 int count = [buttons_ count];
5151 _assert(count != 0);
5152 _assert(button <= count + 1);
5154 if (count != button - 1)
5155 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
5159 [super alertSheet:sheet buttonClicked:button];
5162 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5163 return [super webView:sender didFinishLoadForFrame:frame];
5166 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5167 [super webView:sender didClearWindowObject:window forFrame:frame];
5168 [window setValue:package_ forKey:@"package"];
5171 - (bool) _allowJavaScriptPanel {
5176 - (void) __rightButtonClicked {
5177 int count([buttons_ count]);
5182 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5184 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
5185 [buttons addObjectsFromArray:buttons_];
5186 [buttons addObject:UCLocalize("CANCEL")];
5188 [delegate_ slideUp:[[[UIActionSheet alloc]
5191 defaultButtonIndex:([buttons count] - 1)
5198 - (void) _rightButtonClicked {
5200 [super _rightButtonClicked];
5202 [self __rightButtonClicked];
5206 - (id) _rightButtonTitle {
5207 int count = [buttons_ count];
5208 return count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0];
5211 - (NSString *) backButtonTitle {
5215 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5216 if ((self = [super initWithBook:book]) != nil) {
5217 database_ = database;
5218 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5219 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5223 - (void) setPackage:(Package *)package {
5224 if (package_ != nil) {
5225 [package_ autorelease];
5234 [buttons_ removeAllObjects];
5236 if (package != nil) {
5239 package_ = [package retain];
5240 name_ = [[package id] retain];
5241 commercial_ = [package isCommercial];
5243 if ([package_ mode] != nil)
5244 [buttons_ addObject:UCLocalize("CLEAR")];
5245 if ([package_ source] == nil);
5246 else if ([package_ upgradableAndEssential:NO])
5247 [buttons_ addObject:UCLocalize("UPGRADE")];
5248 else if ([package_ uninstalled])
5249 [buttons_ addObject:UCLocalize("INSTALL")];
5251 [buttons_ addObject:UCLocalize("REINSTALL")];
5252 if (![package_ uninstalled])
5253 [buttons_ addObject:UCLocalize("REMOVE")];
5255 if (special_ != NULL) {
5256 CGRect frame([webview_ frame]);
5257 frame.size.width = 320;
5258 frame.size.height = 0;
5259 [webview_ setFrame:frame];
5261 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5264 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5266 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5268 [self setFinishHook:nil];
5269 [self setPopupHook:nil];
5272 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5273 [super callFunction:special_];
5277 [self reloadButtons];
5280 - (bool) isLoading {
5281 return commercial_ ? [super isLoading] : false;
5284 - (void) reloadData {
5285 [self setPackage:[database_ packageWithName:name_]];
5290 /* Package Table {{{ */
5291 @interface PackageTable : RVPage {
5292 _transient Database *database_;
5294 NSMutableArray *packages_;
5295 NSMutableArray *sections_;
5297 NSMutableArray *index_;
5298 NSMutableDictionary *indices_;
5301 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5303 - (void) setDelegate:(id)delegate;
5305 - (void) reloadData;
5306 - (void) resetCursor;
5308 - (UITableView *) list;
5310 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5314 @implementation PackageTable
5317 [list_ setDataSource:nil];
5320 [packages_ release];
5321 [sections_ release];
5328 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5329 NSInteger count([sections_ count]);
5330 return count == 0 ? 1 : count;
5333 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5334 if ([sections_ count] == 0)
5336 return [[sections_ objectAtIndex:section] name];
5339 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5340 if ([sections_ count] == 0)
5342 return [[sections_ objectAtIndex:section] count];
5345 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5346 Section *section([sections_ objectAtIndex:[path section]]);
5347 NSInteger row([path row]);
5348 Package *package([packages_ objectAtIndex:([section row] + row)]);
5352 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5353 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
5355 cell = [[[PackageCell alloc] init] autorelease];
5356 [cell setPackage:[self packageAtIndexPath:path]];
5360 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5362 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5365 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5366 Package *package([self packageAtIndexPath:path]);
5367 package = [database_ packageWithName:[package id]];
5368 PackageView *view([delegate_ packageView]);
5369 [view setPackage:package];
5370 [view setDelegate:delegate_];
5371 [book_ pushPage:view];
5375 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5376 return [packages_ count] > 20 ? index_ : nil;
5379 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5383 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5384 if ((self = [super initWithBook:book]) != nil) {
5385 database_ = database;
5386 title_ = [title retain];
5388 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5389 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5391 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5392 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5394 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5395 [list_ setDataSource:self];
5396 [list_ setDelegate:self];
5398 [self addSubview:list_];
5400 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5401 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5405 - (void) setDelegate:(id)delegate {
5406 delegate_ = delegate;
5409 - (bool) hasPackage:(Package *)package {
5413 - (void) reloadData {
5414 NSArray *packages = [database_ packages];
5416 [packages_ removeAllObjects];
5417 [sections_ removeAllObjects];
5419 _profile(PackageTable$reloadData$Filter)
5420 for (Package *package in packages)
5421 if ([self hasPackage:package])
5422 [packages_ addObject:package];
5425 [index_ removeAllObjects];
5426 [indices_ removeAllObjects];
5428 Section *section = nil;
5430 _profile(PackageTable$reloadData$Section)
5431 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5435 _profile(PackageTable$reloadData$Section$Package)
5436 package = [packages_ objectAtIndex:offset];
5437 index = [package index];
5440 if (section == nil || [section index] != index) {
5441 _profile(PackageTable$reloadData$Section$Allocate)
5442 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5445 [index_ addObject:[section name]];
5446 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5448 _profile(PackageTable$reloadData$Section$Add)
5449 [sections_ addObject:section];
5453 [section addToCount];
5457 _profile(PackageTable$reloadData$List)
5462 - (NSString *) title {
5466 - (void) resetViewAnimated:(BOOL)animated {
5467 [list_ resetViewAnimated:animated];
5470 - (void) resetCursor {
5471 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5474 - (UITableView *) list {
5478 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5479 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5484 /* Filtered Package Table {{{ */
5485 @interface FilteredPackageTable : PackageTable {
5491 - (void) setObject:(id)object;
5493 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5497 @implementation FilteredPackageTable
5505 - (void) setObject:(id)object {
5511 object_ = [object retain];
5514 - (bool) hasPackage:(Package *)package {
5515 _profile(FilteredPackageTable$hasPackage)
5516 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5520 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5521 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5523 object_ = object == nil ? nil : [object retain];
5525 /* XXX: this is an unsafe optimization of doomy hell */
5526 Method method(class_getInstanceMethod([Package class], filter));
5527 _assert(method != NULL);
5528 imp_ = method_getImplementation(method);
5529 _assert(imp_ != NULL);
5538 /* Add Source View {{{ */
5539 @interface AddSourceView : RVPage {
5540 _transient Database *database_;
5543 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5547 @implementation AddSourceView
5549 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5550 if ((self = [super initWithBook:book]) != nil) {
5551 database_ = database;
5557 /* Source Cell {{{ */
5558 @interface SourceCell : UITableCell {
5561 NSString *description_;
5567 - (SourceCell *) initWithSource:(Source *)source;
5571 @implementation SourceCell
5576 [description_ release];
5581 - (SourceCell *) initWithSource:(Source *)source {
5582 if ((self = [super init]) != nil) {
5584 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5586 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5587 icon_ = [icon_ retain];
5589 origin_ = [[source name] retain];
5590 label_ = [[source uri] retain];
5591 description_ = [[source description] retain];
5595 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5597 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5604 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5608 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5612 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5614 [super drawContentInRect:rect selected:selected];
5619 /* Source Table {{{ */
5620 @interface SourceTable : RVPage {
5621 _transient Database *database_;
5622 UISectionList *list_;
5623 NSMutableArray *sources_;
5624 UIActionSheet *alert_;
5628 UIProgressHUD *hud_;
5631 //NSURLConnection *installer_;
5632 NSURLConnection *trivial_;
5633 NSURLConnection *trivial_bz2_;
5634 NSURLConnection *trivial_gz_;
5635 //NSURLConnection *automatic_;
5640 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5644 @implementation SourceTable
5646 - (void) _deallocConnection:(NSURLConnection *)connection {
5647 if (connection != nil) {
5648 [connection cancel];
5649 //[connection setDelegate:nil];
5650 [connection release];
5655 [[list_ table] setDelegate:nil];
5656 [list_ setDataSource:nil];
5665 //[self _deallocConnection:installer_];
5666 [self _deallocConnection:trivial_];
5667 [self _deallocConnection:trivial_gz_];
5668 [self _deallocConnection:trivial_bz2_];
5669 //[self _deallocConnection:automatic_];
5676 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5677 return offset_ == 0 ? 1 : 2;
5680 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5681 switch (section + (offset_ == 0 ? 1 : 0)) {
5682 case 0: return UCLocalize("ENTERED_BY_USER");
5683 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5689 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5690 switch (section + (offset_ == 0 ? 1 : 0)) {
5692 case 1: return offset_;
5698 - (int) numberOfRowsInTable:(UITable *)table {
5699 return [sources_ count];
5702 - (float) table:(UITable *)table heightForRow:(int)row {
5703 Source *source = [sources_ objectAtIndex:row];
5704 return [source description] == nil ? 56 : 73;
5707 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5708 Source *source = [sources_ objectAtIndex:row];
5709 // XXX: weird warning, stupid selectors ;P
5710 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5713 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5717 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5721 - (void) tableRowSelected:(NSNotification*)notification {
5722 UITable *table([list_ table]);
5723 int row([table selectedRow]);
5727 Source *source = [sources_ objectAtIndex:row];
5729 PackageTable *packages = [[[FilteredPackageTable alloc]
5732 title:[source label]
5733 filter:@selector(isVisibleInSource:)
5737 [packages setDelegate:delegate_];
5739 [book_ pushPage:packages];
5742 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5743 Source *source = [sources_ objectAtIndex:row];
5744 return [source record] != nil;
5747 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5748 [[list_ table] setDeleteConfirmationRow:row];
5751 - (void) table:(UITable *)table deleteRow:(int)row {
5752 Source *source = [sources_ objectAtIndex:row];
5753 [Sources_ removeObjectForKey:[source key]];
5754 [delegate_ syncData];
5758 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5761 @"./", @"Distribution",
5762 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5764 [delegate_ syncData];
5767 - (NSString *) getWarning {
5768 NSString *href(href_);
5769 NSRange colon([href rangeOfString:@"://"]);
5770 if (colon.location != NSNotFound)
5771 href = [href substringFromIndex:(colon.location + 3)];
5772 href = [href stringByAddingPercentEscapes];
5773 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5774 href = [href stringByCachingURLWithCurrentCDN];
5776 NSURL *url([NSURL URLWithString:href]);
5778 NSStringEncoding encoding;
5779 NSError *error(nil);
5781 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5782 return [warning length] == 0 ? nil : warning;
5786 - (void) _endConnection:(NSURLConnection *)connection {
5787 NSURLConnection **field = NULL;
5788 if (connection == trivial_)
5790 else if (connection == trivial_bz2_)
5791 field = &trivial_bz2_;
5792 else if (connection == trivial_gz_)
5793 field = &trivial_gz_;
5794 _assert(field != NULL);
5795 [connection release];
5800 trivial_bz2_ == nil &&
5806 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5809 UIActionSheet *sheet = [[[UIActionSheet alloc]
5810 initWithTitle:UCLocalize("SOURCE_WARNING")
5811 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_ANYWAY"), UCLocalize("CANCEL"), nil]
5812 defaultButtonIndex:0
5817 [sheet setNumberOfRows:1];
5819 [sheet setBodyText:warning];
5820 [sheet popupAlertAnimated:YES];
5823 } else if (error_ != nil) {
5824 UIActionSheet *sheet = [[[UIActionSheet alloc]
5825 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5826 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5827 defaultButtonIndex:0
5832 [sheet setBodyText:[error_ localizedDescription]];
5833 [sheet popupAlertAnimated:YES];
5835 UIActionSheet *sheet = [[[UIActionSheet alloc]
5836 initWithTitle:UCLocalize("NOT_REPOSITORY")
5837 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5838 defaultButtonIndex:0
5843 [sheet setBodyText:UCLocalize("NOT_REPOSITORY_EX")];
5844 [sheet popupAlertAnimated:YES];
5847 [delegate_ setStatusBarShowsProgress:NO];
5848 [delegate_ removeProgressHUD:hud_];
5858 if (error_ != nil) {
5865 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5866 switch ([response statusCode]) {
5872 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5873 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5875 error_ = [error retain];
5876 [self _endConnection:connection];
5879 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5880 [self _endConnection:connection];
5883 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5884 NSMutableURLRequest *request = [NSMutableURLRequest
5885 requestWithURL:[NSURL URLWithString:href]
5886 cachePolicy:NSURLRequestUseProtocolCachePolicy
5887 timeoutInterval:20.0
5890 [request setHTTPMethod:method];
5892 if (Machine_ != NULL)
5893 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5894 if (UniqueID_ != nil)
5895 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5898 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5900 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5903 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5904 NSString *context([sheet context]);
5906 if ([context isEqualToString:@"source"]) {
5909 NSString *href = [[sheet textField] text];
5911 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5913 if (![href hasSuffix:@"/"])
5914 href_ = [href stringByAppendingString:@"/"];
5917 href_ = [href_ retain];
5919 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
5920 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5921 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5922 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5926 hud_ = [[delegate_ addProgressHUD] retain];
5927 [hud_ setText:UCLocalize("VERIFYING_URL")];
5937 } else if ([context isEqualToString:@"trivial"])
5939 else if ([context isEqualToString:@"urlerror"])
5941 else if ([context isEqualToString:@"warning"]) {
5960 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5961 if ((self = [super initWithBook:book]) != nil) {
5962 database_ = database;
5963 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5965 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5966 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5967 [list_ setShouldHideHeaderInShortLists:NO];
5969 [self addSubview:list_];
5970 [list_ setDataSource:self];
5972 UITableColumn *column = [[UITableColumn alloc]
5973 initWithTitle:UCLocalize("NAME")
5975 width:[self frame].size.width
5978 UITable *table = [list_ table];
5979 [table setSeparatorStyle:1];
5980 [table addTableColumn:column];
5981 [table setDelegate:self];
5985 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5986 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5990 - (void) reloadData {
5992 if (!list.ReadMainList())
5995 [sources_ removeAllObjects];
5996 [sources_ addObjectsFromArray:[database_ sources]];
5998 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6001 int count([sources_ count]);
6002 for (offset_ = 0; offset_ != count; ++offset_) {
6003 Source *source = [sources_ objectAtIndex:offset_];
6004 if ([source record] == nil)
6011 - (void) resetViewAnimated:(BOOL)animated {
6012 [list_ resetViewAnimated:animated];
6015 - (void) _leftButtonClicked {
6016 /*[book_ pushPage:[[[AddSourceView alloc]
6021 UIActionSheet *sheet = [[[UIActionSheet alloc]
6022 initWithTitle:UCLocalize("ENTER_APT_URL")
6023 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_SOURCE"), UCLocalize("CANCEL"), nil]
6024 defaultButtonIndex:0
6029 [sheet setNumberOfRows:1];
6031 [sheet addTextFieldWithValue:@"http://" label:@""];
6033 UITextInputTraits *traits = [[sheet textField] textInputTraits];
6034 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6035 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6036 [traits setKeyboardType:UIKeyboardTypeURL];
6037 // XXX: UIReturnKeyDone
6038 [traits setReturnKeyType:UIReturnKeyNext];
6040 [sheet popupAlertAnimated:YES];
6043 - (void) _rightButtonClicked {
6044 UITable *table = [list_ table];
6045 BOOL editing = [table isRowDeletionEnabled];
6046 [table enableRowDeletion:!editing animated:YES];
6047 [book_ reloadButtonsForPage:self];
6050 - (NSString *) title {
6051 return UCLocalize("SOURCES");
6054 - (NSString *) leftButtonTitle {
6055 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("ADD") : nil;
6058 - (id) rightButtonTitle {
6059 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("DONE") : UCLocalize("EDIT");
6062 - (UINavigationButtonStyle) rightButtonStyle {
6063 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6069 /* Installed View {{{ */
6070 @interface InstalledView : RVPage {
6071 _transient Database *database_;
6072 FilteredPackageTable *packages_;
6076 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6080 @implementation InstalledView
6083 [packages_ release];
6087 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6088 if ((self = [super initWithBook:book]) != nil) {
6089 database_ = database;
6091 packages_ = [[FilteredPackageTable alloc]
6095 filter:@selector(isInstalledAndVisible:)
6096 with:[NSNumber numberWithBool:YES]
6099 [self addSubview:packages_];
6101 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6102 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6106 - (void) resetViewAnimated:(BOOL)animated {
6107 [packages_ resetViewAnimated:animated];
6110 - (void) reloadData {
6111 [packages_ reloadData];
6114 - (void) _rightButtonClicked {
6115 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6116 [packages_ reloadData];
6118 [book_ reloadButtonsForPage:self];
6121 - (NSString *) title {
6122 return UCLocalize("INSTALLED");
6125 - (NSString *) backButtonTitle {
6126 return UCLocalize("PACKAGES");
6129 - (id) rightButtonTitle {
6130 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE");
6133 - (UINavigationButtonStyle) rightButtonStyle {
6134 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6137 - (void) setDelegate:(id)delegate {
6138 [super setDelegate:delegate];
6139 [packages_ setDelegate:delegate];
6146 @interface HomeView : CydiaBrowserView {
6151 @implementation HomeView
6153 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6154 NSString *context([sheet context]);
6156 if ([context isEqualToString:@"about"])
6159 [super alertSheet:sheet buttonClicked:button];
6162 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6163 [super _setMoreHeaders:request];
6165 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6168 - (void) _leftButtonClicked {
6169 UIActionSheet *sheet = [[[UIActionSheet alloc]
6170 initWithTitle:UCLocalize("ABOUT_CYDIA")
6171 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
6172 defaultButtonIndex:0
6178 @"Copyright (C) 2008-2009\n"
6179 "Jay Freeman (saurik)\n"
6180 "saurik@saurik.com\n"
6181 "http://www.saurik.com/\n"
6184 "http://www.theokorigroup.com/\n"
6186 "College of Creative Studies,\n"
6187 "University of California,\n"
6189 "http://www.ccs.ucsb.edu/"
6192 [sheet popupAlertAnimated:YES];
6195 - (NSString *) leftButtonTitle {
6196 return UCLocalize("ABOUT");
6201 /* Manage View {{{ */
6202 @interface ManageView : CydiaBrowserView {
6207 @implementation ManageView
6209 - (NSString *) title {
6210 return UCLocalize("MANAGE");
6213 - (void) _leftButtonClicked {
6214 [delegate_ askForSettings];
6215 [delegate_ updateData];
6218 - (NSString *) leftButtonTitle {
6219 return UCLocalize("SETTINGS");
6223 - (id) _rightButtonTitle {
6224 return Queuing_ ? UCLocalize("QUEUE") : nil;
6227 - (UINavigationButtonStyle) rightButtonStyle {
6228 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6231 - (void) _rightButtonClicked {
6236 - (bool) isLoading {
6243 /* Cydia Book {{{ */
6244 @interface CYBook : RVBook <
6247 _transient Database *database_;
6248 UINavigationBar *overlay_;
6249 UINavigationBar *underlay_;
6250 UIProgressIndicator *indicator_;
6251 UITextLabel *prompt_;
6252 UIProgressBar *progress_;
6253 UINavigationButton *cancel_;
6257 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
6263 @implementation CYBook
6267 [indicator_ release];
6269 [progress_ release];
6274 - (NSString *) getTitleForPage:(RVPage *)page {
6275 return [super getTitleForPage:page];
6283 [UIView beginAnimations:nil context:NULL];
6285 CGRect ovrframe = [overlay_ frame];
6286 ovrframe.origin.y = 0;
6287 [overlay_ setFrame:ovrframe];
6289 CGRect barframe = [navbar_ frame];
6290 barframe.origin.y += ovrframe.size.height;
6291 [navbar_ setFrame:barframe];
6293 CGRect trnframe = [transition_ frame];
6294 trnframe.origin.y += ovrframe.size.height;
6295 trnframe.size.height -= ovrframe.size.height;
6296 [transition_ setFrame:trnframe];
6298 [UIView endAnimations];
6300 [indicator_ startAnimation];
6301 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6302 [progress_ setProgress:0];
6305 [overlay_ addSubview:cancel_];
6308 detachNewThreadSelector:@selector(_update)
6314 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6315 NSString *context([sheet context]);
6317 if ([context isEqualToString:@"refresh"])
6324 [indicator_ stopAnimation];
6326 [UIView beginAnimations:nil context:NULL];
6328 CGRect ovrframe = [overlay_ frame];
6329 ovrframe.origin.y = -ovrframe.size.height;
6330 [overlay_ setFrame:ovrframe];
6332 CGRect barframe = [navbar_ frame];
6333 barframe.origin.y -= ovrframe.size.height;
6334 [navbar_ setFrame:barframe];
6336 CGRect trnframe = [transition_ frame];
6337 trnframe.origin.y -= ovrframe.size.height;
6338 trnframe.size.height += ovrframe.size.height;
6339 [transition_ setFrame:trnframe];
6341 [UIView commitAnimations];
6343 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6346 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6347 if ((self = [super initWithFrame:frame]) != nil) {
6348 database_ = database;
6350 CGRect ovrrect([navbar_ bounds]);
6351 ovrrect.size.height = [UINavigationBar defaultSize].height;
6352 ovrrect.origin.y = -ovrrect.size.height;
6354 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6355 [self addSubview:overlay_];
6357 ovrrect.origin.y = frame.size.height;
6358 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6359 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6360 [self addSubview:underlay_];
6362 [overlay_ setBarStyle:1];
6363 [underlay_ setBarStyle:1];
6365 int barstyle([overlay_ _barStyle:NO]);
6366 bool ugly(barstyle == 0);
6368 UIProgressIndicatorStyle style = ugly ?
6369 UIProgressIndicatorStyleMediumBrown :
6370 UIProgressIndicatorStyleMediumWhite;
6372 CGSize indsize([UIProgressIndicator defaultSizeForStyle:style]);
6373 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6374 CGRect indrect = {{indoffset, indoffset}, indsize};
6376 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6377 [indicator_ setStyle:style];
6378 [overlay_ addSubview:indicator_];
6380 CGSize prmsize = {215, indsize.height + 4};
6383 indoffset * 2 + indsize.width,
6384 unsigned(ovrrect.size.height - prmsize.height) / 2 - 1
6387 UIFont *font([UIFont systemFontOfSize:15]);
6389 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6391 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6392 [prompt_ setBackgroundColor:[UIColor clearColor]];
6393 [prompt_ setFont:font];
6395 [overlay_ addSubview:prompt_];
6397 CGSize prgsize = {75, 100};
6400 ovrrect.size.width - prgsize.width - 10,
6401 (ovrrect.size.height - prgsize.height) / 2
6404 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6405 [progress_ setStyle:0];
6406 [overlay_ addSubview:progress_];
6408 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6409 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6411 CGRect frame = [cancel_ frame];
6412 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6413 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6414 [cancel_ setFrame:frame];
6416 [cancel_ setBarStyle:barstyle];
6420 - (void) _onCancel {
6422 [cancel_ removeFromSuperview];
6425 - (void) _update { _pooled
6427 status.setDelegate(self);
6428 [database_ updateWithStatus:status];
6431 performSelectorOnMainThread:@selector(_update_)
6437 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6438 [prompt_ setText:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6442 UIActionSheet *sheet = [[[UIActionSheet alloc]
6443 initWithTitle:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), UCLocalize("REFRESH")]
6444 buttons:[NSArray arrayWithObjects:
6447 defaultButtonIndex:0
6452 [sheet setBodyText:error];
6453 [sheet popupAlertAnimated:YES];
6455 [self reloadButtons];
6458 - (void) setProgressTitle:(NSString *)title {
6460 performSelectorOnMainThread:@selector(_setProgressTitle:)
6466 - (void) setProgressPercent:(float)percent {
6468 performSelectorOnMainThread:@selector(_setProgressPercent:)
6469 withObject:[NSNumber numberWithFloat:percent]
6474 - (void) startProgress {
6477 - (void) addProgressOutput:(NSString *)output {
6479 performSelectorOnMainThread:@selector(_addProgressOutput:)
6485 - (bool) isCancelling:(size_t)received {
6489 - (void) _setProgressTitle:(NSString *)title {
6490 [prompt_ setText:title];
6493 - (void) _setProgressPercent:(NSNumber *)percent {
6494 [progress_ setProgress:[percent floatValue]];
6497 - (void) _addProgressOutput:(NSString *)output {
6502 /* Cydia:// Protocol {{{ */
6503 @interface CydiaURLProtocol : NSURLProtocol {
6508 @implementation CydiaURLProtocol
6510 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6511 NSURL *url([request URL]);
6514 NSString *scheme([[url scheme] lowercaseString]);
6515 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6520 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6524 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6525 id<NSURLProtocolClient> client([self client]);
6527 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6529 NSData *data(UIImagePNGRepresentation(icon));
6531 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6532 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6533 [client URLProtocol:self didLoadData:data];
6534 [client URLProtocolDidFinishLoading:self];
6538 - (void) startLoading {
6539 id<NSURLProtocolClient> client([self client]);
6540 NSURLRequest *request([self request]);
6542 NSURL *url([request URL]);
6543 NSString *href([url absoluteString]);
6545 NSString *path([href substringFromIndex:8]);
6546 NSRange slash([path rangeOfString:@"/"]);
6549 if (slash.location == NSNotFound) {
6553 command = [path substringToIndex:slash.location];
6554 path = [path substringFromIndex:(slash.location + 1)];
6557 Database *database([Database sharedInstance]);
6559 if ([command isEqualToString:@"package-icon"]) {
6562 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6563 Package *package([database packageWithName:path]);
6566 UIImage *icon([package icon]);
6567 [self _returnPNGWithImage:icon forRequest:request];
6568 } else if ([command isEqualToString:@"source-icon"]) {
6571 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6572 NSString *source(Simplify(path));
6573 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6575 icon = [UIImage applicationImageNamed:@"unknown.png"];
6576 [self _returnPNGWithImage:icon forRequest:request];
6577 } else if ([command isEqualToString:@"uikit-image"]) {
6580 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6581 UIImage *icon(_UIImageWithName(path));
6582 [self _returnPNGWithImage:icon forRequest:request];
6583 } else if ([command isEqualToString:@"section-icon"]) {
6586 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6587 NSString *section(Simplify(path));
6588 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6590 icon = [UIImage applicationImageNamed:@"unknown.png"];
6591 [self _returnPNGWithImage:icon forRequest:request];
6593 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6597 - (void) stopLoading {
6603 /* Sections View {{{ */
6604 @interface SectionsView : RVPage {
6605 _transient Database *database_;
6606 NSMutableArray *sections_;
6607 NSMutableArray *filtered_;
6608 UITransitionView *transition_;
6614 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6615 - (void) reloadData;
6620 @implementation SectionsView
6623 [list_ setDataSource:nil];
6624 [list_ setDelegate:nil];
6626 [sections_ release];
6627 [filtered_ release];
6628 [transition_ release];
6630 [accessory_ release];
6634 - (int) numberOfRowsInTable:(UITable *)table {
6635 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6638 - (float) table:(UITable *)table heightForRow:(int)row {
6642 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6644 reusing = [[[SectionCell alloc] init] autorelease];
6645 [(SectionCell *)reusing setSection:(editing_ ?
6646 [sections_ objectAtIndex:row] :
6647 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6648 ) editing:editing_];
6652 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6656 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6660 - (void) tableRowSelected:(NSNotification *)notification {
6661 int row = [[notification object] selectedRow];
6672 title = UCLocalize("ALL_PACKAGES");
6674 section = [filtered_ objectAtIndex:(row - 1)];
6675 name = [section name];
6678 name = [NSString stringWithString:name];
6679 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6682 title = UCLocalize("NO_SECTION");
6686 PackageTable *table = [[[FilteredPackageTable alloc]
6690 filter:@selector(isVisibleInSection:)
6694 [table setDelegate:delegate_];
6696 [book_ pushPage:table];
6699 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6700 if ((self = [super initWithBook:book]) != nil) {
6701 database_ = database;
6703 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6704 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6706 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6707 [self addSubview:transition_];
6709 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6710 [transition_ transition:0 toView:list_];
6712 UITableColumn *column = [[[UITableColumn alloc]
6713 initWithTitle:UCLocalize("NAME")
6715 width:[self frame].size.width
6718 [list_ setDataSource:self];
6719 [list_ setSeparatorStyle:1];
6720 [list_ addTableColumn:column];
6721 [list_ setDelegate:self];
6722 [list_ setReusesTableCells:YES];
6726 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6727 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6731 - (void) reloadData {
6732 NSArray *packages = [database_ packages];
6734 [sections_ removeAllObjects];
6735 [filtered_ removeAllObjects];
6738 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6739 SectionMap sections;
6740 sections.resize(64);
6742 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6746 for (Package *package in packages) {
6747 NSString *name([package section]);
6748 NSString *key(name == nil ? @"" : name);
6753 _profile(SectionsView$reloadData$Section)
6754 section = §ions[key];
6755 if (*section == nil) {
6756 _profile(SectionsView$reloadData$Section$Allocate)
6757 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6762 [*section addToCount];
6764 _profile(SectionsView$reloadData$Filter)
6765 if (![package valid] || ![package visible])
6769 [*section addToRow];
6773 _profile(SectionsView$reloadData$Section)
6774 section = [sections objectForKey:key];
6775 if (section == nil) {
6776 _profile(SectionsView$reloadData$Section$Allocate)
6777 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6778 [sections setObject:section forKey:key];
6783 [section addToCount];
6785 _profile(SectionsView$reloadData$Filter)
6786 if (![package valid] || ![package visible])
6796 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6797 [sections_ addObject:i->second];
6799 [sections_ addObjectsFromArray:[sections allValues]];
6802 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6804 for (Section *section in sections_) {
6805 size_t count([section row]);
6809 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6810 [section setCount:count];
6811 [filtered_ addObject:section];
6818 - (void) resetView {
6820 [self _rightButtonClicked];
6823 - (void) resetViewAnimated:(BOOL)animated {
6824 [list_ resetViewAnimated:animated];
6827 - (void) _rightButtonClicked {
6828 if ((editing_ = !editing_))
6831 [delegate_ updateData];
6832 [book_ reloadTitleForPage:self];
6833 [book_ reloadButtonsForPage:self];
6836 - (NSString *) title {
6837 return editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS");
6840 - (NSString *) backButtonTitle {
6841 return UCLocalize("SECTIONS");
6844 - (id) rightButtonTitle {
6845 return [sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT");
6848 - (UINavigationButtonStyle) rightButtonStyle {
6849 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6852 - (UIView *) accessoryView {
6858 /* Changes View {{{ */
6859 @interface ChangesView : RVPage {
6860 _transient Database *database_;
6861 NSMutableArray *packages_;
6862 NSMutableArray *sections_;
6867 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6868 - (void) reloadData;
6872 @implementation ChangesView
6875 [list_ setDelegate:nil];
6876 [list_ setDataSource:nil];
6878 [packages_ release];
6879 [sections_ release];
6884 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6885 NSInteger count([sections_ count]);
6886 return count == 0 ? 1 : count;
6889 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6890 if ([sections_ count] == 0)
6892 return [[sections_ objectAtIndex:section] name];
6895 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6896 if ([sections_ count] == 0)
6898 return [[sections_ objectAtIndex:section] count];
6901 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6902 Section *section([sections_ objectAtIndex:[path section]]);
6903 NSInteger row([path row]);
6904 return [packages_ objectAtIndex:([section row] + row)];
6907 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6908 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
6910 cell = [[[PackageCell alloc] init] autorelease];
6911 [cell setPackage:[self packageAtIndexPath:path]];
6915 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6917 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6920 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6921 Package *package([self packageAtIndexPath:path]);
6922 PackageView *view([delegate_ packageView]);
6923 [view setDelegate:delegate_];
6924 [view setPackage:package];
6925 [book_ pushPage:view];
6929 - (void) _leftButtonClicked {
6930 [(CYBook *)book_ update];
6931 [self reloadButtons];
6934 - (void) _rightButtonClicked {
6935 [delegate_ distUpgrade];
6938 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6939 if ((self = [super initWithBook:book]) != nil) {
6940 database_ = database;
6942 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6943 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6945 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
6946 [self addSubview:list_];
6948 //XXX:[list_ setShouldHideHeaderInShortLists:NO];
6949 [list_ setDataSource:self];
6950 [list_ setDelegate:self];
6951 //[list_ setSectionListStyle:1];
6955 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6956 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6960 - (void) reloadData {
6961 NSArray *packages = [database_ packages];
6963 [packages_ removeAllObjects];
6964 [sections_ removeAllObjects];
6967 for (Package *package in packages)
6969 [package uninstalled] && [package valid] && [package visible] ||
6970 [package upgradableAndEssential:YES]
6972 [packages_ addObject:package];
6975 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6978 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6979 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6980 Section *section = nil;
6984 bool unseens = false;
6986 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6988 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6989 Package *package = [packages_ objectAtIndex:offset];
6991 BOOL uae = [package upgradableAndEssential:YES];
6997 _profile(ChangesView$reloadData$Remember)
6998 seen = [package seen];
7001 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7006 name = UCLocalize("UNKNOWN");
7008 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7012 _profile(ChangesView$reloadData$Allocate)
7013 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7014 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7015 [sections_ addObject:section];
7019 [section addToCount];
7020 } else if ([package ignored])
7021 [ignored addToCount];
7024 [upgradable addToCount];
7029 CFRelease(formatter);
7032 Section *last = [sections_ lastObject];
7033 size_t count = [last count];
7034 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7035 [sections_ removeLastObject];
7038 if ([ignored count] != 0)
7039 [sections_ insertObject:ignored atIndex:0];
7041 [sections_ insertObject:upgradable atIndex:0];
7044 [self reloadButtons];
7047 - (void) resetViewAnimated:(BOOL)animated {
7048 [list_ resetViewAnimated:animated];
7051 - (NSString *) leftButtonTitle {
7052 return [(CYBook *)book_ updating] ? nil : UCLocalize("REFRESH");
7055 - (id) rightButtonTitle {
7056 return upgrades_ == 0 ? nil : [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
7059 - (NSString *) title {
7060 return UCLocalize("CHANGES");
7065 /* Search View {{{ */
7066 @protocol SearchViewDelegate
7067 - (void) showKeyboard:(BOOL)show;
7070 @interface SearchView : RVPage {
7072 UISearchField *field_;
7073 FilteredPackageTable *table_;
7078 - (id) initWithBook:(RVBook *)book database:(Database *)database;
7079 - (void) reloadData;
7083 @implementation SearchView
7086 [field_ setDelegate:nil];
7088 [accessory_ release];
7095 - (void) _showKeyboard:(BOOL)show {
7096 CGSize keysize = [UIKeyboard defaultSize];
7097 CGRect keydown = [book_ pageBounds];
7098 CGRect keyup = keydown;
7099 keyup.size.height -= keysize.height - ButtonBarHeight_;
7101 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
7103 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
7104 [animation setSignificantRectFields:8];
7107 [animation setStartFrame:keydown];
7108 [animation setEndFrame:keyup];
7110 [animation setStartFrame:keyup];
7111 [animation setEndFrame:keydown];
7114 UIAnimator *animator = [UIAnimator sharedAnimator];
7117 addAnimations:[NSArray arrayWithObjects:animation, nil]
7118 withDuration:(KeyboardTime_ - delay)
7123 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
7125 [delegate_ showKeyboard:show];
7128 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
7129 [self _showKeyboard:YES];
7132 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
7133 [self _showKeyboard:NO];
7136 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
7138 NSString *text([field_ text]);
7139 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
7145 - (void) textFieldClearButtonPressed:(UITextField *)field {
7149 - (void) keyboardInputShouldDelete:(id)input {
7153 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
7154 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
7158 [field_ resignFirstResponder];
7163 - (id) initWithBook:(RVBook *)book database:(Database *)database {
7164 if ((self = [super initWithBook:book]) != nil) {
7165 CGRect pageBounds = [book_ pageBounds];
7167 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
7168 CGColor dimmed(space_, 0, 0, 0, 0.5);
7169 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
7171 table_ = [[FilteredPackageTable alloc]
7175 filter:@selector(isUnfilteredAndSearchedForBy:)
7179 [table_ setShouldHideHeaderInShortLists:NO];
7180 [self addSubview:table_];
7182 CGRect cnfrect = {{7, 38}, {17, 18}};
7189 area.size.width = [self bounds].size.width - area.origin.x * 2;
7190 area.size.height = [UISearchField defaultHeight];
7192 field_ = [[UISearchField alloc] initWithFrame:area];
7194 UIFont *font = [UIFont systemFontOfSize:16];
7195 [field_ setFont:font];
7197 [field_ setPlaceholder:UCLocalize("SEARCH_EX")];
7198 [field_ setDelegate:self];
7200 [field_ setPaddingTop:5];
7202 UITextInputTraits *traits([field_ textInputTraits]);
7203 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7204 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7205 [traits setReturnKeyType:UIReturnKeySearch];
7207 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
7209 accessory_ = [[UIView alloc] initWithFrame:accrect];
7210 [accessory_ addSubview:field_];
7212 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7213 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7217 - (void) resetViewAnimated:(BOOL)animated {
7218 [table_ resetViewAnimated:animated];
7221 - (void) _reloadData {
7224 - (void) reloadData {
7225 [table_ setObject:[field_ text]];
7226 _profile(SearchView$reloadData)
7227 [table_ reloadData];
7230 [table_ resetCursor];
7233 - (UIView *) accessoryView {
7237 - (NSString *) title {
7241 - (NSString *) backButtonTitle {
7242 return UCLocalize("SEARCH");
7245 - (void) setDelegate:(id)delegate {
7246 [table_ setDelegate:delegate];
7247 [super setDelegate:delegate];
7252 /* Settings View {{{ */
7253 @interface SettingsView : RVPage {
7254 _transient Database *database_;
7257 UIPreferencesTable *table_;
7258 _UISwitchSlider *subscribedSwitch_;
7259 _UISwitchSlider *ignoredSwitch_;
7260 UIPreferencesControlTableCell *subscribedCell_;
7261 UIPreferencesControlTableCell *ignoredCell_;
7264 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7268 @implementation SettingsView
7271 [table_ setDataSource:nil];
7274 if (package_ != nil)
7277 [subscribedSwitch_ release];
7278 [ignoredSwitch_ release];
7279 [subscribedCell_ release];
7280 [ignoredCell_ release];
7284 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7285 if (package_ == nil)
7291 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7292 if (package_ == nil)
7305 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7306 if (package_ == nil)
7319 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7320 if (package_ == nil)
7333 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7334 if (package_ == nil)
7337 _UISwitchSlider *slider([cell control]);
7338 BOOL value([slider value] != 0);
7339 NSMutableDictionary *metadata([package_ metadata]);
7342 if (NSNumber *number = [metadata objectForKey:key])
7343 before = [number boolValue];
7347 if (value != before) {
7348 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7350 [delegate_ updateData];
7354 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7355 [self onSomething:cell withKey:@"IsSubscribed"];
7358 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7359 [self onSomething:cell withKey:@"IsIgnored"];
7362 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7363 if (package_ == nil)
7367 case 0: switch (row) {
7369 return subscribedCell_;
7371 return ignoredCell_;
7375 case 1: switch (row) {
7377 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7378 [cell setShowSelection:NO];
7379 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7392 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7393 if ((self = [super initWithBook:book])) {
7394 database_ = database;
7395 name_ = [package retain];
7397 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7398 [self addSubview:table_];
7400 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7401 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
7403 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7404 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
7406 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7407 [subscribedCell_ setShowSelection:NO];
7408 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7409 [subscribedCell_ setControl:subscribedSwitch_];
7411 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7412 [ignoredCell_ setShowSelection:NO];
7413 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7414 [ignoredCell_ setControl:ignoredSwitch_];
7416 [table_ setDataSource:self];
7421 - (void) resetViewAnimated:(BOOL)animated {
7422 [table_ resetViewAnimated:animated];
7425 - (void) reloadData {
7426 if (package_ != nil)
7427 [package_ autorelease];
7428 package_ = [database_ packageWithName:name_];
7429 if (package_ != nil) {
7431 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7432 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7435 [table_ reloadData];
7438 - (NSString *) title {
7439 return UCLocalize("SETTINGS");
7445 /* Signature View {{{ */
7446 @interface SignatureView : CydiaBrowserView {
7447 _transient Database *database_;
7451 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7455 @implementation SignatureView
7462 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7464 [super webView:sender didClearWindowObject:window forFrame:frame];
7467 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7468 if ((self = [super initWithBook:book]) != nil) {
7469 database_ = database;
7470 package_ = [package retain];
7475 - (void) resetViewAnimated:(BOOL)animated {
7478 - (void) reloadData {
7479 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7485 @interface Cydia : UIApplication <
7486 ConfirmationViewDelegate,
7487 ProgressViewDelegate,
7496 UIToolbar *toolbar_;
7500 NSMutableArray *essential_;
7501 NSMutableArray *broken_;
7503 Database *database_;
7504 ProgressView *progress_;
7508 UIKeyboard *keyboard_;
7509 UIProgressHUD *hud_;
7511 SectionsView *sections_;
7512 ChangesView *changes_;
7513 ManageView *manage_;
7514 SearchView *search_;
7516 #if RecyclePackageViews
7517 NSMutableArray *details_;
7521 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7522 - (void) setPage:(RVPage *)page;
7526 static _finline void _setHomePage(Cydia *self) {
7527 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeView class]]];
7530 @implementation Cydia
7533 if ([broken_ count] != 0) {
7534 int count = [broken_ count];
7536 UIActionSheet *sheet = [[[UIActionSheet alloc]
7537 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7538 buttons:[NSArray arrayWithObjects:
7539 UCLocalize("FORCIBLY_CLEAR"),
7540 UCLocalize("TEMPORARY_IGNORE"),
7542 defaultButtonIndex:0
7547 [sheet setBodyText:UCLocalize("HALFINSTALLED_PACKAGE_EX")];
7548 [sheet popupAlertAnimated:YES];
7549 } else if (!Ignored_ && [essential_ count] != 0) {
7550 int count = [essential_ count];
7552 UIActionSheet *sheet = [[[UIActionSheet alloc]
7553 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7554 buttons:[NSArray arrayWithObjects:
7555 UCLocalize("UPGRADE_ESSENTIAL"),
7556 UCLocalize("COMPLETE_UPGRADE"),
7557 UCLocalize("TEMPORARY_IGNORE"),
7559 defaultButtonIndex:0
7564 [sheet setBodyText:UCLocalize("ESSENTIAL_UPGRADE_EX")];
7565 [sheet popupAlertAnimated:YES];
7569 - (void) _saveConfig {
7572 NSString *error(nil);
7573 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7575 NSError *error(nil);
7576 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7577 NSLog(@"failure to save metadata data: %@", error);
7580 NSLog(@"failure to serialize metadata: %@", error);
7588 - (void) _updateData {
7591 /* XXX: this is just stupid */
7592 if (tag_ != 2 && sections_ != nil)
7593 [sections_ reloadData];
7594 if (tag_ != 3 && changes_ != nil)
7595 [changes_ reloadData];
7596 if (tag_ != 5 && search_ != nil)
7597 [search_ reloadData];
7602 - (void) _reloadData {
7605 static bool loaded(false);
7606 UIProgressHUD *hud([self addProgressHUD]);
7607 [hud setText:(loaded ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7609 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7612 [self removeProgressHUD:hud];
7616 [essential_ removeAllObjects];
7617 [broken_ removeAllObjects];
7619 NSArray *packages([database_ packages]);
7620 for (Package *package in packages) {
7622 [broken_ addObject:package];
7623 if ([package upgradableAndEssential:NO]) {
7624 if ([package essential])
7625 [essential_ addObject:package];
7631 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7632 [toolbar_ setBadgeValue:badge forButton:3];
7633 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7634 [toolbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7635 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7636 [self setApplicationBadge:badge];
7638 [self setApplicationBadgeString:badge];
7640 [toolbar_ setBadgeValue:nil forButton:3];
7641 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7642 [toolbar_ setBadgeAnimated:NO forButton:3];
7643 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7644 [self removeApplicationBadge];
7645 else // XXX: maybe use setApplicationBadgeString also?
7646 [self setApplicationIconBadgeNumber:0];
7650 [toolbar_ setBadgeValue:nil forButton:4];
7654 if (loaded || ManualRefresh) loaded:
7659 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7660 NSTimeInterval interval([update timeIntervalSinceNow]);
7661 if (interval <= 0 && interval > -(15*60))
7669 - (void) updateData {
7670 [database_ setVisible];
7679 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
7680 _assert(file != NULL);
7682 for (NSString *key in [Sources_ allKeys]) {
7683 NSDictionary *source([Sources_ objectForKey:key]);
7685 fprintf(file, "%s %s %s\n",
7686 [[source objectForKey:@"Type"] UTF8String],
7687 [[source objectForKey:@"URI"] UTF8String],
7688 [[source objectForKey:@"Distribution"] UTF8String]
7697 detachNewThreadSelector:@selector(update_)
7700 title:UCLocalize("UPDATING_SOURCES")
7704 - (void) reloadData {
7705 @synchronized (self) {
7706 if (confirm_ == nil)
7712 pkgProblemResolver *resolver = [database_ resolver];
7714 resolver->InstallProtect();
7715 if (!resolver->Resolve(true))
7719 - (void) popUpBook:(RVBook *)book {
7720 [underlay_ popSubview:book];
7723 - (CGRect) popUpBounds {
7724 return [underlay_ bounds];
7728 if (![database_ prepare])
7731 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7732 [confirm_ setDelegate:self];
7734 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7735 [page setDelegate:self];
7737 [confirm_ setPage:page];
7738 [self popUpBook:confirm_];
7744 @synchronized (self) {
7749 - (void) clearPackage:(Package *)package {
7750 @synchronized (self) {
7757 - (void) installPackage:(Package *)package {
7758 @synchronized (self) {
7765 - (void) removePackage:(Package *)package {
7766 @synchronized (self) {
7773 - (void) distUpgrade {
7774 @synchronized (self) {
7775 if (![database_ upgrade])
7782 [self slideUp:[[[UIActionSheet alloc]
7784 buttons:[NSArray arrayWithObjects:UCLocalize("CONTINUE_QUEUING"), UCLocalize("CANCEL_CLEAR"), nil]
7785 defaultButtonIndex:1
7792 @synchronized (self) {
7795 if (confirm_ != nil) {
7803 [overlay_ removeFromSuperview];
7807 detachNewThreadSelector:@selector(perform)
7810 title:UCLocalize("RUNNING")
7814 - (void) progressViewIsComplete:(ProgressView *)progress {
7815 if (confirm_ != nil) {
7816 [underlay_ addSubview:overlay_];
7817 [confirm_ popFromSuperviewAnimated:NO];
7823 - (void) setPage:(RVPage *)page {
7824 [page resetViewAnimated:NO];
7825 [page setDelegate:self];
7826 [book_ setPage:page];
7829 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7830 CydiaBrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7831 [browser loadURL:url];
7835 - (SectionsView *) sectionsView {
7836 if (sections_ == nil)
7837 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7841 - (void) buttonBarItemTapped:(id)sender {
7842 unsigned tag = [sender tag];
7844 [book_ resetViewAnimated:YES];
7846 } else if (tag_ == 2)
7847 [[self sectionsView] resetView];
7850 case 1: _setHomePage(self); break;
7852 case 2: [self setPage:[self sectionsView]]; break;
7853 case 3: [self setPage:changes_]; break;
7854 case 4: [self setPage:manage_]; break;
7855 case 5: [self setPage:search_]; break;
7863 - (void) askForSettings {
7864 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
7866 CYActionSheet *role([[[CYActionSheet alloc]
7867 initWithTitle:UCLocalize("WHO_ARE_YOU")
7868 buttons:[NSArray arrayWithObjects:
7869 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
7870 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
7871 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
7873 defaultButtonIndex:-1
7876 [role setBodyText:UCLocalize("ROLE_EX")];
7878 int button([role yieldToPopupAlertAnimated:YES]);
7881 case 1: Role_ = @"User"; break;
7882 case 2: Role_ = @"Hacker"; break;
7883 case 3: Role_ = @"Developer"; break;
7888 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7892 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7899 - (void) setPackageView:(PackageView *)view {
7901 [view setPackage:nil];
7902 #if RecyclePackageViews
7903 if ([details_ count] < 3)
7904 [details_ addObject:view];
7909 - (PackageView *) _packageView {
7910 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7913 - (PackageView *) packageView {
7914 #if RecyclePackageViews
7916 size_t count([details_ count]);
7919 view = [self _packageView];
7921 [details_ addObject:[self _packageView]];
7923 view = [[[details_ lastObject] retain] autorelease];
7924 [details_ removeLastObject];
7931 return [self _packageView];
7935 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7936 NSString *context([sheet context]);
7938 if ([context isEqualToString:@"missing"])
7940 else if ([context isEqualToString:@"cancel"]) {
7957 @synchronized (self) {
7962 [toolbar_ setBadgeValue:UCLocalize("Q_D") forButton:4];
7966 if (confirm_ != nil) {
7971 } else if ([context isEqualToString:@"fixhalf"]) {
7974 @synchronized (self) {
7975 for (Package *broken in broken_) {
7978 NSString *id = [broken id];
7979 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7980 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7981 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7982 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7991 [broken_ removeAllObjects];
7999 } else if ([context isEqualToString:@"upgrade"]) {
8002 @synchronized (self) {
8003 for (Package *essential in essential_)
8004 [essential install];
8026 - (void) system:(NSString *)command { _pooled
8027 system([command UTF8String]);
8030 - (void) applicationWillSuspend {
8032 [super applicationWillSuspend];
8035 - (void) applicationSuspend:(__GSEvent *)event {
8036 if (hud_ == nil && ![progress_ isRunning])
8037 [super applicationSuspend:event];
8040 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8042 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8045 - (void) _setSuspended:(BOOL)value {
8047 [super _setSuspended:value];
8050 - (UIProgressHUD *) addProgressHUD {
8051 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8052 [window_ setUserInteractionEnabled:NO];
8054 [progress_ addSubview:hud];
8058 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8060 [hud removeFromSuperview];
8061 [window_ setUserInteractionEnabled:YES];
8064 - (RVPage *) pageForPackage:(NSString *)name {
8065 if (Package *package = [database_ packageWithName:name]) {
8066 PackageView *view([self packageView]);
8067 [view setPackage:package];
8070 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8071 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8072 return [self _pageForURL:url withClass:[CydiaBrowserView class]];
8076 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8080 NSString *href([url absoluteString]);
8081 if ([href hasPrefix:@"apptapp://package/"])
8082 return [self pageForPackage:[href substringFromIndex:18]];
8084 NSString *scheme([[url scheme] lowercaseString]);
8085 if (![scheme isEqualToString:@"cydia"])
8087 NSString *path([url absoluteString]);
8088 if ([path length] < 8)
8090 path = [path substringFromIndex:8];
8091 if (![path hasPrefix:@"/"])
8092 path = [@"/" stringByAppendingString:path];
8094 if ([path isEqualToString:@"/add-source"])
8095 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8096 else if ([path isEqualToString:@"/storage"])
8097 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CydiaBrowserView class]];
8098 else if ([path isEqualToString:@"/sources"])
8099 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8100 else if ([path isEqualToString:@"/packages"])
8101 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8102 else if ([path hasPrefix:@"/url/"])
8103 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CydiaBrowserView class]];
8104 else if ([path hasPrefix:@"/launch/"])
8105 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8106 else if ([path hasPrefix:@"/package-settings/"])
8107 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8108 else if ([path hasPrefix:@"/package-signature/"])
8109 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8110 else if ([path hasPrefix:@"/package/"])
8111 return [self pageForPackage:[path substringFromIndex:9]];
8112 else if ([path hasPrefix:@"/files/"]) {
8113 NSString *name = [path substringFromIndex:7];
8115 if (Package *package = [database_ packageWithName:name]) {
8116 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8117 [files setPackage:package];
8125 - (void) applicationOpenURL:(NSURL *)url {
8126 [super applicationOpenURL:url];
8128 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8129 [self setPage:page];
8130 [toolbar_ showSelectionForButton:tag];
8135 - (void) applicationDidFinishLaunching:(id)unused {
8136 [BrowserView _initialize];
8138 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8140 Font12_ = [[UIFont systemFontOfSize:12] retain];
8141 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8142 Font14_ = [[UIFont systemFontOfSize:14] retain];
8143 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8144 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8148 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8149 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8151 window_ = [[UIWindow alloc] initWithContentRect:[UIHardware fullScreenApplicationContentRect]];
8152 [window_ orderFront:self];
8153 [window_ makeKey:self];
8154 [window_ setHidden:NO];
8156 database_ = [Database sharedInstance];
8158 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8159 [database_ setDelegate:progress_];
8160 [window_ setContentView:progress_];
8162 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8163 [progress_ setContentView:underlay_];
8165 [progress_ resetView];
8168 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8169 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8170 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8171 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8172 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8173 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8174 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8175 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8176 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8179 [self setIdleTimerDisabled:YES];
8181 hud_ = [self addProgressHUD];
8182 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8183 [self setStatusBarShowsProgress:YES];
8185 [self yieldToSelector:@selector(system) withObject:@"http://www.hipsterwave.com/tag/cydia/"];
8187 [self setStatusBarShowsProgress:NO];
8188 [self removeProgressHUD:hud_];
8191 if (ExecFork() == 0) {
8192 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8193 perror("launchctl stop");
8200 [self askForSettings];
8203 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
8205 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8206 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
8207 0, 0, screenrect.size.width, screenrect.size.height - 48
8208 ) database:database_];
8210 [book_ setDelegate:self];
8212 [overlay_ addSubview:book_];
8214 NSArray *buttonitems = [NSArray arrayWithObjects:
8215 [NSDictionary dictionaryWithObjectsAndKeys:
8216 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8217 @"home-up.png", kUIButtonBarButtonInfo,
8218 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
8219 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
8220 self, kUIButtonBarButtonTarget,
8221 @"Cydia", kUIButtonBarButtonTitle,
8222 @"0", kUIButtonBarButtonType,
8225 [NSDictionary dictionaryWithObjectsAndKeys:
8226 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8227 @"install-up.png", kUIButtonBarButtonInfo,
8228 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
8229 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
8230 self, kUIButtonBarButtonTarget,
8231 UCLocalize("SECTIONS"), kUIButtonBarButtonTitle,
8232 @"0", kUIButtonBarButtonType,
8235 [NSDictionary dictionaryWithObjectsAndKeys:
8236 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8237 @"changes-up.png", kUIButtonBarButtonInfo,
8238 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
8239 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
8240 self, kUIButtonBarButtonTarget,
8241 UCLocalize("CHANGES"), kUIButtonBarButtonTitle,
8242 @"0", kUIButtonBarButtonType,
8245 [NSDictionary dictionaryWithObjectsAndKeys:
8246 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8247 @"manage-up.png", kUIButtonBarButtonInfo,
8248 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
8249 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
8250 self, kUIButtonBarButtonTarget,
8251 UCLocalize("MANAGE"), kUIButtonBarButtonTitle,
8252 @"0", kUIButtonBarButtonType,
8255 [NSDictionary dictionaryWithObjectsAndKeys:
8256 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8257 @"search-up.png", kUIButtonBarButtonInfo,
8258 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
8259 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
8260 self, kUIButtonBarButtonTarget,
8261 UCLocalize("SEARCH"), kUIButtonBarButtonTitle,
8262 @"0", kUIButtonBarButtonType,
8266 toolbar_ = [[UIToolbar alloc]
8268 withFrame:CGRectMake(
8269 0, screenrect.size.height - ButtonBarHeight_,
8270 screenrect.size.width, ButtonBarHeight_
8272 withItemList:buttonitems
8275 [toolbar_ setDelegate:self];
8276 [toolbar_ setBarStyle:1];
8277 [toolbar_ setButtonBarTrackingMode:2];
8279 int buttons[5] = {1, 2, 3, 4, 5};
8280 [toolbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
8281 [toolbar_ showButtonGroup:0 withDuration:0];
8283 for (int i = 0; i != 5; ++i)
8284 [[toolbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
8285 i * 64 + 2, 1, 60, ButtonBarHeight_
8288 [toolbar_ showSelectionForButton:1];
8289 [overlay_ addSubview:toolbar_];
8291 [UIKeyboard initImplementationNow];
8292 CGSize keysize = [UIKeyboard defaultSize];
8293 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
8294 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
8295 [overlay_ addSubview:keyboard_];
8297 [underlay_ addSubview:overlay_];
8301 [self sectionsView];
8302 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
8303 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
8305 manage_ = (ManageView *) [[self
8306 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8307 withClass:[ManageView class]
8310 #if RecyclePackageViews
8311 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8312 [details_ addObject:[self _packageView]];
8313 [details_ addObject:[self _packageView]];
8321 - (void) showKeyboard:(BOOL)show {
8322 CGSize keysize([UIKeyboard defaultSize]);
8323 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8324 CGRect keyup(keydown);
8325 keyup.origin.y -= keysize.height;
8327 UIFrameAnimation *animation([[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease]);
8328 [animation setSignificantRectFields:2];
8331 [animation setStartFrame:keydown];
8332 [animation setEndFrame:keyup];
8333 [keyboard_ activate];
8335 [animation setStartFrame:keyup];
8336 [animation setEndFrame:keydown];
8337 [keyboard_ deactivate];
8340 [[UIAnimator sharedAnimator]
8341 addAnimations:[NSArray arrayWithObjects:animation, nil]
8342 withDuration:KeyboardTime_
8347 - (void) slideUp:(UIActionSheet *)alert {
8348 [alert presentSheetInView:overlay_];
8354 id Alloc_(id self, SEL selector) {
8355 id object = alloc_(self, selector);
8356 lprintf("[%s]A-%p\n", self->isa->name, object);
8361 id Dealloc_(id self, SEL selector) {
8362 id object = dealloc_(self, selector);
8363 lprintf("[%s]D-%p\n", self->isa->name, object);
8367 Class $WebDefaultUIKitDelegate;
8369 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8370 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8371 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8372 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8375 int main(int argc, char *argv[]) { _pooled
8378 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8380 /* Library Hacks {{{ */
8381 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8383 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8384 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8385 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8386 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8387 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8390 /* Set Locale {{{ */
8391 Locale_ = CFLocaleCopyCurrent();
8392 Languages_ = [NSLocale preferredLanguages];
8393 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8394 //NSLog(@"%@", [Languages_ description]);
8396 if (Languages_ == nil || [Languages_ count] == 0)
8399 lang = [[Languages_ objectAtIndex:0] UTF8String];
8400 setenv("LANG", lang, true);
8401 //std::setlocale(LC_ALL, lang);
8402 NSLog(@"Setting Language: %s", lang);
8405 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8407 /* Parse Arguments {{{ */
8408 bool substrate(false);
8414 for (int argi(1); argi != argc; ++argi)
8415 if (strcmp(argv[argi], "--") == 0) {
8417 argv[argi] = argv[0];
8423 for (int argi(1); argi != arge; ++argi)
8424 if (strcmp(args[argi], "--substrate") == 0)
8427 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8431 App_ = [[NSBundle mainBundle] bundlePath];
8432 Home_ = NSHomeDirectory();
8438 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8439 alloc_ = alloc->method_imp;
8440 alloc->method_imp = (IMP) &Alloc_;*/
8442 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8443 dealloc_ = dealloc->method_imp;
8444 dealloc->method_imp = (IMP) &Dealloc_;*/
8446 /* System Information {{{ */
8450 size = sizeof(maxproc);
8451 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8452 perror("sysctlbyname(\"kern.maxproc\", ?)");
8453 else if (maxproc < 64) {
8455 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8456 perror("sysctlbyname(\"kern.maxproc\", #)");
8459 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8460 char *osversion = new char[size];
8461 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8462 perror("sysctlbyname(\"kern.osversion\", ?)");
8464 System_ = [NSString stringWithUTF8String:osversion];
8466 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8467 char *machine = new char[size];
8468 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8469 perror("sysctlbyname(\"hw.machine\", ?)");
8473 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8474 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8475 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8476 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8480 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8481 NSData *data((NSData *) ecid);
8482 size_t length([data length]);
8483 uint8_t bytes[length];
8484 [data getBytes:bytes];
8485 char string[length * 2 + 1];
8486 for (size_t i(0); i != length; ++i)
8487 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8488 ChipID_ = [NSString stringWithUTF8String:string];
8492 IOObjectRelease(service);
8496 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8498 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8499 Build_ = [system objectForKey:@"ProductBuildVersion"];
8500 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8501 Product_ = [info objectForKey:@"SafariProductVersion"];
8502 Safari_ = [info objectForKey:@"CFBundleVersion"];
8505 /* Load Database {{{ */
8507 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8509 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8512 if (Metadata_ == NULL)
8513 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8515 Settings_ = [Metadata_ objectForKey:@"Settings"];
8517 Packages_ = [Metadata_ objectForKey:@"Packages"];
8518 Sections_ = [Metadata_ objectForKey:@"Sections"];
8519 Sources_ = [Metadata_ objectForKey:@"Sources"];
8522 if (Settings_ != nil)
8523 Role_ = [Settings_ objectForKey:@"Role"];
8525 if (Packages_ == nil) {
8526 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8527 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8530 if (Sections_ == nil) {
8531 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8532 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8535 if (Sources_ == nil) {
8536 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8537 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8542 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8545 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8547 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8548 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8549 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8550 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8552 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8553 unlink("/tmp/.cydia.fw");
8555 } else if (access("/User", F_OK) != 0) {
8558 system("/usr/libexec/cydia/firmware.sh");
8562 _assert([[NSFileManager defaultManager]
8563 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8564 withIntermediateDirectories:YES
8569 if (access("/tmp/cydia.chk", F_OK) == 0) {
8570 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8571 _assert(errno == ENOENT);
8572 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8573 _assert(errno == ENOENT);
8576 /* APT Initialization {{{ */
8577 _assert(pkgInitConfig(*_config));
8578 _assert(pkgInitSystem(*_config, _system));
8581 _config->Set("APT::Acquire::Translation", lang);
8582 _config->Set("Acquire::http::Timeout", 15);
8583 _config->Set("Acquire::http::MaxParallel", 3);
8585 /* Color Choices {{{ */
8586 space_ = CGColorSpaceCreateDeviceRGB();
8588 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8589 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8590 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8591 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8592 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8593 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8594 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8595 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8596 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8598 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8599 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8601 /* UIKit Configuration {{{ */
8602 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8603 if ($GSFontSetUseLegacyFontMetrics != NULL)
8604 $GSFontSetUseLegacyFontMetrics(YES);
8606 UIKeyboardDisableAutomaticAppearance();
8609 Colon_ = UCLocalize("COLON_DELIMITED");
8610 Error_ = UCLocalize("ERROR");
8611 Warning_ = UCLocalize("WARNING");
8614 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8616 CGColorSpaceRelease(space_);