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];
1625 authority_ = [host_ retain];
1627 authority_ = [url path];
1630 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1631 if ((self = [super init]) != nil) {
1632 [self setMetaIndex:index inPool:pool];
1636 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1637 NSDictionary *lhr = [self record];
1638 NSDictionary *rhr = [source record];
1641 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1643 NSString *lhs = [self name];
1644 NSString *rhs = [source name];
1646 if ([lhs length] != 0 && [rhs length] != 0) {
1647 unichar lhc = [lhs characterAtIndex:0];
1648 unichar rhc = [rhs characterAtIndex:0];
1650 if (isalpha(lhc) && !isalpha(rhc))
1651 return NSOrderedAscending;
1652 else if (!isalpha(lhc) && isalpha(rhc))
1653 return NSOrderedDescending;
1656 return [lhs compare:rhs options:LaxCompareOptions_];
1659 - (NSString *) depictionForPackage:(NSString *)package {
1660 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1663 - (NSString *) supportForPackage:(NSString *)package {
1664 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1667 - (NSDictionary *) record {
1675 - (NSString *) uri {
1679 - (NSString *) distribution {
1680 return distribution_;
1683 - (NSString *) type {
1687 - (NSString *) key {
1688 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1691 - (NSString *) host {
1695 - (NSString *) name {
1696 return origin_.empty() ? authority_ : origin_;
1699 - (NSString *) description {
1700 return description_;
1703 - (NSString *) label {
1704 return label_.empty() ? authority_ : label_;
1707 - (NSString *) origin {
1711 - (NSString *) version {
1715 - (NSString *) defaultIcon {
1716 return defaultIcon_;
1721 /* Relationship Class {{{ */
1722 @interface Relationship : NSObject {
1727 - (NSString *) type;
1729 - (NSString *) name;
1733 @implementation Relationship
1741 - (NSString *) type {
1749 - (NSString *) name {
1756 /* Package Class {{{ */
1757 @interface Package : NSObject {
1761 pkgCache::VerIterator version_;
1762 pkgCache::PkgIterator iterator_;
1763 _transient Database *database_;
1764 pkgCache::VerFileIterator file_;
1771 NSString *section$_;
1777 CYString installed_;
1783 CYString depiction_;
1794 NSMutableArray *tags_;
1797 NSArray *relationships_;
1799 NSMutableDictionary *metadata_;
1800 _transient NSDate *firstSeen_;
1801 _transient NSDate *lastSeen_;
1805 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1806 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1808 - (pkgCache::PkgIterator) iterator;
1811 - (NSString *) section;
1812 - (NSString *) simpleSection;
1814 - (NSString *) longSection;
1815 - (NSString *) shortSection;
1819 - (Address *) maintainer;
1821 - (NSString *) longDescription;
1822 - (NSString *) shortDescription;
1825 - (NSMutableDictionary *) metadata;
1827 - (BOOL) subscribed;
1830 - (NSString *) latest;
1831 - (NSString *) installed;
1832 - (BOOL) uninstalled;
1835 - (BOOL) upgradableAndEssential:(BOOL)essential;
1838 - (BOOL) unfiltered;
1842 - (BOOL) halfConfigured;
1843 - (BOOL) halfInstalled;
1845 - (NSString *) mode;
1847 - (void) setVisible;
1850 - (NSString *) name;
1852 - (NSString *) homepage;
1853 - (NSString *) depiction;
1854 - (Address *) author;
1856 - (NSString *) support;
1858 - (NSArray *) files;
1859 - (NSArray *) relationships;
1860 - (NSArray *) warnings;
1861 - (NSArray *) applications;
1863 - (Source *) source;
1864 - (NSString *) role;
1866 - (BOOL) matches:(NSString *)text;
1868 - (bool) hasSupportingRole;
1869 - (BOOL) hasTag:(NSString *)tag;
1870 - (NSString *) primaryPurpose;
1871 - (NSArray *) purposes;
1872 - (bool) isCommercial;
1874 - (CYString &) cyname;
1876 - (uint32_t) compareBySection:(NSArray *)sections;
1878 - (uint32_t) compareForChanges;
1883 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1884 - (bool) isInstalledAndVisible:(NSNumber *)number;
1885 - (bool) isVisibleInSection:(NSString *)section;
1886 - (bool) isVisibleInSource:(Source *)source;
1890 uint32_t PackageChangesRadix(Package *self, void *) {
1895 uint32_t timestamp : 30;
1896 uint32_t ignored : 1;
1897 uint32_t upgradable : 1;
1901 bool upgradable([self upgradableAndEssential:YES]);
1902 value.bits.upgradable = upgradable ? 1 : 0;
1905 value.bits.timestamp = 0;
1906 value.bits.ignored = [self ignored] ? 0 : 1;
1907 value.bits.upgradable = 1;
1909 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1910 value.bits.ignored = 0;
1911 value.bits.upgradable = 0;
1914 return _not(uint32_t) - value.key;
1917 _finline static void Stifle(uint8_t &value) {
1920 uint32_t PackagePrefixRadix(Package *self, void *context) {
1921 size_t offset(reinterpret_cast<size_t>(context));
1922 CYString &name([self cyname]);
1924 size_t size(name.size());
1927 char *text(name.data());
1930 if (!isdigit(text[0]))
1934 while (size != digits && isdigit(text[digits]))
1944 if (offset == 0 && zeros != 0) {
1945 memset(data, '0', zeros);
1946 memcpy(data + zeros, text, 4 - zeros);
1948 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1949 if (size <= offset - zeros)
1952 text += offset - zeros;
1953 size -= offset - zeros;
1956 memcpy(data, text, 4);
1958 memcpy(data, text, size);
1959 memset(data + size, 0, 4 - size);
1962 for (size_t i(0); i != 4; ++i)
1963 if (isalpha(data[i]))
1968 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1970 /* XXX: ntohl may be more honest */
1971 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1974 CYString &(*PackageName)(Package *self, SEL sel);
1976 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1977 _profile(PackageNameCompare)
1978 CYString &lhi(PackageName(lhs, @selector(cyname)));
1979 CYString &rhi(PackageName(rhs, @selector(cyname)));
1980 CFStringRef lhn(lhi), rhn(rhi);
1982 _profile(PackageNameCompare$NumbersLast)
1983 if (!lhi.empty() && !rhi.empty()) {
1984 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1985 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1986 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1987 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1988 return lha ? NSOrderedAscending : NSOrderedDescending;
1992 CFIndex length = CFStringGetLength(lhn);
1994 _profile(PackageNameCompare$Compare)
1995 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2000 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2001 return PackageNameCompare(*lhs, *rhs, context);
2004 struct PackageNameOrdering :
2005 std::binary_function<Package *, Package *, bool>
2007 _finline bool operator ()(Package *lhs, Package *rhs) const {
2008 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2012 @implementation Package
2014 - (NSString *) description {
2015 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2021 if (section$_ != nil)
2022 [section$_ release];
2027 if (sponsor$_ != nil)
2028 [sponsor$_ release];
2029 if (author$_ != nil)
2036 if (relationships_ != nil)
2037 [relationships_ release];
2038 if (metadata_ != nil)
2039 [metadata_ release];
2044 + (NSString *) webScriptNameForSelector:(SEL)selector {
2045 if (selector == @selector(hasTag:))
2051 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2052 return [self webScriptNameForSelector:selector] == nil;
2055 + (NSArray *) _attributeKeys {
2056 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];
2059 - (NSArray *) attributeKeys {
2060 return [[self class] _attributeKeys];
2063 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2064 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2074 _profile(Package$parse)
2075 pkgRecords::Parser *parser;
2077 _profile(Package$parse$Lookup)
2078 parser = &[database_ records]->Lookup(file_);
2083 _profile(Package$parse$Find)
2089 {"depiction", &depiction_},
2090 {"homepage", &homepage_},
2091 {"website", &website},
2093 {"support", &support_},
2094 {"sponsor", &sponsor_},
2095 {"author", &author_},
2098 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2099 const char *start, *end;
2101 if (parser->Find(names[i].name_, start, end)) {
2102 CYString &value(*names[i].value_);
2103 _profile(Package$parse$Value)
2104 value.set(pool_, start, end - start);
2110 _profile(Package$parse$Tagline)
2111 const char *start, *end;
2112 if (parser->ShortDesc(start, end)) {
2113 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2116 while (stop != start && stop[-1] == '\r')
2118 tagline_.set(pool_, start, stop - start);
2122 _profile(Package$parse$Retain)
2123 if (homepage_.empty())
2124 homepage_ = website;
2125 if (homepage_ == depiction_)
2131 - (void) setVisible {
2132 visible_ = required_ && [self hasSupportingRole] && [self unfiltered];
2135 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2136 if ((self = [super init]) != nil) {
2137 _profile(Package$initWithVersion)
2138 @synchronized (database) {
2139 era_ = [database era];
2143 iterator_ = version.ParentPkg();
2144 database_ = database;
2146 _profile(Package$initWithVersion$Latest)
2147 latest_ = (NSString *) StripVersion(version_.VerStr());
2150 pkgCache::VerIterator current;
2151 _profile(Package$initWithVersion$Versions)
2152 current = iterator_.CurrentVer();
2154 installed_.set(pool_, StripVersion_(current.VerStr()));
2156 if (!version_.end())
2157 file_ = version_.FileList();
2159 pkgCache &cache([database_ cache]);
2160 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2164 _profile(Package$initWithVersion$Name)
2165 id_.set(pool_, iterator_.Name());
2166 name_.set(pool, iterator_.Display());
2170 _profile(Package$initWithVersion$Source)
2171 source_ = [database_ getSource:file_.File()];
2180 _profile(Package$initWithVersion$Tags)
2181 pkgCache::TagIterator tag(iterator_.TagList());
2183 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2185 const char *name(tag.Name());
2186 [tags_ addObject:(NSString *)CFCString(name)];
2187 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2188 role_ = (NSString *) CFCString(name + 6);
2189 if (required_ && strncmp(name, "require::", 9) == 0 && (
2194 } while (!tag.end());
2198 bool changed(false);
2199 NSString *key([id_ lowercaseString]);
2201 _profile(Package$initWithVersion$Metadata)
2202 metadata_ = [Packages_ objectForKey:key];
2204 if (metadata_ == nil) {
2207 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2208 firstSeen_, @"FirstSeen",
2209 latest_, @"LastVersion",
2214 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2215 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2217 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2218 subscribed_ = [subscribed boolValue];
2220 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2222 if (firstSeen_ == nil) {
2223 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2224 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2228 if (version == nil) {
2229 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2232 if (![version isEqualToString:latest_]) {
2233 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2235 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2240 metadata_ = [metadata_ retain];
2243 [Packages_ setObject:metadata_ forKey:key];
2248 _profile(Package$initWithVersion$Section)
2249 section_.set(pool_, iterator_.Section());
2252 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2254 } _end } return self;
2257 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2258 @synchronized ([Database class]) {
2259 pkgCache::VerIterator version;
2261 _profile(Package$packageWithIterator$GetCandidateVer)
2262 version = [database policy]->GetCandidateVer(iterator);
2268 return [[[Package alloc]
2269 initWithVersion:version
2276 - (pkgCache::PkgIterator) iterator {
2280 - (NSString *) section {
2281 if (section$_ == nil) {
2282 if (section_.empty())
2285 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2286 NSString *name(section_);
2289 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2290 if (NSString *rename = [value objectForKey:@"Rename"]) {
2295 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2299 - (NSString *) simpleSection {
2300 if (NSString *section = [self section])
2301 return Simplify(section);
2306 - (NSString *) longSection {
2307 return LocalizeSection([self section]);
2310 - (NSString *) shortSection {
2311 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2314 - (NSString *) uri {
2317 pkgIndexFile *index;
2318 pkgCache::PkgFileIterator file(file_.File());
2319 if (![database_ list].FindIndex(file, index))
2321 return [NSString stringWithUTF8String:iterator_->Path];
2322 //return [NSString stringWithUTF8String:file.Site()];
2323 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2327 - (Address *) maintainer {
2330 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2331 const std::string &maintainer(parser->Maintainer());
2332 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2336 return version_.end() ? 0 : version_->InstalledSize;
2339 - (NSString *) longDescription {
2342 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2343 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2345 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2346 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2347 if ([lines count] < 2)
2350 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2351 for (size_t i(1), e([lines count]); i != e; ++i) {
2352 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2353 [trimmed addObject:trim];
2356 return [trimmed componentsJoinedByString:@"\n"];
2359 - (NSString *) shortDescription {
2364 _profile(Package$index)
2365 CFStringRef name((CFStringRef) [self name]);
2366 if (CFStringGetLength(name) == 0)
2368 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2369 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2371 return toupper(character);
2375 - (NSMutableDictionary *) metadata {
2380 if (subscribed_ && lastSeen_ != nil)
2385 - (BOOL) subscribed {
2390 NSDictionary *metadata([self metadata]);
2391 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2392 return [ignored boolValue];
2397 - (NSString *) latest {
2401 - (NSString *) installed {
2405 - (BOOL) uninstalled {
2406 return installed_.empty();
2410 return !version_.end();
2413 - (BOOL) upgradableAndEssential:(BOOL)essential {
2414 _profile(Package$upgradableAndEssential)
2415 pkgCache::VerIterator current(iterator_.CurrentVer());
2417 return essential && essential_ && visible_;
2419 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2423 - (BOOL) essential {
2428 return [database_ cache][iterator_].InstBroken();
2431 - (BOOL) unfiltered {
2432 NSString *section([self section]);
2433 return section == nil || isSectionVisible(section);
2441 unsigned char current(iterator_->CurrentState);
2442 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2445 - (BOOL) halfConfigured {
2446 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2449 - (BOOL) halfInstalled {
2450 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2454 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2455 return state.Mode != pkgDepCache::ModeKeep;
2458 - (NSString *) mode {
2459 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2461 switch (state.Mode) {
2462 case pkgDepCache::ModeDelete:
2463 if ((state.iFlags & pkgDepCache::Purge) != 0)
2467 case pkgDepCache::ModeKeep:
2468 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2469 return @"REINSTALL";
2470 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2474 case pkgDepCache::ModeInstall:
2475 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2476 return @"REINSTALL";
2477 else*/ switch (state.Status) {
2479 return @"DOWNGRADE";
2485 return @"NEW_INSTALL";
2496 - (NSString *) name {
2497 return name_.empty() ? id_ : name_;
2500 - (UIImage *) icon {
2501 NSString *section = [self simpleSection];
2505 if ([icon_ hasPrefix:@"file:///"])
2506 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2507 if (icon == nil) if (section != nil)
2508 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2509 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2510 if ([dicon hasPrefix:@"file:///"])
2511 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2513 icon = [UIImage applicationImageNamed:@"unknown.png"];
2517 - (NSString *) homepage {
2521 - (NSString *) depiction {
2522 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2525 - (Address *) sponsor {
2526 if (sponsor$_ == nil) {
2527 if (sponsor_.empty())
2529 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2533 - (Address *) author {
2534 if (author$_ == nil) {
2535 if (author_.empty())
2537 author$_ = [[Address addressWithString:author_] retain];
2541 - (NSString *) support {
2542 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2545 - (NSArray *) files {
2546 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2547 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2550 fin.open([path UTF8String]);
2555 while (std::getline(fin, line))
2556 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2561 - (NSArray *) relationships {
2562 return relationships_;
2565 - (NSArray *) warnings {
2566 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2567 const char *name(iterator_.Name());
2569 size_t length(strlen(name));
2570 if (length < 2) invalid:
2571 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2572 else for (size_t i(0); i != length; ++i)
2574 /* XXX: technically this is not allowed */
2575 (name[i] < 'A' || name[i] > 'Z') &&
2576 (name[i] < 'a' || name[i] > 'z') &&
2577 (name[i] < '0' || name[i] > '9') &&
2578 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2581 if (strcmp(name, "cydia") != 0) {
2584 bool _private = false;
2587 bool repository = [[self section] isEqualToString:@"Repositories"];
2589 if (NSArray *files = [self files])
2590 for (NSString *file in files)
2591 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2593 else if (!user && [file isEqualToString:@"/User"])
2595 else if (!_private && [file isEqualToString:@"/private"])
2597 else if (!stash && [file isEqualToString:@"/var/stash"])
2600 /* XXX: this is not sensitive enough. only some folders are valid. */
2601 if (cydia && !repository)
2602 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2604 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2606 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2608 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2611 return [warnings count] == 0 ? nil : warnings;
2614 - (NSArray *) applications {
2615 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2617 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2619 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2620 if (NSArray *files = [self files])
2621 for (NSString *file in files)
2622 if (application_r(file)) {
2623 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2624 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2625 if ([id isEqualToString:me])
2628 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2630 display = application_r[1];
2632 NSString *bundle([file stringByDeletingLastPathComponent]);
2633 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2634 if (icon == nil || [icon length] == 0)
2636 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2638 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2639 [applications addObject:application];
2641 [application addObject:id];
2642 [application addObject:display];
2643 [application addObject:url];
2646 return [applications count] == 0 ? nil : applications;
2649 - (Source *) source {
2651 @synchronized (database_) {
2652 if ([database_ era] != era_ || file_.end())
2655 source_ = [database_ getSource:file_.File()];
2667 - (NSString *) role {
2671 - (BOOL) matches:(NSString *)text {
2677 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2678 if (range.location != NSNotFound)
2681 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2682 if (range.location != NSNotFound)
2685 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2686 if (range.location != NSNotFound)
2692 - (bool) hasSupportingRole {
2695 if ([role_ isEqualToString:@"enduser"])
2697 if ([Role_ isEqualToString:@"User"])
2699 if ([role_ isEqualToString:@"hacker"])
2701 if ([Role_ isEqualToString:@"Hacker"])
2703 if ([role_ isEqualToString:@"developer"])
2705 if ([Role_ isEqualToString:@"Developer"])
2710 - (BOOL) hasTag:(NSString *)tag {
2711 return tags_ == nil ? NO : [tags_ containsObject:tag];
2714 - (NSString *) primaryPurpose {
2715 for (NSString *tag in tags_)
2716 if ([tag hasPrefix:@"purpose::"])
2717 return [tag substringFromIndex:9];
2721 - (NSArray *) purposes {
2722 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2723 for (NSString *tag in tags_)
2724 if ([tag hasPrefix:@"purpose::"])
2725 [purposes addObject:[tag substringFromIndex:9]];
2726 return [purposes count] == 0 ? nil : purposes;
2729 - (bool) isCommercial {
2730 return [self hasTag:@"cydia::commercial"];
2733 - (CYString &) cyname {
2734 return name_.empty() ? id_ : name_;
2737 - (uint32_t) compareBySection:(NSArray *)sections {
2738 NSString *section([self section]);
2739 for (size_t i(0), e([sections count]); i != e; ++i) {
2740 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2744 return _not(uint32_t);
2747 - (uint32_t) compareForChanges {
2752 uint32_t timestamp : 30;
2753 uint32_t ignored : 1;
2754 uint32_t upgradable : 1;
2758 bool upgradable([self upgradableAndEssential:YES]);
2759 value.bits.upgradable = upgradable ? 1 : 0;
2762 value.bits.timestamp = 0;
2763 value.bits.ignored = [self ignored] ? 0 : 1;
2764 value.bits.upgradable = 1;
2766 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2767 value.bits.ignored = 0;
2768 value.bits.upgradable = 0;
2771 return _not(uint32_t) - value.key;
2775 pkgProblemResolver *resolver = [database_ resolver];
2776 resolver->Clear(iterator_);
2777 resolver->Protect(iterator_);
2781 pkgProblemResolver *resolver = [database_ resolver];
2782 resolver->Clear(iterator_);
2783 resolver->Protect(iterator_);
2784 pkgCacheFile &cache([database_ cache]);
2785 cache->MarkInstall(iterator_, false);
2786 pkgDepCache::StateCache &state((*cache)[iterator_]);
2787 if (!state.Install())
2788 cache->SetReInstall(iterator_, true);
2792 pkgProblemResolver *resolver = [database_ resolver];
2793 resolver->Clear(iterator_);
2794 resolver->Protect(iterator_);
2795 resolver->Remove(iterator_);
2796 [database_ cache]->MarkDelete(iterator_, true);
2799 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2800 _profile(Package$isUnfilteredAndSearchedForBy)
2803 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2804 value &= [self unfiltered];
2807 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2808 value &= [self matches:search];
2815 - (bool) isInstalledAndVisible:(NSNumber *)number {
2816 return (![number boolValue] || [self visible]) && ![self uninstalled];
2819 - (bool) isVisibleInSection:(NSString *)name {
2820 NSString *section = [self section];
2825 section == nil && [name length] == 0 ||
2826 [name isEqualToString:section]
2830 - (bool) isVisibleInSource:(Source *)source {
2831 return [self source] == source && [self visible];
2836 /* Section Class {{{ */
2837 @interface Section : NSObject {
2842 NSString *localized_;
2845 - (NSComparisonResult) compareByLocalized:(Section *)section;
2846 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2847 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2848 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2849 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2850 - (NSString *) name;
2857 - (void) addToCount;
2859 - (void) setCount:(size_t)count;
2860 - (NSString *) localized;
2864 @implementation Section
2868 if (localized_ != nil)
2869 [localized_ release];
2873 - (NSComparisonResult) compareByLocalized:(Section *)section {
2874 NSString *lhs(localized_);
2875 NSString *rhs([section localized]);
2877 /*if ([lhs length] != 0 && [rhs length] != 0) {
2878 unichar lhc = [lhs characterAtIndex:0];
2879 unichar rhc = [rhs characterAtIndex:0];
2881 if (isalpha(lhc) && !isalpha(rhc))
2882 return NSOrderedAscending;
2883 else if (!isalpha(lhc) && isalpha(rhc))
2884 return NSOrderedDescending;
2887 return [lhs compare:rhs options:LaxCompareOptions_];
2890 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2891 if ((self = [self initWithName:name localize:NO]) != nil) {
2892 if (localized != nil)
2893 localized_ = [localized retain];
2897 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2898 return [self initWithName:name row:0 localize:localize];
2901 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2902 if ((self = [super init]) != nil) {
2903 name_ = [name retain];
2907 localized_ = [LocalizeSection(name_) retain];
2911 /* XXX: localize the index thingees */
2912 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2913 if ((self = [super init]) != nil) {
2914 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2920 - (NSString *) name {
2940 - (void) addToCount {
2944 - (void) setCount:(size_t)count {
2948 - (NSString *) localized {
2955 static NSString *Colon_;
2956 static NSString *Error_;
2957 static NSString *Warning_;
2959 /* Database Implementation {{{ */
2960 @implementation Database
2962 + (Database *) sharedInstance {
2963 static Database *instance;
2964 if (instance == nil)
2965 instance = [[Database alloc] init];
2975 NSRecycleZone(zone_);
2976 // XXX: malloc_destroy_zone(zone_);
2977 apr_pool_destroy(pool_);
2981 - (void) _readCydia:(NSNumber *)fd { _pooled
2982 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2983 std::istream is(&ib);
2986 static Pcre finish_r("^finish:([^:]*)$");
2988 while (std::getline(is, line)) {
2989 const char *data(line.c_str());
2990 size_t size = line.size();
2991 lprintf("C:%s\n", data);
2993 if (finish_r(data, size)) {
2994 NSString *finish = finish_r[1];
2995 int index = [Finishes_ indexOfObject:finish];
2996 if (index != INT_MAX && index > Finish_)
3004 - (void) _readStatus:(NSNumber *)fd { _pooled
3005 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3006 std::istream is(&ib);
3009 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3010 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3012 while (std::getline(is, line)) {
3013 const char *data(line.c_str());
3014 size_t size(line.size());
3015 lprintf("S:%s\n", data);
3017 if (conffile_r(data, size)) {
3018 [delegate_ setConfigurationData:conffile_r[1]];
3019 } else if (strncmp(data, "status: ", 8) == 0) {
3020 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3021 [delegate_ setProgressTitle:string];
3022 } else if (pmstatus_r(data, size)) {
3023 std::string type([pmstatus_r[1] UTF8String]);
3024 NSString *id = pmstatus_r[2];
3026 float percent([pmstatus_r[3] floatValue]);
3027 [delegate_ setProgressPercent:(percent / 100)];
3029 NSString *string = pmstatus_r[4];
3031 if (type == "pmerror")
3032 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3033 withObject:[NSArray arrayWithObjects:string, id, nil]
3036 else if (type == "pmstatus") {
3037 [delegate_ setProgressTitle:string];
3038 } else if (type == "pmconffile")
3039 [delegate_ setConfigurationData:string];
3041 lprintf("E:unknown pmstatus\n");
3043 lprintf("E:unknown status\n");
3049 - (void) _readOutput:(NSNumber *)fd { _pooled
3050 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3051 std::istream is(&ib);
3054 while (std::getline(is, line)) {
3055 lprintf("O:%s\n", line.c_str());
3056 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3066 - (Package *) packageWithName:(NSString *)name {
3067 @synchronized ([Database class]) {
3068 if (static_cast<pkgDepCache *>(cache_) == NULL)
3070 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3071 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3074 - (Database *) init {
3075 if ((self = [super init]) != nil) {
3082 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3083 apr_pool_create(&pool_, NULL);
3085 packages_ = [[NSMutableArray alloc] init];
3089 _assert(pipe(fds) != -1);
3092 _config->Set("APT::Keep-Fds::", cydiafd_);
3093 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3096 detachNewThreadSelector:@selector(_readCydia:)
3098 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3101 _assert(pipe(fds) != -1);
3105 detachNewThreadSelector:@selector(_readStatus:)
3107 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3110 _assert(pipe(fds) != -1);
3111 _assert(dup2(fds[0], 0) != -1);
3112 _assert(close(fds[0]) != -1);
3114 input_ = fdopen(fds[1], "a");
3116 _assert(pipe(fds) != -1);
3117 _assert(dup2(fds[1], 1) != -1);
3118 _assert(close(fds[1]) != -1);
3121 detachNewThreadSelector:@selector(_readOutput:)
3123 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3128 - (pkgCacheFile &) cache {
3132 - (pkgDepCache::Policy *) policy {
3136 - (pkgRecords *) records {
3140 - (pkgProblemResolver *) resolver {
3144 - (pkgAcquire &) fetcher {
3148 - (pkgSourceList &) list {
3152 - (NSArray *) packages {
3156 - (NSArray *) sources {
3157 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3158 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3159 [sources addObject:i->second];
3163 - (NSArray *) issues {
3164 if (cache_->BrokenCount() == 0)
3167 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3169 for (Package *package in packages_) {
3170 if (![package broken])
3172 pkgCache::PkgIterator pkg([package iterator]);
3174 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3175 [entry addObject:[package name]];
3176 [issues addObject:entry];
3178 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3182 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3183 pkgCache::DepIterator start;
3184 pkgCache::DepIterator end;
3185 dep.GlobOr(start, end); // ++dep
3187 if (!cache_->IsImportantDep(end))
3189 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3192 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3193 [entry addObject:failure];
3194 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3196 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3197 if (Package *package = [self packageWithName:name])
3198 name = [package name];
3199 [failure addObject:name];
3201 pkgCache::PkgIterator target(start.TargetPkg());
3202 if (target->ProvidesList != 0)
3203 [failure addObject:@"?"];
3205 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3207 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3208 else if (!cache_[target].CandidateVerIter(cache_).end())
3209 [failure addObject:@"-"];
3210 else if (target->ProvidesList == 0)
3211 [failure addObject:@"!"];
3213 [failure addObject:@"%"];
3217 if (start.TargetVer() != 0)
3218 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3229 - (bool) popErrorWithTitle:(NSString *)title {
3231 std::string message;
3233 while (!_error->empty()) {
3235 bool warning(!_error->PopMessage(error));
3239 size_t size(error.size());
3240 if (size == 0 || error[size - 1] != '\n')
3242 error.resize(size - 1);
3244 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3246 if (!message.empty())
3251 if (fatal && !message.empty())
3252 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3257 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3258 return [self popErrorWithTitle:title] || !success;
3261 - (void) reloadData { _pooled
3262 @synchronized ([Database class]) {
3263 @synchronized (self) {
3267 [packages_ removeAllObjects];
3293 apr_pool_clear(pool_);
3294 NSRecycleZone(zone_);
3296 int chk(creat("/tmp/cydia.chk", 0644));
3300 NSString *title(UCLocalize("DATABASE"));
3303 if (!cache_.Open(progress_, true)) { pop:
3305 bool warning(!_error->PopMessage(error));
3306 lprintf("cache_.Open():[%s]\n", error.c_str());
3308 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3309 [delegate_ repairWithSelector:@selector(configure)];
3310 else if (error == "The package lists or status file could not be parsed or opened.")
3311 [delegate_ repairWithSelector:@selector(update)];
3312 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3313 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3314 // else if (error == "The list of sources could not be read.")
3316 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3325 unlink("/tmp/cydia.chk");
3327 now_ = [[NSDate date] retain];
3329 policy_ = new pkgDepCache::Policy();
3330 records_ = new pkgRecords(cache_);
3331 resolver_ = new pkgProblemResolver(cache_);
3332 fetcher_ = new pkgAcquire(&status_);
3335 list_ = new pkgSourceList();
3336 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3339 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3340 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3344 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3347 if (cache_->BrokenCount() != 0) {
3348 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3351 if (cache_->BrokenCount() != 0) {
3352 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3356 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3362 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3363 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3364 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3365 // XXX: this could be more intelligent
3366 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3367 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3369 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3376 /*std::vector<Package *> packages;
3377 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3378 [packages_ release];
3383 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3384 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3385 //packages.push_back(package);
3386 [packages_ addObject:package];
3390 /*if (packages.empty())
3391 packages_ = [[NSArray alloc] init];
3393 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3396 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3397 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3398 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3406 /*if (!packages.empty())
3407 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3408 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3410 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3412 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3414 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3420 - (void) configure {
3421 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3422 system([dpkg UTF8String]);
3426 // XXX: I don't remember this condition
3431 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3433 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3435 if ([self popErrorWithTitle:title])
3439 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3442 public pkgArchiveCleaner
3445 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3450 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3457 fetcher_->Shutdown();
3459 pkgRecords records(cache_);
3461 lock_ = new FileFd();
3462 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3464 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3466 if ([self popErrorWithTitle:title])
3470 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3473 manager_ = (_system->CreatePM(cache_));
3474 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3481 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3483 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3485 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3487 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3488 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3491 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3496 bool failed = false;
3497 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3498 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3500 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3503 std::string uri = (*item)->DescURI();
3504 std::string error = (*item)->ErrorText;
3506 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3509 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3510 withObject:[NSArray arrayWithObjects:
3511 [NSString stringWithUTF8String:error.c_str()],
3523 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3525 if (_error->PendingError()) {
3530 if (result == pkgPackageManager::Failed) {
3535 if (result != pkgPackageManager::Completed) {
3540 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3542 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3544 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3545 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3548 if (![before isEqualToArray:after])
3553 NSString *title(UCLocalize("UPGRADE"));
3554 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3560 [self updateWithStatus:status_];
3563 - (void) setVisible {
3564 for (Package *package in packages_)
3565 [package setVisible];
3568 - (void) updateWithStatus:(Status &)status {
3569 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3570 NSString *title(UCLocalize("REFRESHING_DATA"));
3573 if (!list.ReadMainList())
3574 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3577 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3578 if ([self popErrorWithTitle:title])
3581 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3582 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */;
3584 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3588 - (void) setDelegate:(id)delegate {
3589 delegate_ = delegate;
3590 status_.setDelegate(delegate);
3591 progress_.setDelegate(delegate);
3594 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3595 SourceMap::const_iterator i(sources_.find(file->ID));
3596 return i == sources_.end() ? nil : i->second;
3602 /* Confirmation View {{{ */
3603 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3604 if (!iterator.end())
3605 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3606 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3608 pkgCache::PkgIterator package(dep.TargetPkg());
3611 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3618 /* Web Scripting {{{ */
3619 @interface CydiaObject : NSObject {
3623 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3626 @implementation CydiaObject
3629 [indirect_ release];
3633 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3634 if ((self = [super init]) != nil) {
3635 indirect_ = [indirect retain];
3639 + (NSArray *) _attributeKeys {
3640 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3643 - (NSArray *) attributeKeys {
3644 return [[self class] _attributeKeys];
3647 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3648 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3651 - (NSString *) device {
3652 return [[UIDevice currentDevice] uniqueIdentifier];
3655 #if 0 // XXX: implement!
3656 - (NSString *) mac {
3657 if (![indirect_ promptForSensitive:@"Mac Address"])
3661 - (NSString *) serial {
3662 if (![indirect_ promptForSensitive:@"Serial #"])
3666 - (NSString *) firewire {
3667 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3671 - (NSString *) imei {
3672 if (![indirect_ promptForSensitive:@"IMEI"])
3677 + (NSString *) webScriptNameForSelector:(SEL)selector {
3678 if (selector == @selector(close))
3680 else if (selector == @selector(getPackageById:))
3681 return @"getPackageById";
3682 else if (selector == @selector(setAutoPopup:))
3683 return @"setAutoPopup";
3684 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3685 return @"setButtonImage";
3686 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3687 return @"setButtonTitle";
3688 else if (selector == @selector(setFinishHook:))
3689 return @"setFinishHook";
3690 else if (selector == @selector(setPopupHook:))
3691 return @"setPopupHook";
3692 else if (selector == @selector(setSpecial:))
3693 return @"setSpecial";
3694 else if (selector == @selector(setViewportWidth:))
3695 return @"setViewportWidth";
3696 else if (selector == @selector(supports:))
3698 else if (selector == @selector(stringWithFormat:arguments:))
3700 else if (selector == @selector(localizedStringForKey:value:table:))
3702 else if (selector == @selector(du:))
3704 else if (selector == @selector(statfs:))
3710 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3711 return [self webScriptNameForSelector:selector] == nil;
3714 - (BOOL) supports:(NSString *)feature {
3715 return [feature isEqualToString:@"window.open"];
3718 - (Package *) getPackageById:(NSString *)id {
3719 Package *package([[Database sharedInstance] packageWithName:id]);
3724 - (NSArray *) statfs:(NSString *)path {
3727 if (path == nil || statfs([path UTF8String], &stat) == -1)
3730 return [NSArray arrayWithObjects:
3731 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3732 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3733 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3737 - (NSNumber *) du:(NSString *)path {
3738 NSNumber *value(nil);
3741 _assert(pipe(fds) != -1);
3743 pid_t pid(ExecFork());
3745 _assert(dup2(fds[1], 1) != -1);
3746 _assert(close(fds[0]) != -1);
3747 _assert(close(fds[1]) != -1);
3748 /* XXX: this should probably not use du */
3749 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3754 _assert(close(fds[1]) != -1);
3756 if (FILE *du = fdopen(fds[0], "r")) {
3758 while (fgets(line, sizeof(line), du) != NULL) {
3759 size_t length(strlen(line));
3760 while (length != 0 && line[length - 1] == '\n')
3761 line[--length] = '\0';
3762 if (char *tab = strchr(line, '\t')) {
3764 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3769 } else _assert(close(fds[0]));
3773 if (waitpid(pid, &status, 0) == -1)
3776 else _assert(false);
3785 - (void) setAutoPopup:(BOOL)popup {
3786 [indirect_ setAutoPopup:popup];
3789 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3790 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3793 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3794 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3797 - (void) setSpecial:(id)function {
3798 [indirect_ setSpecial:function];
3801 - (void) setFinishHook:(id)function {
3802 [indirect_ setFinishHook:function];
3805 - (void) setPopupHook:(id)function {
3806 [indirect_ setPopupHook:function];
3809 - (void) setViewportWidth:(float)width {
3810 [indirect_ setViewportWidth:width];
3813 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3814 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3815 unsigned count([arguments count]);
3817 for (unsigned i(0); i != count; ++i)
3818 values[i] = [arguments objectAtIndex:i];
3819 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3822 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3823 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3825 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3827 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3833 @interface CydiaBrowserView : BrowserView {
3834 CydiaObject *cydia_;
3839 @implementation CydiaBrowserView
3846 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3847 [super webView:sender didClearWindowObject:window forFrame:frame];
3848 [window setValue:cydia_ forKey:@"cydia"];
3851 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3852 if (System_ != NULL)
3853 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3854 if (Machine_ != NULL)
3855 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3856 if (UniqueID_ != nil)
3857 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
3859 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3862 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3863 NSMutableURLRequest *copy = [request mutableCopy];
3864 [self _setMoreHeaders:copy];
3868 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
3869 if ((self = [super initWithBook:book forWidth:width ofClass:[CydiaBrowserView class]]) != nil) {
3870 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3872 WebView *webview([webview_ webView]);
3874 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3876 NSString *application = package == nil ? @"Cydia" : [NSString
3877 stringWithFormat:@"Cydia/%@",
3882 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3884 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3885 if (Product_ != nil)
3886 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3888 [webview setApplicationNameForUserAgent:application];
3894 @protocol ConfirmationViewDelegate
3900 @interface ConfirmationView : CydiaBrowserView {
3901 _transient Database *database_;
3902 UIActionSheet *essential_;
3909 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3913 @implementation ConfirmationView
3920 if (essential_ != nil)
3921 [essential_ release];
3927 [book_ popFromSuperviewAnimated:YES];
3930 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3931 NSString *context([sheet context]);
3933 if ([context isEqualToString:@"remove"]) {
3941 [delegate_ confirm];
3947 } else if ([context isEqualToString:@"unable"]) {
3951 [super alertSheet:sheet buttonClicked:button];
3954 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3955 [super webView:sender didClearWindowObject:window forFrame:frame];
3956 [window setValue:changes_ forKey:@"changes"];
3957 [window setValue:issues_ forKey:@"issues"];
3958 [window setValue:sizes_ forKey:@"sizes"];
3961 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3962 if ((self = [super initWithBook:book]) != nil) {
3963 database_ = database;
3965 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3966 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3967 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3968 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3969 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3973 pkgDepCache::Policy *policy([database_ policy]);
3975 pkgCacheFile &cache([database_ cache]);
3976 NSArray *packages = [database_ packages];
3977 for (Package *package in packages) {
3978 pkgCache::PkgIterator iterator = [package iterator];
3979 pkgDepCache::StateCache &state(cache[iterator]);
3981 NSString *name([package name]);
3983 if (state.NewInstall())
3984 [installing addObject:name];
3985 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3986 [reinstalling addObject:name];
3987 else if (state.Upgrade())
3988 [upgrading addObject:name];
3989 else if (state.Downgrade())
3990 [downgrading addObject:name];
3991 else if (state.Delete()) {
3992 if ([package essential])
3994 [removing addObject:name];
3997 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3998 substrate_ |= DepSubstrate(iterator.CurrentVer());
4003 else if (Advanced_) {
4004 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4006 essential_ = [[UIActionSheet alloc]
4007 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4008 buttons:[NSArray arrayWithObjects:
4009 [NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")],
4010 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4012 defaultButtonIndex:0
4017 [essential_ setDestructiveButtonIndex:1];
4018 [essential_ setBodyText:UCLocalize("REMOVING_ESSENTIALS_EX")];
4020 essential_ = [[UIActionSheet alloc]
4021 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4022 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4023 defaultButtonIndex:0
4028 [essential_ setBodyText:UCLocalize("UNABLE_TO_COMPLY_EX")];
4031 changes_ = [[NSArray alloc] initWithObjects:
4039 issues_ = [database_ issues];
4041 issues_ = [issues_ retain];
4043 sizes_ = [[NSArray alloc] initWithObjects:
4044 SizeString([database_ fetcher].FetchNeeded()),
4045 SizeString([database_ fetcher].PartialPresent()),
4046 SizeString([database_ cache]->UsrSize()),
4049 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4053 - (NSString *) backButtonTitle {
4054 return UCLocalize("CONFIRM");
4057 - (NSString *) leftButtonTitle {
4058 return [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")];
4061 - (id) rightButtonTitle {
4062 return issues_ != nil ? nil : [super rightButtonTitle];
4065 - (id) _rightButtonTitle {
4066 #if AlwaysReload || IgnoreInstall
4067 return [super _rightButtonTitle];
4069 return UCLocalize("CONFIRM");
4073 - (void) _leftButtonClicked {
4078 - (void) _rightButtonClicked {
4080 return [super _rightButtonClicked];
4082 if (essential_ != nil)
4083 [essential_ popupAlertAnimated:YES];
4087 [delegate_ confirm];
4095 /* Progress Data {{{ */
4096 @interface ProgressData : NSObject {
4102 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4109 @implementation ProgressData
4111 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4112 if ((self = [super init]) != nil) {
4113 selector_ = selector;
4133 /* Progress View {{{ */
4134 @interface ProgressView : UIView <
4135 ConfigurationDelegate,
4138 _transient Database *database_;
4140 UIView *background_;
4141 UITransitionView *transition_;
4143 UINavigationBar *navbar_;
4144 UIProgressBar *progress_;
4145 UITextView *output_;
4146 UITextLabel *status_;
4147 UIPushButton *close_;
4150 SHA1SumValue springlist_;
4151 SHA1SumValue notifyconf_;
4155 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
4156 - (void) setContentView:(UIView *)view;
4159 - (void) _retachThread;
4160 - (void) _detachNewThreadData:(ProgressData *)data;
4161 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4167 @protocol ProgressViewDelegate
4168 - (void) progressViewIsComplete:(ProgressView *)sender;
4171 @implementation ProgressView
4174 [transition_ setDelegate:nil];
4175 [navbar_ setDelegate:nil];
4178 if (background_ != nil)
4179 [background_ release];
4180 [transition_ release];
4183 [progress_ release];
4192 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
4193 if ((self = [super initWithFrame:frame]) != nil) {
4194 database_ = database;
4195 delegate_ = delegate;
4197 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
4198 [transition_ setDelegate:self];
4200 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
4202 background_ = [[UIView alloc] initWithFrame:[self bounds]];
4203 [background_ setBackgroundColor:[UIColor blackColor]];
4204 [self addSubview:background_];
4206 [self addSubview:transition_];
4208 CGSize navsize = [UINavigationBar defaultSize];
4209 CGRect navrect = {{0, 0}, navsize};
4211 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
4212 [overlay_ addSubview:navbar_];
4214 [navbar_ setBarStyle:1];
4215 [navbar_ setDelegate:self];
4217 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
4218 [navbar_ pushNavigationItem:navitem];
4220 CGRect bounds = [overlay_ bounds];
4221 CGSize prgsize = [UIProgressBar defaultSize];
4224 (bounds.size.width - prgsize.width) / 2,
4225 bounds.size.height - prgsize.height - 20
4228 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
4229 [progress_ setStyle:0];
4231 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
4233 bounds.size.height - prgsize.height - 50,
4234 bounds.size.width - 20,
4238 [status_ setColor:[UIColor whiteColor]];
4239 [status_ setBackgroundColor:[UIColor clearColor]];
4241 [status_ setCentersHorizontally:YES];
4242 //[status_ setFont:font];
4244 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
4246 navrect.size.height + 20,
4247 bounds.size.width - 20,
4248 bounds.size.height - navsize.height - 62 - navrect.size.height
4251 //[output_ setTextFont:@"Courier New"];
4252 [output_ setFont:[[output_ font] fontWithSize:12]];
4254 [output_ setTextColor:[UIColor whiteColor]];
4255 [output_ setBackgroundColor:[UIColor clearColor]];
4257 [output_ setMarginTop:0];
4258 [output_ setAllowsRubberBanding:YES];
4259 [output_ setEditable:NO];
4261 [overlay_ addSubview:output_];
4263 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
4265 bounds.size.height - prgsize.height - 50,
4266 bounds.size.width - 20,
4270 [close_ setAutosizesToFit:NO];
4271 [close_ setDrawsShadow:YES];
4272 [close_ setStretchBackground:YES];
4273 [close_ setEnabled:YES];
4275 UIFont *bold = [UIFont boldSystemFontOfSize:22];
4276 [close_ setTitleFont:bold];
4278 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4279 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4280 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4284 - (void) setContentView:(UIView *)view {
4285 view_ = [view retain];
4288 - (void) resetView {
4289 [transition_ transition:6 toView:view_];
4292 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4293 NSString *context([sheet context]);
4295 if ([context isEqualToString:@"conffile"]) {
4296 FILE *input = [database_ input];
4300 fprintf(input, "N\n");
4304 fprintf(input, "Y\n");
4314 - (void) closeButtonPushed {
4323 [delegate_ terminateWithSuccess];
4324 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4325 [delegate_ suspendWithAnimation:YES];
4327 [delegate_ suspend];*/
4331 system("launchctl stop com.apple.SpringBoard");
4335 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4344 - (void) _retachThread {
4345 UINavigationItem *item([navbar_ topItem]);
4346 [item setTitle:UCLocalize("COMPLETE")];
4348 [overlay_ addSubview:close_];
4349 [progress_ removeFromSuperview];
4350 [status_ removeFromSuperview];
4352 [database_ popErrorWithTitle:title_];
4353 [delegate_ progressViewIsComplete:self];
4357 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4360 MMap mmap(file, MMap::ReadOnly);
4362 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4363 if (!(notifyconf_ == sha1.Result()))
4370 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4373 MMap mmap(file, MMap::ReadOnly);
4375 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4376 if (!(springlist_ == sha1.Result()))
4382 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break;
4383 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4384 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4385 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4386 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4389 #define ListCache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4390 #define IconCache_ "/User/Library/Caches/com.apple.springboard-imagecache-icons.plist"
4394 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ListCache_]) {
4395 [cache autorelease];
4397 NSFileManager *manager([NSFileManager defaultManager]);
4398 NSError *error(nil);
4400 id system([cache objectForKey:@"System"]);
4405 if (stat(ListCache_, &info) == -1)
4408 [system removeAllObjects];
4410 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4411 for (NSString *app in apps)
4412 if ([app hasSuffix:@".app"]) {
4413 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4414 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4415 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4417 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4418 [info setObject:path forKey:@"Path"];
4419 [info setObject:@"System" forKey:@"ApplicationType"];
4420 [system addInfoDictionary:info];
4426 [cache writeToFile:@ListCache_ atomically:YES];
4428 if (chown(ListCache_, info.st_uid, info.st_gid) == -1)
4430 if (chmod(ListCache_, info.st_mode) == -1)
4434 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4437 notify_post("com.apple.mobile.application_installed");
4439 [delegate_ setStatusBarShowsProgress:NO];
4442 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4443 [[data target] performSelector:[data selector] withObject:[data object]];
4446 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4449 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4455 title_ = [title retain];
4457 UINavigationItem *item([navbar_ topItem]);
4458 [item setTitle:title_];
4460 [status_ setText:nil];
4461 [output_ setText:@""];
4462 [progress_ setProgress:0];
4464 [close_ removeFromSuperview];
4465 [overlay_ addSubview:progress_];
4466 [overlay_ addSubview:status_];
4468 [delegate_ setStatusBarShowsProgress:YES];
4473 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4476 MMap mmap(file, MMap::ReadOnly);
4478 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4479 notifyconf_ = sha1.Result();
4485 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4488 MMap mmap(file, MMap::ReadOnly);
4490 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4491 springlist_ = sha1.Result();
4495 [transition_ transition:6 toView:overlay_];
4498 detachNewThreadSelector:@selector(_detachNewThreadData:)
4500 withObject:[[ProgressData alloc]
4501 initWithSelector:selector
4508 - (void) repairWithSelector:(SEL)selector {
4510 detachNewThreadSelector:selector
4513 title:UCLocalize("REPAIRING")
4517 - (void) setConfigurationData:(NSString *)data {
4519 performSelectorOnMainThread:@selector(_setConfigurationData:)
4525 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4526 CYActionSheet *sheet([[[CYActionSheet alloc]
4528 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4529 defaultButtonIndex:0
4532 [sheet setBodyText:error];
4533 [sheet yieldToPopupAlertAnimated:YES];
4537 - (void) setProgressTitle:(NSString *)title {
4539 performSelectorOnMainThread:@selector(_setProgressTitle:)
4545 - (void) setProgressPercent:(float)percent {
4547 performSelectorOnMainThread:@selector(_setProgressPercent:)
4548 withObject:[NSNumber numberWithFloat:percent]
4553 - (void) startProgress {
4556 - (void) addProgressOutput:(NSString *)output {
4558 performSelectorOnMainThread:@selector(_addProgressOutput:)
4564 - (bool) isCancelling:(size_t)received {
4568 - (void) _setConfigurationData:(NSString *)data {
4569 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4571 if (!conffile_r(data)) {
4572 lprintf("E:invalid conffile\n");
4576 NSString *ofile = conffile_r[1];
4577 //NSString *nfile = conffile_r[2];
4579 UIActionSheet *sheet = [[[UIActionSheet alloc]
4580 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4581 buttons:[NSArray arrayWithObjects:
4582 UCLocalize("KEEP_OLD_COPY"),
4583 UCLocalize("ACCEPT_NEW_COPY"),
4584 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4586 defaultButtonIndex:0
4591 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4592 [sheet popupAlertAnimated:YES];
4595 - (void) _setProgressTitle:(NSString *)title {
4596 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4597 for (size_t i(0), e([words count]); i != e; ++i) {
4598 NSString *word([words objectAtIndex:i]);
4599 if (Package *package = [database_ packageWithName:word])
4600 [words replaceObjectAtIndex:i withObject:[package name]];
4603 [status_ setText:[words componentsJoinedByString:@" "]];
4606 - (void) _setProgressPercent:(NSNumber *)percent {
4607 [progress_ setProgress:[percent floatValue]];
4610 - (void) _addProgressOutput:(NSString *)output {
4611 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4612 CGSize size = [output_ contentSize];
4613 CGRect rect = {{0, size.height}, {size.width, 0}};
4614 [output_ scrollRectToVisible:rect animated:YES];
4617 - (BOOL) isRunning {
4624 /* Package Cell {{{ */
4625 @interface ContentView : UIView {
4626 _transient id delegate_;
4631 @interface PackageCell : UITableViewCell {
4634 NSString *description_;
4640 ContentView *content_;
4646 - (PackageCell *) init;
4647 - (void) setPackage:(Package *)package;
4649 + (int) heightForPackage:(Package *)package;
4650 - (void) drawContentRect:(CGRect)rect;
4654 @implementation ContentView
4656 - (id) initWithFrame:(CGRect)frame {
4657 if ((self = [super initWithFrame:frame]) != nil) {
4661 - (void) setDelegate:(id)delegate {
4662 delegate_ = delegate;
4665 - (void) drawRect:(CGRect)rect {
4666 [super drawRect:rect];
4667 [delegate_ drawContentRect:rect];
4672 @implementation PackageCell
4674 - (void) clearPackage {
4685 if (description_ != nil) {
4686 [description_ release];
4690 if (source_ != nil) {
4695 if (badge_ != nil) {
4700 if (placard_ != nil) {
4710 [self clearPackage];
4717 return faded_ ? [self selectionPercent] : fade_;
4720 - (PackageCell *) init {
4721 CGRect frame(CGRectMake(0, 0, 320, 74));
4722 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4723 UIView *content([self contentView]);
4724 CGRect bounds([content bounds]);
4725 content_ = [[ContentView alloc] initWithFrame:bounds];
4726 [content_ setDelegate:self];
4727 [content_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
4728 [content_ setOpaque:YES];
4729 [content addSubview:content_];
4730 if ([self respondsToSelector:@selector(selectionPercent)])
4735 - (void) _setBackgroundColor {
4737 if (NSString *mode = [package_ mode]) {
4738 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4739 color = remove ? RemovingColor_ : InstallingColor_;
4741 color = [UIColor whiteColor];
4743 [content_ setBackgroundColor:color];
4744 [self setNeedsDisplay];
4747 - (void) setPackage:(Package *)package {
4748 [self clearPackage];
4751 Source *source = [package source];
4753 icon_ = [[package icon] retain];
4754 name_ = [[package name] retain];
4755 description_ = [[package shortDescription] retain];
4756 commercial_ = [package isCommercial];
4758 package_ = [package retain];
4760 NSString *label = nil;
4761 bool trusted = false;
4763 if (source != nil) {
4764 label = [source label];
4765 trusted = [source trusted];
4766 } else if ([[package id] isEqualToString:@"firmware"])
4767 label = UCLocalize("APPLE");
4769 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4771 NSString *from(label);
4773 NSString *section = [package simpleSection];
4774 if (section != nil && ![section isEqualToString:label]) {
4775 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4776 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4779 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4780 source_ = [from retain];
4782 if (NSString *purpose = [package primaryPurpose])
4783 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4784 badge_ = [badge_ retain];
4786 if ([package installed] != nil)
4787 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4788 placard_ = [placard_ retain];
4790 [self _setBackgroundColor];
4791 [content_ setNeedsDisplay];
4794 - (void) drawContentRect:(CGRect)rect {
4795 bool selected([self isSelected]);
4798 CGContextRef context(UIGraphicsGetCurrentContext());
4799 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4800 CGContextFillRect(context, rect);
4805 rect.size = [icon_ size];
4807 rect.size.width /= 2;
4808 rect.size.height /= 2;
4810 rect.origin.x = 25 - rect.size.width / 2;
4811 rect.origin.y = 25 - rect.size.height / 2;
4813 [icon_ drawInRect:rect];
4816 if (badge_ != nil) {
4817 CGSize size = [badge_ size];
4819 [badge_ drawAtPoint:CGPointMake(
4820 36 - size.width / 2,
4821 36 - size.height / 2
4829 UISetColor(commercial_ ? Purple_ : Black_);
4830 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(placard_ == nil ? 240 : 214) withFont:Font18Bold_ ellipsis:2];
4831 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4834 UISetColor(commercial_ ? Purplish_ : Gray_);
4835 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:274 withFont:Font14_ ellipsis:2];
4837 if (placard_ != nil)
4838 [placard_ drawAtPoint:CGPointMake(268, 9)];
4841 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4842 //[self _setBackgroundColor];
4843 [super setSelected:selected animated:fade];
4844 [content_ setNeedsDisplay];
4847 + (int) heightForPackage:(Package *)package {
4853 /* Section Cell {{{ */
4854 @interface SectionCell : UISimpleTableCell {
4859 _UISwitchSlider *switch_;
4864 - (void) setSection:(Section *)section editing:(BOOL)editing;
4868 @implementation SectionCell
4870 - (void) clearSection {
4871 if (section_ != nil) {
4881 if (count_ != nil) {
4888 [self clearSection];
4895 if ((self = [super init]) != nil) {
4896 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4898 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4899 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventTouchUpInside];
4903 - (void) onSwitch:(id)sender {
4904 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4905 if (metadata == nil) {
4906 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4907 [Sections_ setObject:metadata forKey:section_];
4911 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4914 - (void) setSection:(Section *)section editing:(BOOL)editing {
4915 if (editing != editing_) {
4917 [switch_ removeFromSuperview];
4919 [self addSubview:switch_];
4923 [self clearSection];
4925 if (section == nil) {
4926 name_ = [UCLocalize("ALL_PACKAGES") retain];
4929 section_ = [section localized];
4930 if (section_ != nil)
4931 section_ = [section_ retain];
4932 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4933 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4936 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4940 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4941 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4948 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4950 CGSize size = [count_ sizeWithFont:Font14_];
4954 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4956 [super drawContentInRect:rect selected:selected];
4962 /* File Table {{{ */
4963 @interface FileTable : RVPage {
4964 _transient Database *database_;
4967 NSMutableArray *files_;
4971 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4972 - (void) setPackage:(Package *)package;
4976 @implementation FileTable
4979 if (package_ != nil)
4988 - (int) numberOfRowsInTable:(UITable *)table {
4989 return files_ == nil ? 0 : [files_ count];
4992 - (float) table:(UITable *)table heightForRow:(int)row {
4996 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4997 if (reusing == nil) {
4998 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4999 UIFont *font = [UIFont systemFontOfSize:16];
5000 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
5002 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
5006 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5010 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5011 if ((self = [super initWithBook:book]) != nil) {
5012 database_ = database;
5014 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5016 list_ = [[UITable alloc] initWithFrame:[self bounds]];
5017 [self addSubview:list_];
5019 UITableColumn *column = [[[UITableColumn alloc]
5020 initWithTitle:UCLocalize("NAME")
5022 width:[self frame].size.width
5025 [list_ setDataSource:self];
5026 [list_ setSeparatorStyle:1];
5027 [list_ addTableColumn:column];
5028 [list_ setDelegate:self];
5029 [list_ setReusesTableCells:YES];
5033 - (void) setPackage:(Package *)package {
5034 if (package_ != nil) {
5035 [package_ autorelease];
5044 [files_ removeAllObjects];
5046 if (package != nil) {
5047 package_ = [package retain];
5048 name_ = [[package id] retain];
5050 if (NSArray *files = [package files])
5051 [files_ addObjectsFromArray:files];
5053 if ([files_ count] != 0) {
5054 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5055 [files_ removeObjectAtIndex:0];
5056 [files_ sortUsingSelector:@selector(compareByPath:)];
5058 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5059 [stack addObject:@"/"];
5061 for (int i(0), e([files_ count]); i != e; ++i) {
5062 NSString *file = [files_ objectAtIndex:i];
5063 while (![file hasPrefix:[stack lastObject]])
5064 [stack removeLastObject];
5065 NSString *directory = [stack lastObject];
5066 [stack addObject:[file stringByAppendingString:@"/"]];
5067 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5068 ([stack count] - 2) * 3, "",
5069 [file substringFromIndex:[directory length]]
5078 - (void) resetViewAnimated:(BOOL)animated {
5079 [list_ resetViewAnimated:animated];
5082 - (void) reloadData {
5083 [self setPackage:[database_ packageWithName:name_]];
5084 [self reloadButtons];
5087 - (NSString *) title {
5088 return UCLocalize("INSTALLED_FILES");
5091 - (NSString *) backButtonTitle {
5092 return UCLocalize("FILES");
5097 /* Package View {{{ */
5098 @interface PackageView : CydiaBrowserView {
5099 _transient Database *database_;
5103 NSMutableArray *buttons_;
5106 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5107 - (void) setPackage:(Package *)package;
5111 @implementation PackageView
5114 if (package_ != nil)
5123 if ([self retainCount] == 1)
5124 [delegate_ setPackageView:self];
5128 /* XXX: this is not safe at all... localization of /fail/ */
5129 - (void) _clickButtonWithName:(NSString *)name {
5130 if ([name isEqualToString:UCLocalize("CLEAR")])
5131 [delegate_ clearPackage:package_];
5132 else if ([name isEqualToString:UCLocalize("INSTALL")])
5133 [delegate_ installPackage:package_];
5134 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5135 [delegate_ installPackage:package_];
5136 else if ([name isEqualToString:UCLocalize("REMOVE")])
5137 [delegate_ removePackage:package_];
5138 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5139 [delegate_ installPackage:package_];
5140 else _assert(false);
5143 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5144 NSString *context([sheet context]);
5146 if ([context isEqualToString:@"modify"]) {
5147 int count = [buttons_ count];
5148 _assert(count != 0);
5149 _assert(button <= count + 1);
5151 if (count != button - 1)
5152 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
5156 [super alertSheet:sheet buttonClicked:button];
5159 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5160 return [super webView:sender didFinishLoadForFrame:frame];
5163 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5164 [super webView:sender didClearWindowObject:window forFrame:frame];
5165 [window setValue:package_ forKey:@"package"];
5168 - (bool) _allowJavaScriptPanel {
5173 - (void) __rightButtonClicked {
5174 int count([buttons_ count]);
5179 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5181 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
5182 [buttons addObjectsFromArray:buttons_];
5183 [buttons addObject:UCLocalize("CANCEL")];
5185 [delegate_ slideUp:[[[UIActionSheet alloc]
5188 defaultButtonIndex:([buttons count] - 1)
5195 - (void) _rightButtonClicked {
5197 [super _rightButtonClicked];
5199 [self __rightButtonClicked];
5203 - (id) _rightButtonTitle {
5204 int count = [buttons_ count];
5205 return count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0];
5208 - (NSString *) backButtonTitle {
5212 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5213 if ((self = [super initWithBook:book]) != nil) {
5214 database_ = database;
5215 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5216 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5220 - (void) setPackage:(Package *)package {
5221 if (package_ != nil) {
5222 [package_ autorelease];
5231 [buttons_ removeAllObjects];
5233 if (package != nil) {
5236 package_ = [package retain];
5237 name_ = [[package id] retain];
5238 commercial_ = [package isCommercial];
5240 if ([package_ mode] != nil)
5241 [buttons_ addObject:UCLocalize("CLEAR")];
5242 if ([package_ source] == nil);
5243 else if ([package_ upgradableAndEssential:NO])
5244 [buttons_ addObject:UCLocalize("UPGRADE")];
5245 else if ([package_ uninstalled])
5246 [buttons_ addObject:UCLocalize("INSTALL")];
5248 [buttons_ addObject:UCLocalize("REINSTALL")];
5249 if (![package_ uninstalled])
5250 [buttons_ addObject:UCLocalize("REMOVE")];
5252 if (special_ != NULL) {
5253 CGRect frame([webview_ frame]);
5254 frame.size.width = 320;
5255 frame.size.height = 0;
5256 [webview_ setFrame:frame];
5258 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5261 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5263 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5265 [self setFinishHook:nil];
5266 [self setPopupHook:nil];
5269 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5270 [super callFunction:special_];
5274 [self reloadButtons];
5277 - (bool) isLoading {
5278 return commercial_ ? [super isLoading] : false;
5281 - (void) reloadData {
5282 [self setPackage:[database_ packageWithName:name_]];
5287 /* Package Table {{{ */
5288 @interface PackageTable : RVPage {
5289 _transient Database *database_;
5291 NSMutableArray *packages_;
5292 NSMutableArray *sections_;
5294 NSMutableArray *index_;
5295 NSMutableDictionary *indices_;
5298 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5300 - (void) setDelegate:(id)delegate;
5302 - (void) reloadData;
5303 - (void) resetCursor;
5305 - (UITableView *) list;
5307 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5311 @implementation PackageTable
5314 [list_ setDataSource:nil];
5317 [packages_ release];
5318 [sections_ release];
5325 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5326 NSInteger count([sections_ count]);
5327 return count == 0 ? 1 : count;
5330 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5331 if ([sections_ count] == 0)
5333 return [[sections_ objectAtIndex:section] name];
5336 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5337 if ([sections_ count] == 0)
5339 return [[sections_ objectAtIndex:section] count];
5342 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5343 Section *section([sections_ objectAtIndex:[path section]]);
5344 NSInteger row([path row]);
5345 Package *package([packages_ objectAtIndex:([section row] + row)]);
5349 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5350 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
5352 cell = [[[PackageCell alloc] init] autorelease];
5353 [cell setPackage:[self packageAtIndexPath:path]];
5357 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5359 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5362 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5363 Package *package([self packageAtIndexPath:path]);
5364 package = [database_ packageWithName:[package id]];
5365 PackageView *view([delegate_ packageView]);
5366 [view setPackage:package];
5367 [view setDelegate:delegate_];
5368 [book_ pushPage:view];
5372 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5373 return [packages_ count] > 20 ? index_ : nil;
5376 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5380 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5381 if ((self = [super initWithBook:book]) != nil) {
5382 database_ = database;
5383 title_ = [title retain];
5385 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5386 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5388 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5389 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5391 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5392 [list_ setDataSource:self];
5393 [list_ setDelegate:self];
5395 [self addSubview:list_];
5397 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5398 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5402 - (void) setDelegate:(id)delegate {
5403 delegate_ = delegate;
5406 - (bool) hasPackage:(Package *)package {
5410 - (void) reloadData {
5411 NSArray *packages = [database_ packages];
5413 [packages_ removeAllObjects];
5414 [sections_ removeAllObjects];
5416 _profile(PackageTable$reloadData$Filter)
5417 for (Package *package in packages)
5418 if ([self hasPackage:package])
5419 [packages_ addObject:package];
5422 [index_ removeAllObjects];
5423 [indices_ removeAllObjects];
5425 Section *section = nil;
5427 _profile(PackageTable$reloadData$Section)
5428 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5432 _profile(PackageTable$reloadData$Section$Package)
5433 package = [packages_ objectAtIndex:offset];
5434 index = [package index];
5437 if (section == nil || [section index] != index) {
5438 _profile(PackageTable$reloadData$Section$Allocate)
5439 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5442 [index_ addObject:[section name]];
5443 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5445 _profile(PackageTable$reloadData$Section$Add)
5446 [sections_ addObject:section];
5450 [section addToCount];
5454 _profile(PackageTable$reloadData$List)
5459 - (NSString *) title {
5463 - (void) resetViewAnimated:(BOOL)animated {
5464 [list_ resetViewAnimated:animated];
5467 - (void) resetCursor {
5468 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5471 - (UITableView *) list {
5475 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5476 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5481 /* Filtered Package Table {{{ */
5482 @interface FilteredPackageTable : PackageTable {
5488 - (void) setObject:(id)object;
5490 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5494 @implementation FilteredPackageTable
5502 - (void) setObject:(id)object {
5508 object_ = [object retain];
5511 - (bool) hasPackage:(Package *)package {
5512 _profile(FilteredPackageTable$hasPackage)
5513 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5517 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5518 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5520 object_ = object == nil ? nil : [object retain];
5522 /* XXX: this is an unsafe optimization of doomy hell */
5523 Method method(class_getInstanceMethod([Package class], filter));
5524 _assert(method != NULL);
5525 imp_ = method_getImplementation(method);
5526 _assert(imp_ != NULL);
5535 /* Add Source View {{{ */
5536 @interface AddSourceView : RVPage {
5537 _transient Database *database_;
5540 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5544 @implementation AddSourceView
5546 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5547 if ((self = [super initWithBook:book]) != nil) {
5548 database_ = database;
5554 /* Source Cell {{{ */
5555 @interface SourceCell : UITableCell {
5558 NSString *description_;
5564 - (SourceCell *) initWithSource:(Source *)source;
5568 @implementation SourceCell
5573 [description_ release];
5578 - (SourceCell *) initWithSource:(Source *)source {
5579 if ((self = [super init]) != nil) {
5581 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5583 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5584 icon_ = [icon_ retain];
5586 origin_ = [[source name] retain];
5587 label_ = [[source uri] retain];
5588 description_ = [[source description] retain];
5592 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5594 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5601 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5605 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5609 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5611 [super drawContentInRect:rect selected:selected];
5616 /* Source Table {{{ */
5617 @interface SourceTable : RVPage {
5618 _transient Database *database_;
5619 UISectionList *list_;
5620 NSMutableArray *sources_;
5621 UIActionSheet *alert_;
5625 UIProgressHUD *hud_;
5628 //NSURLConnection *installer_;
5629 NSURLConnection *trivial_bz2_;
5630 NSURLConnection *trivial_gz_;
5631 //NSURLConnection *automatic_;
5636 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5640 @implementation SourceTable
5642 - (void) _deallocConnection:(NSURLConnection *)connection {
5643 if (connection != nil) {
5644 [connection cancel];
5645 //[connection setDelegate:nil];
5646 [connection release];
5651 [[list_ table] setDelegate:nil];
5652 [list_ setDataSource:nil];
5661 //[self _deallocConnection:installer_];
5662 [self _deallocConnection:trivial_gz_];
5663 [self _deallocConnection:trivial_bz2_];
5664 //[self _deallocConnection:automatic_];
5671 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5672 return offset_ == 0 ? 1 : 2;
5675 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5676 switch (section + (offset_ == 0 ? 1 : 0)) {
5677 case 0: return UCLocalize("ENTERED_BY_USER");
5678 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5684 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5685 switch (section + (offset_ == 0 ? 1 : 0)) {
5687 case 1: return offset_;
5693 - (int) numberOfRowsInTable:(UITable *)table {
5694 return [sources_ count];
5697 - (float) table:(UITable *)table heightForRow:(int)row {
5698 Source *source = [sources_ objectAtIndex:row];
5699 return [source description] == nil ? 56 : 73;
5702 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5703 Source *source = [sources_ objectAtIndex:row];
5704 // XXX: weird warning, stupid selectors ;P
5705 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5708 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5712 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5716 - (void) tableRowSelected:(NSNotification*)notification {
5717 UITable *table([list_ table]);
5718 int row([table selectedRow]);
5722 Source *source = [sources_ objectAtIndex:row];
5724 PackageTable *packages = [[[FilteredPackageTable alloc]
5727 title:[source label]
5728 filter:@selector(isVisibleInSource:)
5732 [packages setDelegate:delegate_];
5734 [book_ pushPage:packages];
5737 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5738 Source *source = [sources_ objectAtIndex:row];
5739 return [source record] != nil;
5742 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5743 [[list_ table] setDeleteConfirmationRow:row];
5746 - (void) table:(UITable *)table deleteRow:(int)row {
5747 Source *source = [sources_ objectAtIndex:row];
5748 [Sources_ removeObjectForKey:[source key]];
5749 [delegate_ syncData];
5753 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5756 @"./", @"Distribution",
5757 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5759 [delegate_ syncData];
5762 - (NSString *) getWarning {
5763 NSString *href(href_);
5764 NSRange colon([href rangeOfString:@"://"]);
5765 if (colon.location != NSNotFound)
5766 href = [href substringFromIndex:(colon.location + 3)];
5767 href = [href stringByAddingPercentEscapes];
5768 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5769 href = [href stringByCachingURLWithCurrentCDN];
5771 NSURL *url([NSURL URLWithString:href]);
5773 NSStringEncoding encoding;
5774 NSError *error(nil);
5776 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5777 return [warning length] == 0 ? nil : warning;
5781 - (void) _endConnection:(NSURLConnection *)connection {
5782 NSURLConnection **field = NULL;
5783 if (connection == trivial_bz2_)
5784 field = &trivial_bz2_;
5785 else if (connection == trivial_gz_)
5786 field = &trivial_gz_;
5787 _assert(field != NULL);
5788 [connection release];
5792 trivial_bz2_ == nil &&
5798 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5801 UIActionSheet *sheet = [[[UIActionSheet alloc]
5802 initWithTitle:UCLocalize("SOURCE_WARNING")
5803 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_ANYWAY"), UCLocalize("CANCEL"), nil]
5804 defaultButtonIndex:0
5809 [sheet setNumberOfRows:1];
5811 [sheet setBodyText:warning];
5812 [sheet popupAlertAnimated:YES];
5815 } else if (error_ != nil) {
5816 UIActionSheet *sheet = [[[UIActionSheet alloc]
5817 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5818 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5819 defaultButtonIndex:0
5824 [sheet setBodyText:[error_ localizedDescription]];
5825 [sheet popupAlertAnimated:YES];
5827 UIActionSheet *sheet = [[[UIActionSheet alloc]
5828 initWithTitle:UCLocalize("NOT_REPOSITORY")
5829 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5830 defaultButtonIndex:0
5835 [sheet setBodyText:UCLocalize("NOT_REPOSITORY_EX")];
5836 [sheet popupAlertAnimated:YES];
5839 [delegate_ setStatusBarShowsProgress:NO];
5840 [delegate_ removeProgressHUD:hud_];
5850 if (error_ != nil) {
5857 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5858 switch ([response statusCode]) {
5864 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5865 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5867 error_ = [error retain];
5868 [self _endConnection:connection];
5871 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5872 [self _endConnection:connection];
5875 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5876 NSMutableURLRequest *request = [NSMutableURLRequest
5877 requestWithURL:[NSURL URLWithString:href]
5878 cachePolicy:NSURLRequestUseProtocolCachePolicy
5879 timeoutInterval:20.0
5882 [request setHTTPMethod:method];
5884 if (Machine_ != NULL)
5885 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5886 if (UniqueID_ != nil)
5887 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5890 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5892 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5895 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5896 NSString *context([sheet context]);
5898 if ([context isEqualToString:@"source"]) {
5901 NSString *href = [[sheet textField] text];
5903 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5905 if (![href hasSuffix:@"/"])
5906 href_ = [href stringByAppendingString:@"/"];
5909 href_ = [href_ retain];
5911 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
5912 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5913 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5914 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5918 hud_ = [[delegate_ addProgressHUD] retain];
5919 [hud_ setText:UCLocalize("VERIFYING_URL")];
5929 } else if ([context isEqualToString:@"trivial"])
5931 else if ([context isEqualToString:@"urlerror"])
5933 else if ([context isEqualToString:@"warning"]) {
5952 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5953 if ((self = [super initWithBook:book]) != nil) {
5954 database_ = database;
5955 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5957 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5958 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5959 [list_ setShouldHideHeaderInShortLists:NO];
5961 [self addSubview:list_];
5962 [list_ setDataSource:self];
5964 UITableColumn *column = [[UITableColumn alloc]
5965 initWithTitle:UCLocalize("NAME")
5967 width:[self frame].size.width
5970 UITable *table = [list_ table];
5971 [table setSeparatorStyle:1];
5972 [table addTableColumn:column];
5973 [table setDelegate:self];
5977 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5978 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5982 - (void) reloadData {
5984 if (!list.ReadMainList())
5987 [sources_ removeAllObjects];
5988 [sources_ addObjectsFromArray:[database_ sources]];
5990 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5993 int count([sources_ count]);
5994 for (offset_ = 0; offset_ != count; ++offset_) {
5995 Source *source = [sources_ objectAtIndex:offset_];
5996 if ([source record] == nil)
6003 - (void) resetViewAnimated:(BOOL)animated {
6004 [list_ resetViewAnimated:animated];
6007 - (void) _leftButtonClicked {
6008 /*[book_ pushPage:[[[AddSourceView alloc]
6013 UIActionSheet *sheet = [[[UIActionSheet alloc]
6014 initWithTitle:UCLocalize("ENTER_APT_URL")
6015 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_SOURCE"), UCLocalize("CANCEL"), nil]
6016 defaultButtonIndex:0
6021 [sheet setNumberOfRows:1];
6023 [sheet addTextFieldWithValue:@"http://" label:@""];
6025 UITextInputTraits *traits = [[sheet textField] textInputTraits];
6026 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6027 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6028 [traits setKeyboardType:UIKeyboardTypeURL];
6029 // XXX: UIReturnKeyDone
6030 [traits setReturnKeyType:UIReturnKeyNext];
6032 [sheet popupAlertAnimated:YES];
6035 - (void) _rightButtonClicked {
6036 UITable *table = [list_ table];
6037 BOOL editing = [table isRowDeletionEnabled];
6038 [table enableRowDeletion:!editing animated:YES];
6039 [book_ reloadButtonsForPage:self];
6042 - (NSString *) title {
6043 return UCLocalize("SOURCES");
6046 - (NSString *) leftButtonTitle {
6047 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("ADD") : nil;
6050 - (id) rightButtonTitle {
6051 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("DONE") : UCLocalize("EDIT");
6054 - (UINavigationButtonStyle) rightButtonStyle {
6055 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6061 /* Installed View {{{ */
6062 @interface InstalledView : RVPage {
6063 _transient Database *database_;
6064 FilteredPackageTable *packages_;
6068 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6072 @implementation InstalledView
6075 [packages_ release];
6079 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6080 if ((self = [super initWithBook:book]) != nil) {
6081 database_ = database;
6083 packages_ = [[FilteredPackageTable alloc]
6087 filter:@selector(isInstalledAndVisible:)
6088 with:[NSNumber numberWithBool:YES]
6091 [self addSubview:packages_];
6093 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6094 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6098 - (void) resetViewAnimated:(BOOL)animated {
6099 [packages_ resetViewAnimated:animated];
6102 - (void) reloadData {
6103 [packages_ reloadData];
6106 - (void) _rightButtonClicked {
6107 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6108 [packages_ reloadData];
6110 [book_ reloadButtonsForPage:self];
6113 - (NSString *) title {
6114 return UCLocalize("INSTALLED");
6117 - (NSString *) backButtonTitle {
6118 return UCLocalize("PACKAGES");
6121 - (id) rightButtonTitle {
6122 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE");
6125 - (UINavigationButtonStyle) rightButtonStyle {
6126 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6129 - (void) setDelegate:(id)delegate {
6130 [super setDelegate:delegate];
6131 [packages_ setDelegate:delegate];
6138 @interface HomeView : CydiaBrowserView {
6143 @implementation HomeView
6145 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6146 NSString *context([sheet context]);
6148 if ([context isEqualToString:@"about"])
6151 [super alertSheet:sheet buttonClicked:button];
6154 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6155 [super _setMoreHeaders:request];
6157 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6160 - (void) _leftButtonClicked {
6161 UIActionSheet *sheet = [[[UIActionSheet alloc]
6162 initWithTitle:UCLocalize("ABOUT_CYDIA")
6163 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
6164 defaultButtonIndex:0
6170 @"Copyright (C) 2008-2009\n"
6171 "Jay Freeman (saurik)\n"
6172 "saurik@saurik.com\n"
6173 "http://www.saurik.com/\n"
6176 "http://www.theokorigroup.com/\n"
6178 "College of Creative Studies,\n"
6179 "University of California,\n"
6181 "http://www.ccs.ucsb.edu/"
6184 [sheet popupAlertAnimated:YES];
6187 - (NSString *) leftButtonTitle {
6188 return UCLocalize("ABOUT");
6193 /* Manage View {{{ */
6194 @interface ManageView : CydiaBrowserView {
6199 @implementation ManageView
6201 - (NSString *) title {
6202 return UCLocalize("MANAGE");
6205 - (void) _leftButtonClicked {
6206 [delegate_ askForSettings];
6207 [delegate_ updateData];
6210 - (NSString *) leftButtonTitle {
6211 return UCLocalize("SETTINGS");
6215 - (id) _rightButtonTitle {
6216 return Queuing_ ? UCLocalize("QUEUE") : nil;
6219 - (UINavigationButtonStyle) rightButtonStyle {
6220 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6223 - (void) _rightButtonClicked {
6228 - (bool) isLoading {
6235 /* Cydia Book {{{ */
6236 @interface CYBook : RVBook <
6239 _transient Database *database_;
6240 UINavigationBar *overlay_;
6241 UINavigationBar *underlay_;
6242 UIProgressIndicator *indicator_;
6243 UITextLabel *prompt_;
6244 UIProgressBar *progress_;
6245 UINavigationButton *cancel_;
6249 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
6255 @implementation CYBook
6259 [indicator_ release];
6261 [progress_ release];
6266 - (NSString *) getTitleForPage:(RVPage *)page {
6267 return [super getTitleForPage:page];
6275 [UIView beginAnimations:nil context:NULL];
6277 CGRect ovrframe = [overlay_ frame];
6278 ovrframe.origin.y = 0;
6279 [overlay_ setFrame:ovrframe];
6281 CGRect barframe = [navbar_ frame];
6282 barframe.origin.y += ovrframe.size.height;
6283 [navbar_ setFrame:barframe];
6285 CGRect trnframe = [transition_ frame];
6286 trnframe.origin.y += ovrframe.size.height;
6287 trnframe.size.height -= ovrframe.size.height;
6288 [transition_ setFrame:trnframe];
6290 [UIView endAnimations];
6292 [indicator_ startAnimation];
6293 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6294 [progress_ setProgress:0];
6297 [overlay_ addSubview:cancel_];
6300 detachNewThreadSelector:@selector(_update)
6306 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6307 NSString *context([sheet context]);
6309 if ([context isEqualToString:@"refresh"])
6316 [indicator_ stopAnimation];
6318 [UIView beginAnimations:nil context:NULL];
6320 CGRect ovrframe = [overlay_ frame];
6321 ovrframe.origin.y = -ovrframe.size.height;
6322 [overlay_ setFrame:ovrframe];
6324 CGRect barframe = [navbar_ frame];
6325 barframe.origin.y -= ovrframe.size.height;
6326 [navbar_ setFrame:barframe];
6328 CGRect trnframe = [transition_ frame];
6329 trnframe.origin.y -= ovrframe.size.height;
6330 trnframe.size.height += ovrframe.size.height;
6331 [transition_ setFrame:trnframe];
6333 [UIView commitAnimations];
6335 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6338 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6339 if ((self = [super initWithFrame:frame]) != nil) {
6340 database_ = database;
6342 CGRect ovrrect([navbar_ bounds]);
6343 ovrrect.size.height = [UINavigationBar defaultSize].height;
6344 ovrrect.origin.y = -ovrrect.size.height;
6346 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6347 [self addSubview:overlay_];
6349 ovrrect.origin.y = frame.size.height;
6350 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6351 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6352 [self addSubview:underlay_];
6354 [overlay_ setBarStyle:1];
6355 [underlay_ setBarStyle:1];
6357 int barstyle([overlay_ _barStyle:NO]);
6358 bool ugly(barstyle == 0);
6360 UIProgressIndicatorStyle style = ugly ?
6361 UIProgressIndicatorStyleMediumBrown :
6362 UIProgressIndicatorStyleMediumWhite;
6364 CGSize indsize([UIProgressIndicator defaultSizeForStyle:style]);
6365 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6366 CGRect indrect = {{indoffset, indoffset}, indsize};
6368 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6369 [indicator_ setStyle:style];
6370 [overlay_ addSubview:indicator_];
6372 CGSize prmsize = {215, indsize.height + 4};
6375 indoffset * 2 + indsize.width,
6376 unsigned(ovrrect.size.height - prmsize.height) / 2 - 1
6379 UIFont *font([UIFont systemFontOfSize:15]);
6381 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6383 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6384 [prompt_ setBackgroundColor:[UIColor clearColor]];
6385 [prompt_ setFont:font];
6387 [overlay_ addSubview:prompt_];
6389 CGSize prgsize = {75, 100};
6392 ovrrect.size.width - prgsize.width - 10,
6393 (ovrrect.size.height - prgsize.height) / 2
6396 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6397 [progress_ setStyle:0];
6398 [overlay_ addSubview:progress_];
6400 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6401 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6403 CGRect frame = [cancel_ frame];
6404 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6405 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6406 [cancel_ setFrame:frame];
6408 [cancel_ setBarStyle:barstyle];
6412 - (void) _onCancel {
6414 [cancel_ removeFromSuperview];
6417 - (void) _update { _pooled
6419 status.setDelegate(self);
6420 [database_ updateWithStatus:status];
6423 performSelectorOnMainThread:@selector(_update_)
6429 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6430 [prompt_ setText:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6434 UIActionSheet *sheet = [[[UIActionSheet alloc]
6435 initWithTitle:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), UCLocalize("REFRESH")]
6436 buttons:[NSArray arrayWithObjects:
6439 defaultButtonIndex:0
6444 [sheet setBodyText:error];
6445 [sheet popupAlertAnimated:YES];
6447 [self reloadButtons];
6450 - (void) setProgressTitle:(NSString *)title {
6452 performSelectorOnMainThread:@selector(_setProgressTitle:)
6458 - (void) setProgressPercent:(float)percent {
6460 performSelectorOnMainThread:@selector(_setProgressPercent:)
6461 withObject:[NSNumber numberWithFloat:percent]
6466 - (void) startProgress {
6469 - (void) addProgressOutput:(NSString *)output {
6471 performSelectorOnMainThread:@selector(_addProgressOutput:)
6477 - (bool) isCancelling:(size_t)received {
6481 - (void) _setProgressTitle:(NSString *)title {
6482 [prompt_ setText:title];
6485 - (void) _setProgressPercent:(NSNumber *)percent {
6486 [progress_ setProgress:[percent floatValue]];
6489 - (void) _addProgressOutput:(NSString *)output {
6494 /* Cydia:// Protocol {{{ */
6495 @interface CydiaURLProtocol : NSURLProtocol {
6500 @implementation CydiaURLProtocol
6502 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6503 NSURL *url([request URL]);
6506 NSString *scheme([[url scheme] lowercaseString]);
6507 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6512 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6516 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6517 id<NSURLProtocolClient> client([self client]);
6519 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6521 NSData *data(UIImagePNGRepresentation(icon));
6523 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6524 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6525 [client URLProtocol:self didLoadData:data];
6526 [client URLProtocolDidFinishLoading:self];
6530 - (void) startLoading {
6531 id<NSURLProtocolClient> client([self client]);
6532 NSURLRequest *request([self request]);
6534 NSURL *url([request URL]);
6535 NSString *href([url absoluteString]);
6537 NSString *path([href substringFromIndex:8]);
6538 NSRange slash([path rangeOfString:@"/"]);
6541 if (slash.location == NSNotFound) {
6545 command = [path substringToIndex:slash.location];
6546 path = [path substringFromIndex:(slash.location + 1)];
6549 Database *database([Database sharedInstance]);
6551 if ([command isEqualToString:@"package-icon"]) {
6554 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6555 Package *package([database packageWithName:path]);
6558 UIImage *icon([package icon]);
6559 [self _returnPNGWithImage:icon forRequest:request];
6560 } else if ([command isEqualToString:@"source-icon"]) {
6563 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6564 NSString *source(Simplify(path));
6565 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6567 icon = [UIImage applicationImageNamed:@"unknown.png"];
6568 [self _returnPNGWithImage:icon forRequest:request];
6569 } else if ([command isEqualToString:@"uikit-image"]) {
6572 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6573 UIImage *icon(_UIImageWithName(path));
6574 [self _returnPNGWithImage:icon forRequest:request];
6575 } else if ([command isEqualToString:@"section-icon"]) {
6578 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6579 NSString *section(Simplify(path));
6580 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6582 icon = [UIImage applicationImageNamed:@"unknown.png"];
6583 [self _returnPNGWithImage:icon forRequest:request];
6585 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6589 - (void) stopLoading {
6595 /* Sections View {{{ */
6596 @interface SectionsView : RVPage {
6597 _transient Database *database_;
6598 NSMutableArray *sections_;
6599 NSMutableArray *filtered_;
6600 UITransitionView *transition_;
6606 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6607 - (void) reloadData;
6612 @implementation SectionsView
6615 [list_ setDataSource:nil];
6616 [list_ setDelegate:nil];
6618 [sections_ release];
6619 [filtered_ release];
6620 [transition_ release];
6622 [accessory_ release];
6626 - (int) numberOfRowsInTable:(UITable *)table {
6627 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6630 - (float) table:(UITable *)table heightForRow:(int)row {
6634 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6636 reusing = [[[SectionCell alloc] init] autorelease];
6637 [(SectionCell *)reusing setSection:(editing_ ?
6638 [sections_ objectAtIndex:row] :
6639 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6640 ) editing:editing_];
6644 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6648 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6652 - (void) tableRowSelected:(NSNotification *)notification {
6653 int row = [[notification object] selectedRow];
6664 title = UCLocalize("ALL_PACKAGES");
6666 section = [filtered_ objectAtIndex:(row - 1)];
6667 name = [section name];
6670 name = [NSString stringWithString:name];
6671 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6674 title = UCLocalize("NO_SECTION");
6678 PackageTable *table = [[[FilteredPackageTable alloc]
6682 filter:@selector(isVisibleInSection:)
6686 [table setDelegate:delegate_];
6688 [book_ pushPage:table];
6691 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6692 if ((self = [super initWithBook:book]) != nil) {
6693 database_ = database;
6695 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6696 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6698 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6699 [self addSubview:transition_];
6701 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6702 [transition_ transition:0 toView:list_];
6704 UITableColumn *column = [[[UITableColumn alloc]
6705 initWithTitle:UCLocalize("NAME")
6707 width:[self frame].size.width
6710 [list_ setDataSource:self];
6711 [list_ setSeparatorStyle:1];
6712 [list_ addTableColumn:column];
6713 [list_ setDelegate:self];
6714 [list_ setReusesTableCells:YES];
6718 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6719 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6723 - (void) reloadData {
6724 NSArray *packages = [database_ packages];
6726 [sections_ removeAllObjects];
6727 [filtered_ removeAllObjects];
6730 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6731 SectionMap sections;
6732 sections.resize(64);
6734 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6738 for (Package *package in packages) {
6739 NSString *name([package section]);
6740 NSString *key(name == nil ? @"" : name);
6745 _profile(SectionsView$reloadData$Section)
6746 section = §ions[key];
6747 if (*section == nil) {
6748 _profile(SectionsView$reloadData$Section$Allocate)
6749 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6754 [*section addToCount];
6756 _profile(SectionsView$reloadData$Filter)
6757 if (![package valid] || ![package visible])
6761 [*section addToRow];
6765 _profile(SectionsView$reloadData$Section)
6766 section = [sections objectForKey:key];
6767 if (section == nil) {
6768 _profile(SectionsView$reloadData$Section$Allocate)
6769 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6770 [sections setObject:section forKey:key];
6775 [section addToCount];
6777 _profile(SectionsView$reloadData$Filter)
6778 if (![package valid] || ![package visible])
6788 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6789 [sections_ addObject:i->second];
6791 [sections_ addObjectsFromArray:[sections allValues]];
6794 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6796 for (Section *section in sections_) {
6797 size_t count([section row]);
6801 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6802 [section setCount:count];
6803 [filtered_ addObject:section];
6810 - (void) resetView {
6812 [self _rightButtonClicked];
6815 - (void) resetViewAnimated:(BOOL)animated {
6816 [list_ resetViewAnimated:animated];
6819 - (void) _rightButtonClicked {
6820 if ((editing_ = !editing_))
6823 [delegate_ updateData];
6824 [book_ reloadTitleForPage:self];
6825 [book_ reloadButtonsForPage:self];
6828 - (NSString *) title {
6829 return editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS");
6832 - (NSString *) backButtonTitle {
6833 return UCLocalize("SECTIONS");
6836 - (id) rightButtonTitle {
6837 return [sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT");
6840 - (UINavigationButtonStyle) rightButtonStyle {
6841 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6844 - (UIView *) accessoryView {
6850 /* Changes View {{{ */
6851 @interface ChangesView : RVPage {
6852 _transient Database *database_;
6853 NSMutableArray *packages_;
6854 NSMutableArray *sections_;
6859 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6860 - (void) reloadData;
6864 @implementation ChangesView
6867 [list_ setDelegate:nil];
6868 [list_ setDataSource:nil];
6870 [packages_ release];
6871 [sections_ release];
6876 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6877 NSInteger count([sections_ count]);
6878 return count == 0 ? 1 : count;
6881 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6882 if ([sections_ count] == 0)
6884 return [[sections_ objectAtIndex:section] name];
6887 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6888 if ([sections_ count] == 0)
6890 return [[sections_ objectAtIndex:section] count];
6893 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6894 Section *section([sections_ objectAtIndex:[path section]]);
6895 NSInteger row([path row]);
6896 return [packages_ objectAtIndex:([section row] + row)];
6899 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6900 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
6902 cell = [[[PackageCell alloc] init] autorelease];
6903 [cell setPackage:[self packageAtIndexPath:path]];
6907 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6909 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6912 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6913 Package *package([self packageAtIndexPath:path]);
6914 PackageView *view([delegate_ packageView]);
6915 [view setDelegate:delegate_];
6916 [view setPackage:package];
6917 [book_ pushPage:view];
6921 - (void) _leftButtonClicked {
6922 [(CYBook *)book_ update];
6923 [self reloadButtons];
6926 - (void) _rightButtonClicked {
6927 [delegate_ distUpgrade];
6930 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6931 if ((self = [super initWithBook:book]) != nil) {
6932 database_ = database;
6934 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6935 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6937 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
6938 [self addSubview:list_];
6940 //XXX:[list_ setShouldHideHeaderInShortLists:NO];
6941 [list_ setDataSource:self];
6942 [list_ setDelegate:self];
6943 //[list_ setSectionListStyle:1];
6947 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6948 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6952 - (void) reloadData {
6953 NSArray *packages = [database_ packages];
6955 [packages_ removeAllObjects];
6956 [sections_ removeAllObjects];
6959 for (Package *package in packages)
6961 [package uninstalled] && [package valid] && [package visible] ||
6962 [package upgradableAndEssential:YES]
6964 [packages_ addObject:package];
6967 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6970 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6971 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6972 Section *section = nil;
6976 bool unseens = false;
6978 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6980 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6981 Package *package = [packages_ objectAtIndex:offset];
6983 BOOL uae = [package upgradableAndEssential:YES];
6989 _profile(ChangesView$reloadData$Remember)
6990 seen = [package seen];
6993 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6998 name = UCLocalize("UNKNOWN");
7000 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7004 _profile(ChangesView$reloadData$Allocate)
7005 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7006 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7007 [sections_ addObject:section];
7011 [section addToCount];
7012 } else if ([package ignored])
7013 [ignored addToCount];
7016 [upgradable addToCount];
7021 CFRelease(formatter);
7024 Section *last = [sections_ lastObject];
7025 size_t count = [last count];
7026 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7027 [sections_ removeLastObject];
7030 if ([ignored count] != 0)
7031 [sections_ insertObject:ignored atIndex:0];
7033 [sections_ insertObject:upgradable atIndex:0];
7036 [self reloadButtons];
7039 - (void) resetViewAnimated:(BOOL)animated {
7040 [list_ resetViewAnimated:animated];
7043 - (NSString *) leftButtonTitle {
7044 return [(CYBook *)book_ updating] ? nil : UCLocalize("REFRESH");
7047 - (id) rightButtonTitle {
7048 return upgrades_ == 0 ? nil : [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
7051 - (NSString *) title {
7052 return UCLocalize("CHANGES");
7057 /* Search View {{{ */
7058 @protocol SearchViewDelegate
7059 - (void) showKeyboard:(BOOL)show;
7062 @interface SearchView : RVPage {
7064 UISearchField *field_;
7065 FilteredPackageTable *table_;
7070 - (id) initWithBook:(RVBook *)book database:(Database *)database;
7071 - (void) reloadData;
7075 @implementation SearchView
7078 [field_ setDelegate:nil];
7080 [accessory_ release];
7087 - (void) _showKeyboard:(BOOL)show {
7088 CGSize keysize = [UIKeyboard defaultSize];
7089 CGRect keydown = [book_ pageBounds];
7090 CGRect keyup = keydown;
7091 keyup.size.height -= keysize.height - ButtonBarHeight_;
7093 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
7095 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
7096 [animation setSignificantRectFields:8];
7099 [animation setStartFrame:keydown];
7100 [animation setEndFrame:keyup];
7102 [animation setStartFrame:keyup];
7103 [animation setEndFrame:keydown];
7106 UIAnimator *animator = [UIAnimator sharedAnimator];
7109 addAnimations:[NSArray arrayWithObjects:animation, nil]
7110 withDuration:(KeyboardTime_ - delay)
7115 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
7117 [delegate_ showKeyboard:show];
7120 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
7121 [self _showKeyboard:YES];
7124 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
7125 [self _showKeyboard:NO];
7128 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
7130 NSString *text([field_ text]);
7131 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
7137 - (void) textFieldClearButtonPressed:(UITextField *)field {
7141 - (void) keyboardInputShouldDelete:(id)input {
7145 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
7146 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
7150 [field_ resignFirstResponder];
7155 - (id) initWithBook:(RVBook *)book database:(Database *)database {
7156 if ((self = [super initWithBook:book]) != nil) {
7157 CGRect pageBounds = [book_ pageBounds];
7159 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
7160 CGColor dimmed(space_, 0, 0, 0, 0.5);
7161 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
7163 table_ = [[FilteredPackageTable alloc]
7167 filter:@selector(isUnfilteredAndSearchedForBy:)
7171 [table_ setShouldHideHeaderInShortLists:NO];
7172 [self addSubview:table_];
7174 CGRect cnfrect = {{7, 38}, {17, 18}};
7181 area.size.width = [self bounds].size.width - area.origin.x * 2;
7182 area.size.height = [UISearchField defaultHeight];
7184 field_ = [[UISearchField alloc] initWithFrame:area];
7186 UIFont *font = [UIFont systemFontOfSize:16];
7187 [field_ setFont:font];
7189 [field_ setPlaceholder:UCLocalize("SEARCH_EX")];
7190 [field_ setDelegate:self];
7192 [field_ setPaddingTop:5];
7194 UITextInputTraits *traits([field_ textInputTraits]);
7195 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7196 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7197 [traits setReturnKeyType:UIReturnKeySearch];
7199 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
7201 accessory_ = [[UIView alloc] initWithFrame:accrect];
7202 [accessory_ addSubview:field_];
7204 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7205 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7209 - (void) resetViewAnimated:(BOOL)animated {
7210 [table_ resetViewAnimated:animated];
7213 - (void) _reloadData {
7216 - (void) reloadData {
7217 [table_ setObject:[field_ text]];
7218 _profile(SearchView$reloadData)
7219 [table_ reloadData];
7222 [table_ resetCursor];
7225 - (UIView *) accessoryView {
7229 - (NSString *) title {
7233 - (NSString *) backButtonTitle {
7234 return UCLocalize("SEARCH");
7237 - (void) setDelegate:(id)delegate {
7238 [table_ setDelegate:delegate];
7239 [super setDelegate:delegate];
7244 /* Settings View {{{ */
7245 @interface SettingsView : RVPage {
7246 _transient Database *database_;
7249 UIPreferencesTable *table_;
7250 _UISwitchSlider *subscribedSwitch_;
7251 _UISwitchSlider *ignoredSwitch_;
7252 UIPreferencesControlTableCell *subscribedCell_;
7253 UIPreferencesControlTableCell *ignoredCell_;
7256 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7260 @implementation SettingsView
7263 [table_ setDataSource:nil];
7266 if (package_ != nil)
7269 [subscribedSwitch_ release];
7270 [ignoredSwitch_ release];
7271 [subscribedCell_ release];
7272 [ignoredCell_ release];
7276 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7277 if (package_ == nil)
7283 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7284 if (package_ == nil)
7297 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7298 if (package_ == nil)
7311 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7312 if (package_ == nil)
7325 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7326 if (package_ == nil)
7329 _UISwitchSlider *slider([cell control]);
7330 BOOL value([slider value] != 0);
7331 NSMutableDictionary *metadata([package_ metadata]);
7334 if (NSNumber *number = [metadata objectForKey:key])
7335 before = [number boolValue];
7339 if (value != before) {
7340 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7342 [delegate_ updateData];
7346 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7347 [self onSomething:cell withKey:@"IsSubscribed"];
7350 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7351 [self onSomething:cell withKey:@"IsIgnored"];
7354 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7355 if (package_ == nil)
7359 case 0: switch (row) {
7361 return subscribedCell_;
7363 return ignoredCell_;
7367 case 1: switch (row) {
7369 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7370 [cell setShowSelection:NO];
7371 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7384 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7385 if ((self = [super initWithBook:book])) {
7386 database_ = database;
7387 name_ = [package retain];
7389 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7390 [self addSubview:table_];
7392 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7393 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
7395 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7396 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
7398 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7399 [subscribedCell_ setShowSelection:NO];
7400 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7401 [subscribedCell_ setControl:subscribedSwitch_];
7403 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7404 [ignoredCell_ setShowSelection:NO];
7405 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7406 [ignoredCell_ setControl:ignoredSwitch_];
7408 [table_ setDataSource:self];
7413 - (void) resetViewAnimated:(BOOL)animated {
7414 [table_ resetViewAnimated:animated];
7417 - (void) reloadData {
7418 if (package_ != nil)
7419 [package_ autorelease];
7420 package_ = [database_ packageWithName:name_];
7421 if (package_ != nil) {
7423 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7424 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7427 [table_ reloadData];
7430 - (NSString *) title {
7431 return UCLocalize("SETTINGS");
7437 /* Signature View {{{ */
7438 @interface SignatureView : CydiaBrowserView {
7439 _transient Database *database_;
7443 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7447 @implementation SignatureView
7454 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7456 [super webView:sender didClearWindowObject:window forFrame:frame];
7459 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7460 if ((self = [super initWithBook:book]) != nil) {
7461 database_ = database;
7462 package_ = [package retain];
7467 - (void) resetViewAnimated:(BOOL)animated {
7470 - (void) reloadData {
7471 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7477 @interface Cydia : UIApplication <
7478 ConfirmationViewDelegate,
7479 ProgressViewDelegate,
7488 UIToolbar *toolbar_;
7492 NSMutableArray *essential_;
7493 NSMutableArray *broken_;
7495 Database *database_;
7496 ProgressView *progress_;
7500 UIKeyboard *keyboard_;
7501 UIProgressHUD *hud_;
7503 SectionsView *sections_;
7504 ChangesView *changes_;
7505 ManageView *manage_;
7506 SearchView *search_;
7508 #if RecyclePackageViews
7509 NSMutableArray *details_;
7513 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7514 - (void) setPage:(RVPage *)page;
7518 static _finline void _setHomePage(Cydia *self) {
7519 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeView class]]];
7522 @implementation Cydia
7525 if ([broken_ count] != 0) {
7526 int count = [broken_ count];
7528 UIActionSheet *sheet = [[[UIActionSheet alloc]
7529 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7530 buttons:[NSArray arrayWithObjects:
7531 UCLocalize("FORCIBLY_CLEAR"),
7532 UCLocalize("TEMPORARY_IGNORE"),
7534 defaultButtonIndex:0
7539 [sheet setBodyText:UCLocalize("HALFINSTALLED_PACKAGE_EX")];
7540 [sheet popupAlertAnimated:YES];
7541 } else if (!Ignored_ && [essential_ count] != 0) {
7542 int count = [essential_ count];
7544 UIActionSheet *sheet = [[[UIActionSheet alloc]
7545 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7546 buttons:[NSArray arrayWithObjects:
7547 UCLocalize("UPGRADE_ESSENTIAL"),
7548 UCLocalize("COMPLETE_UPGRADE"),
7549 UCLocalize("TEMPORARY_IGNORE"),
7551 defaultButtonIndex:0
7556 [sheet setBodyText:UCLocalize("ESSENTIAL_UPGRADE_EX")];
7557 [sheet popupAlertAnimated:YES];
7561 - (void) _saveConfig {
7564 NSString *error(nil);
7565 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7567 NSError *error(nil);
7568 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7569 NSLog(@"failure to save metadata data: %@", error);
7572 NSLog(@"failure to serialize metadata: %@", error);
7580 - (void) _updateData {
7583 /* XXX: this is just stupid */
7584 if (tag_ != 2 && sections_ != nil)
7585 [sections_ reloadData];
7586 if (tag_ != 3 && changes_ != nil)
7587 [changes_ reloadData];
7588 if (tag_ != 5 && search_ != nil)
7589 [search_ reloadData];
7594 - (void) _reloadData {
7597 static bool loaded(false);
7598 UIProgressHUD *hud([self addProgressHUD]);
7599 [hud setText:(loaded ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7601 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7604 [self removeProgressHUD:hud];
7608 [essential_ removeAllObjects];
7609 [broken_ removeAllObjects];
7611 NSArray *packages([database_ packages]);
7612 for (Package *package in packages) {
7614 [broken_ addObject:package];
7615 if ([package upgradableAndEssential:NO]) {
7616 if ([package essential])
7617 [essential_ addObject:package];
7623 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7624 [toolbar_ setBadgeValue:badge forButton:3];
7625 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7626 [toolbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7627 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7628 [self setApplicationBadge:badge];
7630 [self setApplicationBadgeString:badge];
7632 [toolbar_ setBadgeValue:nil forButton:3];
7633 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7634 [toolbar_ setBadgeAnimated:NO forButton:3];
7635 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7636 [self removeApplicationBadge];
7637 else // XXX: maybe use setApplicationBadgeString also?
7638 [self setApplicationIconBadgeNumber:0];
7642 [toolbar_ setBadgeValue:nil forButton:4];
7646 if (loaded || ManualRefresh) loaded:
7651 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7652 NSTimeInterval interval([update timeIntervalSinceNow]);
7653 if (interval <= 0 && interval > -(15*60))
7661 - (void) updateData {
7662 [database_ setVisible];
7671 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
7672 _assert(file != NULL);
7674 for (NSString *key in [Sources_ allKeys]) {
7675 NSDictionary *source([Sources_ objectForKey:key]);
7677 fprintf(file, "%s %s %s\n",
7678 [[source objectForKey:@"Type"] UTF8String],
7679 [[source objectForKey:@"URI"] UTF8String],
7680 [[source objectForKey:@"Distribution"] UTF8String]
7689 detachNewThreadSelector:@selector(update_)
7692 title:UCLocalize("UPDATING_SOURCES")
7696 - (void) reloadData {
7697 @synchronized (self) {
7698 if (confirm_ == nil)
7704 pkgProblemResolver *resolver = [database_ resolver];
7706 resolver->InstallProtect();
7707 if (!resolver->Resolve(true))
7711 - (void) popUpBook:(RVBook *)book {
7712 [underlay_ popSubview:book];
7715 - (CGRect) popUpBounds {
7716 return [underlay_ bounds];
7720 if (![database_ prepare])
7723 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7724 [confirm_ setDelegate:self];
7726 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7727 [page setDelegate:self];
7729 [confirm_ setPage:page];
7730 [self popUpBook:confirm_];
7736 @synchronized (self) {
7741 - (void) clearPackage:(Package *)package {
7742 @synchronized (self) {
7749 - (void) installPackage:(Package *)package {
7750 @synchronized (self) {
7757 - (void) removePackage:(Package *)package {
7758 @synchronized (self) {
7765 - (void) distUpgrade {
7766 @synchronized (self) {
7767 if (![database_ upgrade])
7774 [self slideUp:[[[UIActionSheet alloc]
7776 buttons:[NSArray arrayWithObjects:UCLocalize("CONTINUE_QUEUING"), UCLocalize("CANCEL_CLEAR"), nil]
7777 defaultButtonIndex:1
7784 @synchronized (self) {
7787 if (confirm_ != nil) {
7795 [overlay_ removeFromSuperview];
7799 detachNewThreadSelector:@selector(perform)
7802 title:UCLocalize("RUNNING")
7806 - (void) progressViewIsComplete:(ProgressView *)progress {
7807 if (confirm_ != nil) {
7808 [underlay_ addSubview:overlay_];
7809 [confirm_ popFromSuperviewAnimated:NO];
7815 - (void) setPage:(RVPage *)page {
7816 [page resetViewAnimated:NO];
7817 [page setDelegate:self];
7818 [book_ setPage:page];
7821 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7822 CydiaBrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7823 [browser loadURL:url];
7827 - (SectionsView *) sectionsView {
7828 if (sections_ == nil)
7829 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7833 - (void) buttonBarItemTapped:(id)sender {
7834 unsigned tag = [sender tag];
7836 [book_ resetViewAnimated:YES];
7838 } else if (tag_ == 2)
7839 [[self sectionsView] resetView];
7842 case 1: _setHomePage(self); break;
7844 case 2: [self setPage:[self sectionsView]]; break;
7845 case 3: [self setPage:changes_]; break;
7846 case 4: [self setPage:manage_]; break;
7847 case 5: [self setPage:search_]; break;
7855 - (void) askForSettings {
7856 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
7858 CYActionSheet *role([[[CYActionSheet alloc]
7859 initWithTitle:UCLocalize("WHO_ARE_YOU")
7860 buttons:[NSArray arrayWithObjects:
7861 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
7862 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
7863 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
7865 defaultButtonIndex:-1
7868 [role setBodyText:UCLocalize("ROLE_EX")];
7870 int button([role yieldToPopupAlertAnimated:YES]);
7873 case 1: Role_ = @"User"; break;
7874 case 2: Role_ = @"Hacker"; break;
7875 case 3: Role_ = @"Developer"; break;
7880 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7884 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7891 - (void) setPackageView:(PackageView *)view {
7893 [view setPackage:nil];
7894 #if RecyclePackageViews
7895 if ([details_ count] < 3)
7896 [details_ addObject:view];
7901 - (PackageView *) _packageView {
7902 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7905 - (PackageView *) packageView {
7906 #if RecyclePackageViews
7908 size_t count([details_ count]);
7911 view = [self _packageView];
7913 [details_ addObject:[self _packageView]];
7915 view = [[[details_ lastObject] retain] autorelease];
7916 [details_ removeLastObject];
7923 return [self _packageView];
7927 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7928 NSString *context([sheet context]);
7930 if ([context isEqualToString:@"missing"])
7932 else if ([context isEqualToString:@"cancel"]) {
7949 @synchronized (self) {
7954 [toolbar_ setBadgeValue:UCLocalize("Q_D") forButton:4];
7958 if (confirm_ != nil) {
7963 } else if ([context isEqualToString:@"fixhalf"]) {
7966 @synchronized (self) {
7967 for (Package *broken in broken_) {
7970 NSString *id = [broken id];
7971 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7972 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7973 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7974 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7983 [broken_ removeAllObjects];
7991 } else if ([context isEqualToString:@"upgrade"]) {
7994 @synchronized (self) {
7995 for (Package *essential in essential_)
7996 [essential install];
8018 - (void) system:(NSString *)command { _pooled
8019 system([command UTF8String]);
8022 - (void) applicationWillSuspend {
8024 [super applicationWillSuspend];
8027 - (void) applicationSuspend:(__GSEvent *)event {
8028 if (hud_ == nil && ![progress_ isRunning])
8029 [super applicationSuspend:event];
8032 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8034 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8037 - (void) _setSuspended:(BOOL)value {
8039 [super _setSuspended:value];
8042 - (UIProgressHUD *) addProgressHUD {
8043 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8044 [window_ setUserInteractionEnabled:NO];
8046 [progress_ addSubview:hud];
8050 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8052 [hud removeFromSuperview];
8053 [window_ setUserInteractionEnabled:YES];
8056 - (RVPage *) pageForPackage:(NSString *)name {
8057 if (Package *package = [database_ packageWithName:name]) {
8058 PackageView *view([self packageView]);
8059 [view setPackage:package];
8062 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8063 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8064 return [self _pageForURL:url withClass:[CydiaBrowserView class]];
8068 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8072 NSString *href([url absoluteString]);
8073 if ([href hasPrefix:@"apptapp://package/"])
8074 return [self pageForPackage:[href substringFromIndex:18]];
8076 NSString *scheme([[url scheme] lowercaseString]);
8077 if (![scheme isEqualToString:@"cydia"])
8079 NSString *path([url absoluteString]);
8080 if ([path length] < 8)
8082 path = [path substringFromIndex:8];
8083 if (![path hasPrefix:@"/"])
8084 path = [@"/" stringByAppendingString:path];
8086 if ([path isEqualToString:@"/add-source"])
8087 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8088 else if ([path isEqualToString:@"/storage"])
8089 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CydiaBrowserView class]];
8090 else if ([path isEqualToString:@"/sources"])
8091 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8092 else if ([path isEqualToString:@"/packages"])
8093 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8094 else if ([path hasPrefix:@"/url/"])
8095 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CydiaBrowserView class]];
8096 else if ([path hasPrefix:@"/launch/"])
8097 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8098 else if ([path hasPrefix:@"/package-settings/"])
8099 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8100 else if ([path hasPrefix:@"/package-signature/"])
8101 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8102 else if ([path hasPrefix:@"/package/"])
8103 return [self pageForPackage:[path substringFromIndex:9]];
8104 else if ([path hasPrefix:@"/files/"]) {
8105 NSString *name = [path substringFromIndex:7];
8107 if (Package *package = [database_ packageWithName:name]) {
8108 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8109 [files setPackage:package];
8117 - (void) applicationOpenURL:(NSURL *)url {
8118 [super applicationOpenURL:url];
8120 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8121 [self setPage:page];
8122 [toolbar_ showSelectionForButton:tag];
8127 - (void) applicationDidFinishLaunching:(id)unused {
8128 [BrowserView _initialize];
8130 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8132 Font12_ = [[UIFont systemFontOfSize:12] retain];
8133 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8134 Font14_ = [[UIFont systemFontOfSize:14] retain];
8135 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8136 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8140 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8141 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8143 window_ = [[UIWindow alloc] initWithContentRect:[UIHardware fullScreenApplicationContentRect]];
8144 [window_ orderFront:self];
8145 [window_ makeKey:self];
8146 [window_ setHidden:NO];
8148 database_ = [Database sharedInstance];
8150 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8151 [database_ setDelegate:progress_];
8152 [window_ setContentView:progress_];
8154 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8155 [progress_ setContentView:underlay_];
8157 [progress_ resetView];
8160 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8161 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8162 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8163 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8164 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8165 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8166 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8167 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8168 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8171 [self setIdleTimerDisabled:YES];
8173 hud_ = [self addProgressHUD];
8174 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8175 [self setStatusBarShowsProgress:YES];
8177 [self yieldToSelector:@selector(system) withObject:@"http://www.hipsterwave.com/tag/cydia/"];
8179 [self setStatusBarShowsProgress:NO];
8180 [self removeProgressHUD:hud_];
8183 if (ExecFork() == 0) {
8184 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8185 perror("launchctl stop");
8192 [self askForSettings];
8195 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
8197 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8198 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
8199 0, 0, screenrect.size.width, screenrect.size.height - 48
8200 ) database:database_];
8202 [book_ setDelegate:self];
8204 [overlay_ addSubview:book_];
8206 NSArray *buttonitems = [NSArray arrayWithObjects:
8207 [NSDictionary dictionaryWithObjectsAndKeys:
8208 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8209 @"home-up.png", kUIButtonBarButtonInfo,
8210 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
8211 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
8212 self, kUIButtonBarButtonTarget,
8213 @"Cydia", kUIButtonBarButtonTitle,
8214 @"0", kUIButtonBarButtonType,
8217 [NSDictionary dictionaryWithObjectsAndKeys:
8218 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8219 @"install-up.png", kUIButtonBarButtonInfo,
8220 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
8221 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
8222 self, kUIButtonBarButtonTarget,
8223 UCLocalize("SECTIONS"), kUIButtonBarButtonTitle,
8224 @"0", kUIButtonBarButtonType,
8227 [NSDictionary dictionaryWithObjectsAndKeys:
8228 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8229 @"changes-up.png", kUIButtonBarButtonInfo,
8230 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
8231 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
8232 self, kUIButtonBarButtonTarget,
8233 UCLocalize("CHANGES"), kUIButtonBarButtonTitle,
8234 @"0", kUIButtonBarButtonType,
8237 [NSDictionary dictionaryWithObjectsAndKeys:
8238 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8239 @"manage-up.png", kUIButtonBarButtonInfo,
8240 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
8241 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
8242 self, kUIButtonBarButtonTarget,
8243 UCLocalize("MANAGE"), kUIButtonBarButtonTitle,
8244 @"0", kUIButtonBarButtonType,
8247 [NSDictionary dictionaryWithObjectsAndKeys:
8248 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8249 @"search-up.png", kUIButtonBarButtonInfo,
8250 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
8251 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
8252 self, kUIButtonBarButtonTarget,
8253 UCLocalize("SEARCH"), kUIButtonBarButtonTitle,
8254 @"0", kUIButtonBarButtonType,
8258 toolbar_ = [[UIToolbar alloc]
8260 withFrame:CGRectMake(
8261 0, screenrect.size.height - ButtonBarHeight_,
8262 screenrect.size.width, ButtonBarHeight_
8264 withItemList:buttonitems
8267 [toolbar_ setDelegate:self];
8268 [toolbar_ setBarStyle:1];
8269 [toolbar_ setButtonBarTrackingMode:2];
8271 int buttons[5] = {1, 2, 3, 4, 5};
8272 [toolbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
8273 [toolbar_ showButtonGroup:0 withDuration:0];
8275 for (int i = 0; i != 5; ++i)
8276 [[toolbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
8277 i * 64 + 2, 1, 60, ButtonBarHeight_
8280 [toolbar_ showSelectionForButton:1];
8281 [overlay_ addSubview:toolbar_];
8283 [UIKeyboard initImplementationNow];
8284 CGSize keysize = [UIKeyboard defaultSize];
8285 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
8286 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
8287 [overlay_ addSubview:keyboard_];
8289 [underlay_ addSubview:overlay_];
8293 [self sectionsView];
8294 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
8295 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
8297 manage_ = (ManageView *) [[self
8298 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8299 withClass:[ManageView class]
8302 #if RecyclePackageViews
8303 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8304 [details_ addObject:[self _packageView]];
8305 [details_ addObject:[self _packageView]];
8313 - (void) showKeyboard:(BOOL)show {
8314 CGSize keysize([UIKeyboard defaultSize]);
8315 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8316 CGRect keyup(keydown);
8317 keyup.origin.y -= keysize.height;
8319 UIFrameAnimation *animation([[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease]);
8320 [animation setSignificantRectFields:2];
8323 [animation setStartFrame:keydown];
8324 [animation setEndFrame:keyup];
8325 [keyboard_ activate];
8327 [animation setStartFrame:keyup];
8328 [animation setEndFrame:keydown];
8329 [keyboard_ deactivate];
8332 [[UIAnimator sharedAnimator]
8333 addAnimations:[NSArray arrayWithObjects:animation, nil]
8334 withDuration:KeyboardTime_
8339 - (void) slideUp:(UIActionSheet *)alert {
8340 [alert presentSheetInView:overlay_];
8346 id Alloc_(id self, SEL selector) {
8347 id object = alloc_(self, selector);
8348 lprintf("[%s]A-%p\n", self->isa->name, object);
8353 id Dealloc_(id self, SEL selector) {
8354 id object = dealloc_(self, selector);
8355 lprintf("[%s]D-%p\n", self->isa->name, object);
8359 Class $WebDefaultUIKitDelegate;
8361 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8362 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8363 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8364 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8367 int main(int argc, char *argv[]) { _pooled
8370 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8372 /* Library Hacks {{{ */
8373 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8375 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8376 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8377 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8378 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8379 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8382 /* Set Locale {{{ */
8383 Locale_ = CFLocaleCopyCurrent();
8384 Languages_ = [NSLocale preferredLanguages];
8385 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8386 //NSLog(@"%@", [Languages_ description]);
8388 if (Languages_ == nil || [Languages_ count] == 0)
8391 lang = [[Languages_ objectAtIndex:0] UTF8String];
8392 setenv("LANG", lang, true);
8393 //std::setlocale(LC_ALL, lang);
8394 NSLog(@"Setting Language: %s", lang);
8397 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8399 /* Parse Arguments {{{ */
8400 bool substrate(false);
8406 for (int argi(1); argi != argc; ++argi)
8407 if (strcmp(argv[argi], "--") == 0) {
8409 argv[argi] = argv[0];
8415 for (int argi(1); argi != arge; ++argi)
8416 if (strcmp(args[argi], "--substrate") == 0)
8419 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8423 App_ = [[NSBundle mainBundle] bundlePath];
8424 Home_ = NSHomeDirectory();
8430 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8431 alloc_ = alloc->method_imp;
8432 alloc->method_imp = (IMP) &Alloc_;*/
8434 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8435 dealloc_ = dealloc->method_imp;
8436 dealloc->method_imp = (IMP) &Dealloc_;*/
8438 /* System Information {{{ */
8442 size = sizeof(maxproc);
8443 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8444 perror("sysctlbyname(\"kern.maxproc\", ?)");
8445 else if (maxproc < 64) {
8447 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8448 perror("sysctlbyname(\"kern.maxproc\", #)");
8451 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8452 char *osversion = new char[size];
8453 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8454 perror("sysctlbyname(\"kern.osversion\", ?)");
8456 System_ = [NSString stringWithUTF8String:osversion];
8458 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8459 char *machine = new char[size];
8460 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8461 perror("sysctlbyname(\"hw.machine\", ?)");
8465 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8466 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8467 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8468 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8472 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8473 NSData *data((NSData *) ecid);
8474 size_t length([data length]);
8475 uint8_t bytes[length];
8476 [data getBytes:bytes];
8477 char string[length * 2 + 1];
8478 for (size_t i(0); i != length; ++i)
8479 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8480 ChipID_ = [NSString stringWithUTF8String:string];
8484 IOObjectRelease(service);
8488 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8490 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8491 Build_ = [system objectForKey:@"ProductBuildVersion"];
8492 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8493 Product_ = [info objectForKey:@"SafariProductVersion"];
8494 Safari_ = [info objectForKey:@"CFBundleVersion"];
8497 /* Load Database {{{ */
8499 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8501 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8504 if (Metadata_ == NULL)
8505 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8507 Settings_ = [Metadata_ objectForKey:@"Settings"];
8509 Packages_ = [Metadata_ objectForKey:@"Packages"];
8510 Sections_ = [Metadata_ objectForKey:@"Sections"];
8511 Sources_ = [Metadata_ objectForKey:@"Sources"];
8514 if (Settings_ != nil)
8515 Role_ = [Settings_ objectForKey:@"Role"];
8517 if (Packages_ == nil) {
8518 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8519 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8522 if (Sections_ == nil) {
8523 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8524 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8527 if (Sources_ == nil) {
8528 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8529 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8534 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8537 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8539 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8540 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8541 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8542 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8544 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8545 unlink("/tmp/.cydia.fw");
8547 } else if (access("/User", F_OK) != 0) {
8550 system("/usr/libexec/cydia/firmware.sh");
8554 _assert([[NSFileManager defaultManager]
8555 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8556 withIntermediateDirectories:YES
8561 if (access("/tmp/cydia.chk", F_OK) == 0) {
8562 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8563 _assert(errno == ENOENT);
8564 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8565 _assert(errno == ENOENT);
8568 /* APT Initialization {{{ */
8569 _assert(pkgInitConfig(*_config));
8570 _assert(pkgInitSystem(*_config, _system));
8573 _config->Set("APT::Acquire::Translation", lang);
8574 _config->Set("Acquire::http::Timeout", 15);
8575 _config->Set("Acquire::http::MaxParallel", 3);
8577 /* Color Choices {{{ */
8578 space_ = CGColorSpaceCreateDeviceRGB();
8580 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8581 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8582 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8583 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8584 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8585 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8586 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8587 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8588 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8590 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8591 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8593 /* UIKit Configuration {{{ */
8594 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8595 if ($GSFontSetUseLegacyFontMetrics != NULL)
8596 $GSFontSetUseLegacyFontMetrics(YES);
8598 UIKeyboardDisableAutomaticAppearance();
8601 Colon_ = UCLocalize("COLON_DELIMITED");
8602 Error_ = UCLocalize("ERROR");
8603 Warning_ = UCLocalize("WARNING");
8606 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8608 CGColorSpaceRelease(space_);