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>
77 #include <apt-pkg/acquire.h>
78 #include <apt-pkg/acquire-item.h>
79 #include <apt-pkg/algorithms.h>
80 #include <apt-pkg/cachefile.h>
81 #include <apt-pkg/clean.h>
82 #include <apt-pkg/configuration.h>
83 #include <apt-pkg/debindexfile.h>
84 #include <apt-pkg/debmetaindex.h>
85 #include <apt-pkg/error.h>
86 #include <apt-pkg/init.h>
87 #include <apt-pkg/mmap.h>
88 #include <apt-pkg/pkgrecords.h>
89 #include <apt-pkg/sha1.h>
90 #include <apt-pkg/sourcelist.h>
91 #include <apt-pkg/sptr.h>
92 #include <apt-pkg/strutl.h>
93 #include <apt-pkg/tagfile.h>
95 #include <apr-1/apr_pools.h>
97 #include <sys/types.h>
99 #include <sys/sysctl.h>
100 #include <sys/param.h>
101 #include <sys/mount.h>
107 #include <mach-o/nlist.h>
117 #include <ext/hash_map>
119 #import "UICaboodle/BrowserView.h"
120 #import "UICaboodle/ResetView.h"
122 #import "substrate.h"
129 #define _timestamp ({ \
131 gettimeofday(&tv, NULL); \
132 tv.tv_sec * 1000000 + tv.tv_usec; \
135 typedef std::vector<class ProfileTime *> TimeList;
145 ProfileTime(const char *name) :
149 times_.push_back(this);
152 void AddTime(uint64_t time) {
159 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
171 ProfileTimer(ProfileTime &time) :
178 time_.AddTime(_timestamp - start_);
183 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
185 std::cerr << "========" << std::endl;
188 #define _profile(name) { \
189 static ProfileTime name(#name); \
190 ProfileTimer _ ## name(name);
195 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
197 void NSLogPoint(const char *fix, const CGPoint &point) {
198 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
201 void NSLogRect(const char *fix, const CGRect &rect) {
202 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
205 static _finline NSString *CydiaURL(NSString *path) {
207 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
208 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
209 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
210 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
211 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
212 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
215 /* [NSObject yieldToSelector:(withObject:)] {{{*/
216 @interface NSObject (Cydia)
217 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
218 - (id) yieldToSelector:(SEL)selector;
221 @implementation NSObject (Cydia)
226 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
227 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
228 id object([[context objectAtIndex:1] nonretainedObjectValue]);
229 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
231 /* XXX: deal with exceptions */
232 id value([self performSelector:selector withObject:object]);
234 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
235 [context removeAllObjects];
236 if ([signature methodReturnLength] != 0 && value != nil)
237 [context addObject:value];
242 performSelectorOnMainThread:@selector(doNothing)
248 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
249 /*return [self performSelector:selector withObject:object];*/
251 volatile bool stopped(false);
253 NSMutableArray *context([NSMutableArray arrayWithObjects:
254 [NSValue valueWithPointer:selector],
255 [NSValue valueWithNonretainedObject:object],
256 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
259 NSThread *thread([[[NSThread alloc]
261 selector:@selector(_yieldToContext:)
267 NSRunLoop *loop([NSRunLoop currentRunLoop]);
268 NSDate *future([NSDate distantFuture]);
270 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
272 return [context count] == 0 ? nil : [context objectAtIndex:0];
275 - (id) yieldToSelector:(SEL)selector {
276 return [self yieldToSelector:selector withObject:nil];
282 @interface CYActionSheet : UIActionSheet {
286 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
289 @implementation CYActionSheet
291 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
292 if ((self = [super initWithTitle:title buttons:buttons defaultButtonIndex:index delegate:self context:nil]) != nil) {
296 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
300 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
302 [self popupAlertAnimated:animated];
303 NSRunLoop *loop([NSRunLoop currentRunLoop]);
304 NSDate *future([NSDate distantFuture]);
305 while (button_ == 0 && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
311 /* NSForcedOrderingSearch doesn't work on the iPhone */
312 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
313 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
314 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
316 /* Information Dictionaries {{{ */
317 @interface NSMutableArray (Cydia)
318 - (void) addInfoDictionary:(NSDictionary *)info;
321 @implementation NSMutableArray (Cydia)
323 - (void) addInfoDictionary:(NSDictionary *)info {
324 [self addObject:info];
329 @interface NSMutableDictionary (Cydia)
330 - (void) addInfoDictionary:(NSDictionary *)info;
333 @implementation NSMutableDictionary (Cydia)
335 - (void) addInfoDictionary:(NSDictionary *)info {
336 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
341 /* Pop Transitions {{{ */
342 @interface PopTransitionView : UITransitionView {
347 @implementation PopTransitionView
349 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
350 if (from != nil && to == nil)
351 [self removeFromSuperview];
356 @implementation UIView (PopUpView)
358 - (void) popFromSuperviewAnimated:(BOOL)animated {
359 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
362 - (void) popSubview:(UIView *)view {
363 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
364 [transition setDelegate:transition];
365 [self addSubview:transition];
367 UIView *blank = [[[UIView alloc] initWithFrame:[transition bounds]] autorelease];
368 [transition transition:UITransitionNone toView:blank];
369 [transition transition:UITransitionPushFromBottom toView:view];
375 #define lprintf(args...) fprintf(stderr, args)
378 #define TraceLogging (1 && !ForRelease)
379 #define HistogramInsertionSort (0 && !ForRelease)
380 #define ProfileTimes (0 && !ForRelease)
381 #define ForSaurik (0 && !ForRelease)
382 #define LogBrowser (0 && !ForRelease)
383 #define TrackResize (0 && !ForRelease)
384 #define ManualRefresh (1 && !ForRelease)
385 #define ShowInternals (0 && !ForRelease)
386 #define IgnoreInstall (0 && !ForRelease)
387 #define RecycleWebViews 0
388 #define RecyclePackageViews (1 && ForRelease)
389 #define AlwaysReload (0 && !ForRelease)
393 #define _trace(args...)
398 #define _profile(name) {
401 #define PrintTimes() do {} while (false)
405 typedef uint32_t (*SKRadixFunction)(id, void *);
407 @interface NSMutableArray (Radix)
408 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
409 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
417 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
418 struct RadixItem_ *lhs(swap), *rhs(swap + count);
420 static const size_t width = 32;
421 static const size_t bits = 11;
422 static const size_t slots = 1 << bits;
423 static const size_t passes = (width + (bits - 1)) / bits;
425 size_t *hist(new size_t[slots]);
427 for (size_t pass(0); pass != passes; ++pass) {
428 memset(hist, 0, sizeof(size_t) * slots);
430 for (size_t i(0); i != count; ++i) {
431 uint32_t key(lhs[i].key);
433 key &= _not(uint32_t) >> width - bits;
438 for (size_t i(0); i != slots; ++i) {
439 size_t local(offset);
444 for (size_t i(0); i != count; ++i) {
445 uint32_t key(lhs[i].key);
447 key &= _not(uint32_t) >> width - bits;
448 rhs[hist[key]++] = lhs[i];
451 RadixItem_ *tmp(lhs);
458 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
459 for (size_t i(0); i != count; ++i)
460 [values addObject:[self objectAtIndex:lhs[i].index]];
461 [self setArray:values];
466 @implementation NSMutableArray (Radix)
468 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
469 size_t count([self count]);
474 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
475 [invocation setSelector:selector];
476 [invocation setArgument:&object atIndex:2];
478 /* XXX: this is an unsafe optimization of doomy hell */
479 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
480 _assert(method != NULL);
481 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
482 _assert(imp != NULL);
485 struct RadixItem_ *swap(new RadixItem_[count * 2]);
487 for (size_t i(0); i != count; ++i) {
488 RadixItem_ &item(swap[i]);
491 id object([self objectAtIndex:i]);
494 [invocation setTarget:object];
496 [invocation getReturnValue:&item.key];
498 item.key = imp(object, selector, object);
502 RadixSort_(self, count, swap);
505 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
506 size_t count([self count]);
507 struct RadixItem_ *swap(new RadixItem_[count * 2]);
509 for (size_t i(0); i != count; ++i) {
510 RadixItem_ &item(swap[i]);
513 id object([self objectAtIndex:i]);
514 item.key = function(object, argument);
517 RadixSort_(self, count, swap);
522 /* Insertion Sort {{{ */
524 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
525 const char *ptr = (const char *)list;
527 CFIndex half = count / 2;
528 const char *probe = ptr + elementSize * half;
529 CFComparisonResult cr = comparator(element, probe, context);
530 if (0 == cr) return (probe - (const char *)list) / elementSize;
531 ptr = (cr < 0) ? ptr : probe + elementSize;
532 count = (cr < 0) ? half : (half + (count & 1) - 1);
534 return (ptr - (const char *)list) / elementSize;
537 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
538 const char *ptr = (const char *)list;
540 CFIndex half = count / 2;
541 const char *probe = ptr + elementSize * half;
542 CFComparisonResult cr = comparator(element, probe, context);
543 if (0 == cr) return (probe - (const char *)list) / elementSize;
544 ptr = (cr < 0) ? ptr : probe + elementSize;
545 count = (cr < 0) ? half : (half + (count & 1) - 1);
547 return (ptr - (const char *)list) / elementSize;
550 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
551 if (range.length == 0)
553 const void **values(new const void *[range.length]);
554 CFArrayGetValues(array, range, values);
556 #if HistogramInsertionSort
557 uint32_t total(0), *offsets(new uint32_t[range.length]);
560 for (CFIndex index(1); index != range.length; ++index) {
561 const void *value(values[index]);
562 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
563 CFIndex correct(index);
564 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
567 if (correct != index) {
568 size_t offset(index - correct);
569 #if HistogramInsertionSort
573 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
575 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
576 values[correct] = value;
580 CFArrayReplaceValues(array, range, values, range.length);
583 #if HistogramInsertionSort
584 for (CFIndex index(0); index != range.length; ++index)
585 if (offsets[index] != 0)
586 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
587 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
594 /* Apple Bug Fixes {{{ */
595 @implementation UIWebDocumentView (Cydia)
597 - (void) _setScrollerOffset:(CGPoint)offset {
598 UIScroller *scroller([self _scroller]);
600 CGSize size([scroller contentSize]);
601 CGSize bounds([scroller bounds].size);
604 max.x = size.width - bounds.width;
605 max.y = size.height - bounds.height;
613 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
614 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
616 [scroller setOffset:offset];
622 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
623 size_t length([self length] - state->state);
626 else if (length > count)
628 for (size_t i(0); i != length; ++i)
629 objects[i] = [self item:state->state++];
630 state->itemsPtr = objects;
631 state->mutationsPtr = (unsigned long *) self;
635 @interface NSString (UIKit)
636 - (NSString *) stringByAddingPercentEscapes;
639 /* Cydia NSString Additions {{{ */
640 @interface NSString (Cydia)
641 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
642 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
643 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
644 - (NSComparisonResult) compareByPath:(NSString *)other;
645 - (NSString *) stringByCachingURLWithCurrentCDN;
646 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
649 @implementation NSString (Cydia)
651 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
652 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
655 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
656 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
657 memcpy(data, bytes, length);
658 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
661 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
662 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
665 - (NSComparisonResult) compareByPath:(NSString *)other {
666 NSString *prefix = [self commonPrefixWithString:other options:0];
667 size_t length = [prefix length];
669 NSRange lrange = NSMakeRange(length, [self length] - length);
670 NSRange rrange = NSMakeRange(length, [other length] - length);
672 lrange = [self rangeOfString:@"/" options:0 range:lrange];
673 rrange = [other rangeOfString:@"/" options:0 range:rrange];
675 NSComparisonResult value;
677 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
678 value = NSOrderedSame;
679 else if (lrange.location == NSNotFound)
680 value = NSOrderedAscending;
681 else if (rrange.location == NSNotFound)
682 value = NSOrderedDescending;
684 value = NSOrderedSame;
686 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
687 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
688 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
689 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
691 NSComparisonResult result = [lpath compare:rpath];
692 return result == NSOrderedSame ? value : result;
695 - (NSString *) stringByCachingURLWithCurrentCDN {
697 stringByReplacingOccurrencesOfString:@"://"
698 withString:@"://ne.edgecastcdn.net/8003A4/"
700 /* XXX: this is somewhat inaccurate */
701 range:NSMakeRange(0, 10)
705 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
706 return [(id)CFURLCreateStringByAddingPercentEscapes(
711 kCFStringEncodingUTF8
718 /* C++ NSString Wrapper Cache {{{ */
725 _finline void clear_() {
726 if (cache_ != NULL) {
733 _finline bool empty() const {
737 _finline size_t size() const {
741 _finline char *data() const {
745 _finline void clear() {
750 _finline CYString() :
757 _finline ~CYString() {
761 void operator =(const CYString &rhs) {
765 if (rhs.cache_ == nil)
768 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
771 void set(apr_pool_t *pool, const char *data, size_t size) {
777 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
778 memcpy(temp, data, size);
785 _finline void set(apr_pool_t *pool, const char *data) {
786 set(pool, data, data == NULL ? 0 : strlen(data));
789 _finline void set(apr_pool_t *pool, const std::string &rhs) {
790 set(pool, rhs.data(), rhs.size());
793 bool operator ==(const CYString &rhs) const {
794 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
797 operator CFStringRef() {
798 if (cache_ == NULL) {
801 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
805 _finline operator id() {
806 return (NSString *) static_cast<CFStringRef>(*this);
810 /* C++ NSString Algorithm Adapters {{{ */
812 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
815 struct NSStringMapHash :
816 std::unary_function<NSString *, size_t>
818 _finline size_t operator ()(NSString *value) const {
819 return CFStringHashNSString((CFStringRef) value);
823 struct NSStringMapLess :
824 std::binary_function<NSString *, NSString *, bool>
826 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
827 return [lhs compare:rhs] == NSOrderedAscending;
831 struct NSStringMapEqual :
832 std::binary_function<NSString *, NSString *, bool>
834 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
835 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
836 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
837 //[lhs isEqualToString:rhs];
842 /* Perl-Compatible RegEx {{{ */
852 Pcre(const char *regex) :
857 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
860 lprintf("%d:%s\n", offset, error);
864 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
865 matches_ = new int[(capture_ + 1) * 3];
873 NSString *operator [](size_t match) {
874 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
877 bool operator ()(NSString *data) {
878 // XXX: length is for characters, not for bytes
879 return operator ()([data UTF8String], [data length]);
882 bool operator ()(const char *data, size_t size) {
884 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
888 /* Mime Addresses {{{ */
889 @interface Address : NSObject {
895 - (NSString *) address;
897 - (void) setAddress:(NSString *)address;
899 + (Address *) addressWithString:(NSString *)string;
900 - (Address *) initWithString:(NSString *)string;
903 @implementation Address
912 - (NSString *) name {
916 - (NSString *) address {
920 - (void) setAddress:(NSString *)address {
922 [address_ autorelease];
926 address_ = [address retain];
929 + (Address *) addressWithString:(NSString *)string {
930 return [[[Address alloc] initWithString:string] autorelease];
933 + (NSArray *) _attributeKeys {
934 return [NSArray arrayWithObjects:@"address", @"name", nil];
937 - (NSArray *) attributeKeys {
938 return [[self class] _attributeKeys];
941 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
942 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
945 - (Address *) initWithString:(NSString *)string {
946 if ((self = [super init]) != nil) {
947 const char *data = [string UTF8String];
948 size_t size = [string length];
950 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
952 if (address_r(data, size)) {
953 name_ = [address_r[1] retain];
954 address_ = [address_r[2] retain];
956 name_ = [string retain];
964 /* CoreGraphics Primitives {{{ */
975 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
978 Set(space, red, green, blue, alpha);
983 CGColorRelease(color_);
990 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
992 float color[] = {red, green, blue, alpha};
993 color_ = CGColorCreate(space, color);
996 operator CGColorRef() {
1002 /* Random Global Variables {{{ */
1003 static const int PulseInterval_ = 50000;
1004 static const int ButtonBarWidth_ = 60;
1005 static const int ButtonBarHeight_ = 48;
1006 static const float KeyboardTime_ = 0.3f;
1009 static NSArray *Finishes_;
1011 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1012 #define NotifyConfig_ "/etc/notify.conf"
1014 static bool Queuing_;
1016 static CGColor Blue_;
1017 static CGColor Blueish_;
1018 static CGColor Black_;
1019 static CGColor Off_;
1020 static CGColor White_;
1021 static CGColor Gray_;
1022 static CGColor Green_;
1023 static CGColor Purple_;
1024 static CGColor Purplish_;
1026 static UIColor *InstallingColor_;
1027 static UIColor *RemovingColor_;
1029 static NSString *App_;
1030 static NSString *Home_;
1032 static BOOL Advanced_;
1033 static BOOL Ignored_;
1035 static UIFont *Font12_;
1036 static UIFont *Font12Bold_;
1037 static UIFont *Font14_;
1038 static UIFont *Font18Bold_;
1039 static UIFont *Font22Bold_;
1041 static const char *Machine_ = NULL;
1042 static const NSString *System_ = NULL;
1043 static const NSString *SerialNumber_ = nil;
1044 static const NSString *ChipID_ = nil;
1045 static const NSString *UniqueID_ = nil;
1046 static const NSString *Build_ = nil;
1047 static const NSString *Product_ = nil;
1048 static const NSString *Safari_ = nil;
1050 static CFLocaleRef Locale_;
1051 static NSArray *Languages_;
1052 static CGColorSpaceRef space_;
1054 static bool reload_;
1056 static NSDictionary *SectionMap_;
1057 static NSMutableDictionary *Metadata_;
1058 static _transient NSMutableDictionary *Settings_;
1059 static _transient NSString *Role_;
1060 static _transient NSMutableDictionary *Packages_;
1061 static _transient NSMutableDictionary *Sections_;
1062 static _transient NSMutableDictionary *Sources_;
1063 static bool Changed_;
1064 static NSDate *now_;
1067 static NSMutableArray *Documents_;
1071 /* Display Helpers {{{ */
1072 inline float Interpolate(float begin, float end, float fraction) {
1073 return (end - begin) * fraction + begin;
1076 /* XXX: localize this! */
1077 NSString *SizeString(double size) {
1078 bool negative = size < 0;
1083 while (size > 1024) {
1088 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1090 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1093 static _finline CFStringRef CFCString(const char *value) {
1094 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1097 const char *StripVersion_(const char *version) {
1098 const char *colon(strchr(version, ':'));
1100 version = colon + 1;
1104 CFStringRef StripVersion(const char *version) {
1105 const char *colon(strchr(version, ':'));
1107 version = colon + 1;
1108 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1110 return CFCString(version);
1113 NSString *LocalizeSection(NSString *section) {
1114 static Pcre title_r("^(.*?) \\((.*)\\)$");
1115 if (title_r(section)) {
1116 NSString *parent(title_r[1]);
1117 NSString *child(title_r[2]);
1119 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1120 LocalizeSection(parent),
1121 LocalizeSection(child)
1125 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1128 NSString *Simplify(NSString *title) {
1129 const char *data = [title UTF8String];
1130 size_t size = [title length];
1132 static Pcre square_r("^\\[(.*)\\]$");
1133 if (square_r(data, size))
1134 return Simplify(square_r[1]);
1136 static Pcre paren_r("^\\((.*)\\)$");
1137 if (paren_r(data, size))
1138 return Simplify(paren_r[1]);
1140 static Pcre title_r("^(.*?) \\((.*)\\)$");
1141 if (title_r(data, size))
1142 return Simplify(title_r[1]);
1148 NSString *GetLastUpdate() {
1149 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1152 return UCLocalize("NEVER_OR_UNKNOWN");
1154 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1155 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1157 CFRelease(formatter);
1159 return [(NSString *) formatted autorelease];
1162 bool isSectionVisible(NSString *section) {
1163 NSDictionary *metadata([Sections_ objectForKey:section]);
1164 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1165 return hidden == nil || ![hidden boolValue];
1168 /* Delegate Prototypes {{{ */
1172 @interface NSObject (ProgressDelegate)
1175 @protocol ProgressDelegate
1176 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1177 - (void) setProgressTitle:(NSString *)title;
1178 - (void) setProgressPercent:(float)percent;
1179 - (void) startProgress;
1180 - (void) addProgressOutput:(NSString *)output;
1181 - (bool) isCancelling:(size_t)received;
1184 @protocol ConfigurationDelegate
1185 - (void) repairWithSelector:(SEL)selector;
1186 - (void) setConfigurationData:(NSString *)data;
1191 @protocol CydiaDelegate
1192 - (void) setPackageView:(PackageView *)view;
1193 - (void) clearPackage:(Package *)package;
1194 - (void) installPackage:(Package *)package;
1195 - (void) removePackage:(Package *)package;
1196 - (void) slideUp:(UIActionSheet *)alert;
1197 - (void) distUpgrade;
1198 - (void) updateData;
1200 - (void) askForSettings;
1201 - (UIProgressHUD *) addProgressHUD;
1202 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1203 - (RVPage *) pageForPackage:(NSString *)name;
1204 - (PackageView *) packageView;
1208 /* Status Delegation {{{ */
1210 public pkgAcquireStatus
1213 _transient NSObject<ProgressDelegate> *delegate_;
1221 void setDelegate(id delegate) {
1222 delegate_ = delegate;
1225 NSObject<ProgressDelegate> *getDelegate() const {
1229 virtual bool MediaChange(std::string media, std::string drive) {
1233 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1236 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1237 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1238 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1241 virtual void Done(pkgAcquire::ItemDesc &item) {
1244 virtual void Fail(pkgAcquire::ItemDesc &item) {
1246 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1247 item.Owner->Status == pkgAcquire::Item::StatDone
1251 std::string &error(item.Owner->ErrorText);
1255 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1256 NSArray *fields([description componentsSeparatedByString:@" "]);
1257 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1259 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1260 withObject:[NSArray arrayWithObjects:
1261 [NSString stringWithUTF8String:error.c_str()],
1268 virtual bool Pulse(pkgAcquire *Owner) {
1269 bool value = pkgAcquireStatus::Pulse(Owner);
1272 double(CurrentBytes + CurrentItems) /
1273 double(TotalBytes + TotalItems)
1276 [delegate_ setProgressPercent:percent];
1277 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1280 virtual void Start() {
1281 [delegate_ startProgress];
1284 virtual void Stop() {
1288 /* Progress Delegation {{{ */
1293 _transient id<ProgressDelegate> delegate_;
1297 virtual void Update() {
1298 /*if (abs(Percent - percent_) > 2)
1299 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1303 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1304 [delegate_ setProgressPercent:(Percent / 100)];*/
1314 void setDelegate(id delegate) {
1315 delegate_ = delegate;
1318 id getDelegate() const {
1322 virtual void Done() {
1324 //[delegate_ setProgressPercent:1];
1329 /* Database Interface {{{ */
1330 typedef std::map< unsigned long, _H<Source> > SourceMap;
1332 @interface Database : NSObject {
1338 pkgCacheFile cache_;
1339 pkgDepCache::Policy *policy_;
1340 pkgRecords *records_;
1341 pkgProblemResolver *resolver_;
1342 pkgAcquire *fetcher_;
1344 SPtr<pkgPackageManager> manager_;
1345 pkgSourceList *list_;
1348 NSMutableArray *packages_;
1350 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1359 + (Database *) sharedInstance;
1362 - (void) _readCydia:(NSNumber *)fd;
1363 - (void) _readStatus:(NSNumber *)fd;
1364 - (void) _readOutput:(NSNumber *)fd;
1368 - (Package *) packageWithName:(NSString *)name;
1370 - (pkgCacheFile &) cache;
1371 - (pkgDepCache::Policy *) policy;
1372 - (pkgRecords *) records;
1373 - (pkgProblemResolver *) resolver;
1374 - (pkgAcquire &) fetcher;
1375 - (pkgSourceList &) list;
1376 - (NSArray *) packages;
1377 - (NSArray *) sources;
1378 - (void) reloadData;
1386 - (void) setVisible;
1388 - (void) updateWithStatus:(Status &)status;
1390 - (void) setDelegate:(id)delegate;
1391 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1394 /* Delegate Helpers {{{ */
1395 @implementation NSObject(ProgressDelegate)
1397 - (void) _setProgressErrorPackage:(NSArray *)args {
1398 [self performSelector:@selector(setProgressError:forPackage:)
1399 withObject:[args objectAtIndex:0]
1400 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1404 - (void) _setProgressErrorTitle:(NSArray *)args {
1405 [self performSelector:@selector(setProgressError:withTitle:)
1406 withObject:[args objectAtIndex:0]
1407 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1411 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1412 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1413 withObject:[NSArray arrayWithObjects:error, title, nil]
1418 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1419 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1420 // XXX: holy typecast batman!
1421 [(id<ProgressDelegate>)self setProgressError:error withTitle:(package == nil ? id : [package name])];
1427 /* Source Class {{{ */
1428 @interface Source : NSObject {
1429 CYString depiction_;
1430 CYString description_;
1436 CYString distribution_;
1441 NSString *authority_;
1443 CYString defaultIcon_;
1445 NSDictionary *record_;
1449 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1451 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1453 - (NSString *) depictionForPackage:(NSString *)package;
1454 - (NSString *) supportForPackage:(NSString *)package;
1456 - (NSDictionary *) record;
1460 - (NSString *) distribution;
1461 - (NSString *) type;
1463 - (NSString *) host;
1465 - (NSString *) name;
1466 - (NSString *) description;
1467 - (NSString *) label;
1468 - (NSString *) origin;
1469 - (NSString *) version;
1471 - (NSString *) defaultIcon;
1475 @implementation Source
1479 distribution_.clear();
1482 description_.clear();
1488 defaultIcon_.clear();
1490 if (record_ != nil) {
1500 if (authority_ != nil) {
1501 [authority_ release];
1511 + (NSArray *) _attributeKeys {
1512 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1515 - (NSArray *) attributeKeys {
1516 return [[self class] _attributeKeys];
1519 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1520 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1523 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1526 trusted_ = index->IsTrusted();
1528 uri_.set(pool, index->GetURI());
1529 distribution_.set(pool, index->GetDist());
1530 type_.set(pool, index->GetType());
1532 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1533 if (dindex != NULL) {
1535 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1538 pkgTagFile tags(&fd);
1540 pkgTagSection section;
1547 {"default-icon", &defaultIcon_},
1548 {"depiction", &depiction_},
1549 {"description", &description_},
1551 {"origin", &origin_},
1552 {"support", &support_},
1553 {"version", &version_},
1556 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1557 const char *start, *end;
1559 if (section.Find(names[i].name_, start, end)) {
1560 CYString &value(*names[i].value_);
1561 value.set(pool, start, end - start);
1567 record_ = [Sources_ objectForKey:[self key]];
1569 record_ = [record_ retain];
1571 NSURL *url([NSURL URLWithString:uri_]);
1575 host_ = [[host_ lowercaseString] retain];
1580 authority_ = [url path];
1582 if (authority_ != nil)
1583 authority_ = [authority_ retain];
1586 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1587 if ((self = [super init]) != nil) {
1588 [self setMetaIndex:index inPool:pool];
1592 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1593 NSDictionary *lhr = [self record];
1594 NSDictionary *rhr = [source record];
1597 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1599 NSString *lhs = [self name];
1600 NSString *rhs = [source name];
1602 if ([lhs length] != 0 && [rhs length] != 0) {
1603 unichar lhc = [lhs characterAtIndex:0];
1604 unichar rhc = [rhs characterAtIndex:0];
1606 if (isalpha(lhc) && !isalpha(rhc))
1607 return NSOrderedAscending;
1608 else if (!isalpha(lhc) && isalpha(rhc))
1609 return NSOrderedDescending;
1612 return [lhs compare:rhs options:LaxCompareOptions_];
1615 - (NSString *) depictionForPackage:(NSString *)package {
1616 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1619 - (NSString *) supportForPackage:(NSString *)package {
1620 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1623 - (NSDictionary *) record {
1631 - (NSString *) uri {
1635 - (NSString *) distribution {
1636 return distribution_;
1639 - (NSString *) type {
1643 - (NSString *) key {
1644 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1647 - (NSString *) host {
1651 - (NSString *) name {
1652 return origin_.empty() ? authority_ : origin_;
1655 - (NSString *) description {
1656 return description_;
1659 - (NSString *) label {
1660 return label_.empty() ? authority_ : label_;
1663 - (NSString *) origin {
1667 - (NSString *) version {
1671 - (NSString *) defaultIcon {
1672 return defaultIcon_;
1677 /* Relationship Class {{{ */
1678 @interface Relationship : NSObject {
1683 - (NSString *) type;
1685 - (NSString *) name;
1689 @implementation Relationship
1697 - (NSString *) type {
1705 - (NSString *) name {
1712 /* Package Class {{{ */
1713 @interface Package : NSObject {
1717 pkgCache::VerIterator version_;
1718 pkgCache::PkgIterator iterator_;
1719 _transient Database *database_;
1720 pkgCache::VerFileIterator file_;
1727 NSString *section$_;
1733 CYString installed_;
1739 CYString depiction_;
1750 NSMutableArray *tags_;
1753 NSArray *relationships_;
1755 NSMutableDictionary *metadata_;
1756 _transient NSDate *firstSeen_;
1757 _transient NSDate *lastSeen_;
1761 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1762 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1764 - (pkgCache::PkgIterator) iterator;
1767 - (NSString *) section;
1768 - (NSString *) simpleSection;
1770 - (NSString *) longSection;
1771 - (NSString *) shortSection;
1775 - (Address *) maintainer;
1777 - (NSString *) longDescription;
1778 - (NSString *) shortDescription;
1781 - (NSMutableDictionary *) metadata;
1783 - (BOOL) subscribed;
1786 - (NSString *) latest;
1787 - (NSString *) installed;
1788 - (BOOL) uninstalled;
1791 - (BOOL) upgradableAndEssential:(BOOL)essential;
1794 - (BOOL) unfiltered;
1798 - (BOOL) halfConfigured;
1799 - (BOOL) halfInstalled;
1801 - (NSString *) mode;
1803 - (void) setVisible;
1806 - (NSString *) name;
1808 - (NSString *) homepage;
1809 - (NSString *) depiction;
1810 - (Address *) author;
1812 - (NSString *) support;
1814 - (NSArray *) files;
1815 - (NSArray *) relationships;
1816 - (NSArray *) warnings;
1817 - (NSArray *) applications;
1819 - (Source *) source;
1820 - (NSString *) role;
1822 - (BOOL) matches:(NSString *)text;
1824 - (bool) hasSupportingRole;
1825 - (BOOL) hasTag:(NSString *)tag;
1826 - (NSString *) primaryPurpose;
1827 - (NSArray *) purposes;
1828 - (bool) isCommercial;
1830 - (CYString &) cyname;
1832 - (uint32_t) compareBySection:(NSArray *)sections;
1834 - (uint32_t) compareForChanges;
1839 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1840 - (bool) isInstalledAndVisible:(NSNumber *)number;
1841 - (bool) isVisibleInSection:(NSString *)section;
1842 - (bool) isVisibleInSource:(Source *)source;
1846 uint32_t PackageChangesRadix(Package *self, void *) {
1851 uint32_t timestamp : 30;
1852 uint32_t ignored : 1;
1853 uint32_t upgradable : 1;
1857 bool upgradable([self upgradableAndEssential:YES]);
1858 value.bits.upgradable = upgradable ? 1 : 0;
1861 value.bits.timestamp = 0;
1862 value.bits.ignored = [self ignored] ? 0 : 1;
1863 value.bits.upgradable = 1;
1865 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1866 value.bits.ignored = 0;
1867 value.bits.upgradable = 0;
1870 return _not(uint32_t) - value.key;
1873 _finline static void Stifle(uint8_t &value) {
1876 uint32_t PackagePrefixRadix(Package *self, void *context) {
1877 size_t offset(reinterpret_cast<size_t>(context));
1878 CYString &name([self cyname]);
1880 size_t size(name.size());
1883 char *text(name.data());
1886 if (!isdigit(text[0]))
1890 while (size != digits && isdigit(text[digits]))
1900 if (offset == 0 && zeros != 0) {
1901 memset(data, '0', zeros);
1902 memcpy(data + zeros, text, 4 - zeros);
1904 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1905 if (size <= offset - zeros)
1908 text += offset - zeros;
1909 size -= offset - zeros;
1912 memcpy(data, text, 4);
1914 memcpy(data, text, size);
1915 memset(data + size, 0, 4 - size);
1918 for (size_t i(0); i != 4; ++i)
1919 if (isalpha(data[i]))
1924 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1926 /* XXX: ntohl may be more honest */
1927 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1930 CYString &(*PackageName)(Package *self, SEL sel);
1932 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1933 _profile(PackageNameCompare)
1934 CYString &lhi(PackageName(lhs, @selector(cyname)));
1935 CYString &rhi(PackageName(rhs, @selector(cyname)));
1936 CFStringRef lhn(lhi), rhn(rhi);
1939 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1940 else if (rhn == NULL)
1941 return NSOrderedDescending;
1943 _profile(PackageNameCompare$NumbersLast)
1944 if (!lhi.empty() && !rhi.empty()) {
1945 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1946 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1947 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1948 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1949 return lha ? NSOrderedAscending : NSOrderedDescending;
1953 CFIndex length = CFStringGetLength(lhn);
1955 _profile(PackageNameCompare$Compare)
1956 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1961 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1962 return PackageNameCompare(*lhs, *rhs, context);
1965 struct PackageNameOrdering :
1966 std::binary_function<Package *, Package *, bool>
1968 _finline bool operator ()(Package *lhs, Package *rhs) const {
1969 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1973 @implementation Package
1975 - (NSString *) description {
1976 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1982 if (section$_ != nil)
1983 [section$_ release];
1988 if (sponsor$_ != nil)
1989 [sponsor$_ release];
1990 if (author$_ != nil)
1997 if (relationships_ != nil)
1998 [relationships_ release];
1999 if (metadata_ != nil)
2000 [metadata_ release];
2005 + (NSString *) webScriptNameForSelector:(SEL)selector {
2006 if (selector == @selector(hasTag:))
2012 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2013 return [self webScriptNameForSelector:selector] == nil;
2016 + (NSArray *) _attributeKeys {
2017 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];
2020 - (NSArray *) attributeKeys {
2021 return [[self class] _attributeKeys];
2024 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2025 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2035 _profile(Package$parse)
2036 pkgRecords::Parser *parser;
2038 _profile(Package$parse$Lookup)
2039 parser = &[database_ records]->Lookup(file_);
2044 _profile(Package$parse$Find)
2050 {"depiction", &depiction_},
2051 {"homepage", &homepage_},
2052 {"website", &website},
2054 {"support", &support_},
2055 {"sponsor", &sponsor_},
2056 {"author", &author_},
2059 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2060 const char *start, *end;
2062 if (parser->Find(names[i].name_, start, end)) {
2063 CYString &value(*names[i].value_);
2064 _profile(Package$parse$Value)
2065 value.set(pool_, start, end - start);
2071 _profile(Package$parse$Tagline)
2072 const char *start, *end;
2073 if (parser->ShortDesc(start, end)) {
2074 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2077 while (stop != start && stop[-1] == '\r')
2079 tagline_.set(pool_, start, stop - start);
2083 _profile(Package$parse$Retain)
2084 if (homepage_.empty())
2085 homepage_ = website;
2086 if (homepage_ == depiction_)
2092 - (void) setVisible {
2093 visible_ = required_ && [self hasSupportingRole] && [self unfiltered];
2096 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2097 if ((self = [super init]) != nil) {
2098 _profile(Package$initWithVersion)
2099 @synchronized (database) {
2100 era_ = [database era];
2104 iterator_ = version.ParentPkg();
2105 database_ = database;
2107 _profile(Package$initWithVersion$Latest)
2108 latest_ = (NSString *) StripVersion(version_.VerStr());
2111 pkgCache::VerIterator current;
2112 _profile(Package$initWithVersion$Versions)
2113 current = iterator_.CurrentVer();
2115 installed_.set(pool_, StripVersion_(current.VerStr()));
2117 if (!version_.end())
2118 file_ = version_.FileList();
2120 pkgCache &cache([database_ cache]);
2121 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2125 _profile(Package$initWithVersion$Name)
2126 id_.set(pool_, iterator_.Name());
2127 name_.set(pool, iterator_.Display());
2131 _profile(Package$initWithVersion$Source)
2132 source_ = [database_ getSource:file_.File()];
2141 _profile(Package$initWithVersion$Tags)
2142 pkgCache::TagIterator tag(iterator_.TagList());
2144 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2146 const char *name(tag.Name());
2147 [tags_ addObject:(NSString *)CFCString(name)];
2148 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2149 role_ = (NSString *) CFCString(name + 6);
2150 if (required_ && strncmp(name, "require::", 9) == 0 && (
2155 } while (!tag.end());
2159 bool changed(false);
2160 NSString *key([id_ lowercaseString]);
2162 _profile(Package$initWithVersion$Metadata)
2163 metadata_ = [Packages_ objectForKey:key];
2165 if (metadata_ == nil) {
2168 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2169 firstSeen_, @"FirstSeen",
2170 latest_, @"LastVersion",
2175 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2176 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2178 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2179 subscribed_ = [subscribed boolValue];
2181 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2183 if (firstSeen_ == nil) {
2184 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2185 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2189 if (version == nil) {
2190 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2193 if (![version isEqualToString:latest_]) {
2194 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2196 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2201 metadata_ = [metadata_ retain];
2204 [Packages_ setObject:metadata_ forKey:key];
2209 _profile(Package$initWithVersion$Section)
2210 section_.set(pool_, iterator_.Section());
2213 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2215 } _end } return self;
2218 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2219 @synchronized ([Database class]) {
2220 pkgCache::VerIterator version;
2222 _profile(Package$packageWithIterator$GetCandidateVer)
2223 version = [database policy]->GetCandidateVer(iterator);
2229 return [[[Package alloc]
2230 initWithVersion:version
2237 - (pkgCache::PkgIterator) iterator {
2241 - (NSString *) section {
2242 if (section$_ == nil) {
2243 if (section_.empty())
2246 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2247 NSString *name(section_);
2250 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2251 if (NSString *rename = [value objectForKey:@"Rename"]) {
2256 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2260 - (NSString *) simpleSection {
2261 if (NSString *section = [self section])
2262 return Simplify(section);
2267 - (NSString *) longSection {
2268 return LocalizeSection([self section]);
2271 - (NSString *) shortSection {
2272 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2275 - (NSString *) uri {
2278 pkgIndexFile *index;
2279 pkgCache::PkgFileIterator file(file_.File());
2280 if (![database_ list].FindIndex(file, index))
2282 return [NSString stringWithUTF8String:iterator_->Path];
2283 //return [NSString stringWithUTF8String:file.Site()];
2284 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2288 - (Address *) maintainer {
2291 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2292 const std::string &maintainer(parser->Maintainer());
2293 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2297 return version_.end() ? 0 : version_->InstalledSize;
2300 - (NSString *) longDescription {
2303 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2304 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2306 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2307 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2308 if ([lines count] < 2)
2311 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2312 for (size_t i(1), e([lines count]); i != e; ++i) {
2313 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2314 [trimmed addObject:trim];
2317 return [trimmed componentsJoinedByString:@"\n"];
2320 - (NSString *) shortDescription {
2325 _profile(Package$index)
2326 CFStringRef name((CFStringRef) [self name]);
2327 if (CFStringGetLength(name) == 0)
2329 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2330 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2332 return toupper(character);
2336 - (NSMutableDictionary *) metadata {
2341 if (subscribed_ && lastSeen_ != nil)
2346 - (BOOL) subscribed {
2351 NSDictionary *metadata([self metadata]);
2352 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2353 return [ignored boolValue];
2358 - (NSString *) latest {
2362 - (NSString *) installed {
2366 - (BOOL) uninstalled {
2367 return installed_.empty();
2371 return !version_.end();
2374 - (BOOL) upgradableAndEssential:(BOOL)essential {
2375 _profile(Package$upgradableAndEssential)
2376 pkgCache::VerIterator current(iterator_.CurrentVer());
2378 return essential && essential_ && visible_;
2380 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2384 - (BOOL) essential {
2389 return [database_ cache][iterator_].InstBroken();
2392 - (BOOL) unfiltered {
2393 NSString *section([self section]);
2394 return section == nil || isSectionVisible(section);
2402 unsigned char current(iterator_->CurrentState);
2403 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2406 - (BOOL) halfConfigured {
2407 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2410 - (BOOL) halfInstalled {
2411 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2415 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2416 return state.Mode != pkgDepCache::ModeKeep;
2419 - (NSString *) mode {
2420 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2422 switch (state.Mode) {
2423 case pkgDepCache::ModeDelete:
2424 if ((state.iFlags & pkgDepCache::Purge) != 0)
2428 case pkgDepCache::ModeKeep:
2429 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2430 return @"REINSTALL";
2431 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2435 case pkgDepCache::ModeInstall:
2436 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2437 return @"REINSTALL";
2438 else*/ switch (state.Status) {
2440 return @"DOWNGRADE";
2446 return @"NEW_INSTALL";
2457 - (NSString *) name {
2458 return name_.empty() ? id_ : name_;
2461 - (UIImage *) icon {
2462 NSString *section = [self simpleSection];
2466 if ([icon_ hasPrefix:@"file:///"])
2467 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2468 if (icon == nil) if (section != nil)
2469 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2470 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2471 if ([dicon hasPrefix:@"file:///"])
2472 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2474 icon = [UIImage applicationImageNamed:@"unknown.png"];
2478 - (NSString *) homepage {
2482 - (NSString *) depiction {
2483 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2486 - (Address *) sponsor {
2487 if (sponsor$_ == nil) {
2488 if (sponsor_.empty())
2490 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2494 - (Address *) author {
2495 if (author$_ == nil) {
2496 if (author_.empty())
2498 author$_ = [[Address addressWithString:author_] retain];
2502 - (NSString *) support {
2503 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2506 - (NSArray *) files {
2507 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2508 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2511 fin.open([path UTF8String]);
2516 while (std::getline(fin, line))
2517 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2522 - (NSArray *) relationships {
2523 return relationships_;
2526 - (NSArray *) warnings {
2527 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2528 const char *name(iterator_.Name());
2530 size_t length(strlen(name));
2531 if (length < 2) invalid:
2532 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2533 else for (size_t i(0); i != length; ++i)
2535 /* XXX: technically this is not allowed */
2536 (name[i] < 'A' || name[i] > 'Z') &&
2537 (name[i] < 'a' || name[i] > 'z') &&
2538 (name[i] < '0' || name[i] > '9') &&
2539 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2542 if (strcmp(name, "cydia") != 0) {
2545 bool _private = false;
2548 bool repository = [[self section] isEqualToString:@"Repositories"];
2550 if (NSArray *files = [self files])
2551 for (NSString *file in files)
2552 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2554 else if (!user && [file isEqualToString:@"/User"])
2556 else if (!_private && [file isEqualToString:@"/private"])
2558 else if (!stash && [file isEqualToString:@"/var/stash"])
2561 /* XXX: this is not sensitive enough. only some folders are valid. */
2562 if (cydia && !repository)
2563 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2565 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2567 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2569 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2572 return [warnings count] == 0 ? nil : warnings;
2575 - (NSArray *) applications {
2576 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2578 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2580 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2581 if (NSArray *files = [self files])
2582 for (NSString *file in files)
2583 if (application_r(file)) {
2584 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2585 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2586 if ([id isEqualToString:me])
2589 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2591 display = application_r[1];
2593 NSString *bundle([file stringByDeletingLastPathComponent]);
2594 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2595 if (icon == nil || [icon length] == 0)
2597 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2599 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2600 [applications addObject:application];
2602 [application addObject:id];
2603 [application addObject:display];
2604 [application addObject:url];
2607 return [applications count] == 0 ? nil : applications;
2610 - (Source *) source {
2612 @synchronized (database_) {
2613 if ([database_ era] != era_ || file_.end())
2616 source_ = [database_ getSource:file_.File()];
2628 - (NSString *) role {
2632 - (BOOL) matches:(NSString *)text {
2638 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2639 if (range.location != NSNotFound)
2642 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2643 if (range.location != NSNotFound)
2646 /* range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2647 if (range.location != NSNotFound)
2653 - (bool) hasSupportingRole {
2656 if ([role_ isEqualToString:@"enduser"])
2658 if ([Role_ isEqualToString:@"User"])
2660 if ([role_ isEqualToString:@"hacker"])
2662 if ([Role_ isEqualToString:@"Hacker"])
2664 if ([role_ isEqualToString:@"developer"])
2666 if ([Role_ isEqualToString:@"Developer"])
2671 - (BOOL) hasTag:(NSString *)tag {
2672 return tags_ == nil ? NO : [tags_ containsObject:tag];
2675 - (NSString *) primaryPurpose {
2676 for (NSString *tag in tags_)
2677 if ([tag hasPrefix:@"purpose::"])
2678 return [tag substringFromIndex:9];
2682 - (NSArray *) purposes {
2683 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2684 for (NSString *tag in tags_)
2685 if ([tag hasPrefix:@"purpose::"])
2686 [purposes addObject:[tag substringFromIndex:9]];
2687 return [purposes count] == 0 ? nil : purposes;
2690 - (bool) isCommercial {
2691 return [self hasTag:@"cydia::commercial"];
2694 - (CYString &) cyname {
2695 return name_.empty() ? id_ : name_;
2698 - (uint32_t) compareBySection:(NSArray *)sections {
2699 NSString *section([self section]);
2700 for (size_t i(0), e([sections count]); i != e; ++i) {
2701 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2705 return _not(uint32_t);
2708 - (uint32_t) compareForChanges {
2713 uint32_t timestamp : 30;
2714 uint32_t ignored : 1;
2715 uint32_t upgradable : 1;
2719 bool upgradable([self upgradableAndEssential:YES]);
2720 value.bits.upgradable = upgradable ? 1 : 0;
2723 value.bits.timestamp = 0;
2724 value.bits.ignored = [self ignored] ? 0 : 1;
2725 value.bits.upgradable = 1;
2727 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2728 value.bits.ignored = 0;
2729 value.bits.upgradable = 0;
2732 return _not(uint32_t) - value.key;
2736 pkgProblemResolver *resolver = [database_ resolver];
2737 resolver->Clear(iterator_);
2738 resolver->Protect(iterator_);
2742 pkgProblemResolver *resolver = [database_ resolver];
2743 resolver->Clear(iterator_);
2744 resolver->Protect(iterator_);
2745 pkgCacheFile &cache([database_ cache]);
2746 cache->MarkInstall(iterator_, false);
2747 pkgDepCache::StateCache &state((*cache)[iterator_]);
2748 if (!state.Install())
2749 cache->SetReInstall(iterator_, true);
2753 pkgProblemResolver *resolver = [database_ resolver];
2754 resolver->Clear(iterator_);
2755 resolver->Protect(iterator_);
2756 resolver->Remove(iterator_);
2757 [database_ cache]->MarkDelete(iterator_, true);
2760 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2761 _profile(Package$isUnfilteredAndSearchedForBy)
2764 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2765 value &= [self unfiltered];
2768 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2769 value &= [self matches:search];
2776 - (bool) isInstalledAndVisible:(NSNumber *)number {
2777 return (![number boolValue] || [self visible]) && ![self uninstalled];
2780 - (bool) isVisibleInSection:(NSString *)name {
2781 NSString *section = [self section];
2786 section == nil && [name length] == 0 ||
2787 [name isEqualToString:section]
2791 - (bool) isVisibleInSource:(Source *)source {
2792 return [self source] == source && [self visible];
2797 /* Section Class {{{ */
2798 @interface Section : NSObject {
2803 NSString *localized_;
2806 - (NSComparisonResult) compareByLocalized:(Section *)section;
2807 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2808 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2809 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2810 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2811 - (NSString *) name;
2818 - (void) addToCount;
2820 - (void) setCount:(size_t)count;
2821 - (NSString *) localized;
2825 @implementation Section
2829 if (localized_ != nil)
2830 [localized_ release];
2834 - (NSComparisonResult) compareByLocalized:(Section *)section {
2835 NSString *lhs(localized_);
2836 NSString *rhs([section localized]);
2838 /*if ([lhs length] != 0 && [rhs length] != 0) {
2839 unichar lhc = [lhs characterAtIndex:0];
2840 unichar rhc = [rhs characterAtIndex:0];
2842 if (isalpha(lhc) && !isalpha(rhc))
2843 return NSOrderedAscending;
2844 else if (!isalpha(lhc) && isalpha(rhc))
2845 return NSOrderedDescending;
2848 return [lhs compare:rhs options:LaxCompareOptions_];
2851 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2852 if ((self = [self initWithName:name localize:NO]) != nil) {
2853 if (localized != nil)
2854 localized_ = [localized retain];
2858 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2859 return [self initWithName:name row:0 localize:localize];
2862 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2863 if ((self = [super init]) != nil) {
2864 name_ = [name retain];
2868 localized_ = [LocalizeSection(name_) retain];
2872 /* XXX: localize the index thingees */
2873 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2874 if ((self = [super init]) != nil) {
2875 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2881 - (NSString *) name {
2901 - (void) addToCount {
2905 - (void) setCount:(size_t)count {
2909 - (NSString *) localized {
2916 static NSString *Colon_;
2917 static NSString *Error_;
2918 static NSString *Warning_;
2920 /* Database Implementation {{{ */
2921 @implementation Database
2923 + (Database *) sharedInstance {
2924 static Database *instance;
2925 if (instance == nil)
2926 instance = [[Database alloc] init];
2936 NSRecycleZone(zone_);
2937 // XXX: malloc_destroy_zone(zone_);
2938 apr_pool_destroy(pool_);
2942 - (void) _readCydia:(NSNumber *)fd { _pooled
2943 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2944 std::istream is(&ib);
2947 static Pcre finish_r("^finish:([^:]*)$");
2949 while (std::getline(is, line)) {
2950 const char *data(line.c_str());
2951 size_t size = line.size();
2952 lprintf("C:%s\n", data);
2954 if (finish_r(data, size)) {
2955 NSString *finish = finish_r[1];
2956 int index = [Finishes_ indexOfObject:finish];
2957 if (index != INT_MAX && index > Finish_)
2965 - (void) _readStatus:(NSNumber *)fd { _pooled
2966 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2967 std::istream is(&ib);
2970 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2971 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2973 while (std::getline(is, line)) {
2974 const char *data(line.c_str());
2975 size_t size(line.size());
2976 lprintf("S:%s\n", data);
2978 if (conffile_r(data, size)) {
2979 [delegate_ setConfigurationData:conffile_r[1]];
2980 } else if (strncmp(data, "status: ", 8) == 0) {
2981 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2982 [delegate_ setProgressTitle:string];
2983 } else if (pmstatus_r(data, size)) {
2984 std::string type([pmstatus_r[1] UTF8String]);
2985 NSString *id = pmstatus_r[2];
2987 float percent([pmstatus_r[3] floatValue]);
2988 [delegate_ setProgressPercent:(percent / 100)];
2990 NSString *string = pmstatus_r[4];
2992 if (type == "pmerror")
2993 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
2994 withObject:[NSArray arrayWithObjects:string, id, nil]
2997 else if (type == "pmstatus") {
2998 [delegate_ setProgressTitle:string];
2999 } else if (type == "pmconffile")
3000 [delegate_ setConfigurationData:string];
3002 lprintf("E:unknown pmstatus\n");
3004 lprintf("E:unknown status\n");
3010 - (void) _readOutput:(NSNumber *)fd { _pooled
3011 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3012 std::istream is(&ib);
3015 while (std::getline(is, line)) {
3016 lprintf("O:%s\n", line.c_str());
3017 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3027 - (Package *) packageWithName:(NSString *)name {
3028 @synchronized ([Database class]) {
3029 if (static_cast<pkgDepCache *>(cache_) == NULL)
3031 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3032 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3035 - (Database *) init {
3036 if ((self = [super init]) != nil) {
3043 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3044 apr_pool_create(&pool_, NULL);
3046 packages_ = [[NSMutableArray alloc] init];
3050 _assert(pipe(fds) != -1);
3053 _config->Set("APT::Keep-Fds::", cydiafd_);
3054 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3057 detachNewThreadSelector:@selector(_readCydia:)
3059 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3062 _assert(pipe(fds) != -1);
3066 detachNewThreadSelector:@selector(_readStatus:)
3068 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3071 _assert(pipe(fds) != -1);
3072 _assert(dup2(fds[0], 0) != -1);
3073 _assert(close(fds[0]) != -1);
3075 input_ = fdopen(fds[1], "a");
3077 _assert(pipe(fds) != -1);
3078 _assert(dup2(fds[1], 1) != -1);
3079 _assert(close(fds[1]) != -1);
3082 detachNewThreadSelector:@selector(_readOutput:)
3084 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3089 - (pkgCacheFile &) cache {
3093 - (pkgDepCache::Policy *) policy {
3097 - (pkgRecords *) records {
3101 - (pkgProblemResolver *) resolver {
3105 - (pkgAcquire &) fetcher {
3109 - (pkgSourceList &) list {
3113 - (NSArray *) packages {
3117 - (NSArray *) sources {
3118 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3119 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3120 [sources addObject:i->second];
3124 - (NSArray *) issues {
3125 if (cache_->BrokenCount() == 0)
3128 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3130 for (Package *package in packages_) {
3131 if (![package broken])
3133 pkgCache::PkgIterator pkg([package iterator]);
3135 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3136 [entry addObject:[package name]];
3137 [issues addObject:entry];
3139 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3143 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3144 pkgCache::DepIterator start;
3145 pkgCache::DepIterator end;
3146 dep.GlobOr(start, end); // ++dep
3148 if (!cache_->IsImportantDep(end))
3150 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3153 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3154 [entry addObject:failure];
3155 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3157 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3158 if (Package *package = [self packageWithName:name])
3159 name = [package name];
3160 [failure addObject:name];
3162 pkgCache::PkgIterator target(start.TargetPkg());
3163 if (target->ProvidesList != 0)
3164 [failure addObject:@"?"];
3166 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3168 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3169 else if (!cache_[target].CandidateVerIter(cache_).end())
3170 [failure addObject:@"-"];
3171 else if (target->ProvidesList == 0)
3172 [failure addObject:@"!"];
3174 [failure addObject:@"%"];
3178 if (start.TargetVer() != 0)
3179 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3190 - (bool) popErrorWithTitle:(NSString *)title {
3192 std::string message;
3194 while (!_error->empty()) {
3196 bool warning(!_error->PopMessage(error));
3200 size_t size(error.size());
3201 if (size == 0 || error[size - 1] != '\n')
3203 error.resize(size - 1);
3205 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3207 if (!message.empty())
3212 if (fatal && !message.empty())
3213 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3218 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3219 return [self popErrorWithTitle:title] || !success;
3222 - (void) reloadData { _pooled
3223 @synchronized ([Database class]) {
3224 @synchronized (self) {
3228 [packages_ removeAllObjects];
3254 apr_pool_clear(pool_);
3255 NSRecycleZone(zone_);
3257 int chk(creat("/tmp/cydia.chk", 0644));
3261 NSString *title(UCLocalize("DATABASE"));
3264 if (!cache_.Open(progress_, true)) { pop:
3266 bool warning(!_error->PopMessage(error));
3267 lprintf("cache_.Open():[%s]\n", error.c_str());
3269 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3270 [delegate_ repairWithSelector:@selector(configure)];
3271 else if (error == "The package lists or status file could not be parsed or opened.")
3272 [delegate_ repairWithSelector:@selector(update)];
3273 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3274 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3275 // else if (error == "The list of sources could not be read.")
3277 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3286 unlink("/tmp/cydia.chk");
3288 now_ = [[NSDate date] retain];
3290 policy_ = new pkgDepCache::Policy();
3291 records_ = new pkgRecords(cache_);
3292 resolver_ = new pkgProblemResolver(cache_);
3293 fetcher_ = new pkgAcquire(&status_);
3296 list_ = new pkgSourceList();
3297 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3300 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3301 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3305 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3308 if (cache_->BrokenCount() != 0) {
3309 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3312 if (cache_->BrokenCount() != 0) {
3313 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3317 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3323 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3324 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3325 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3326 // XXX: this could be more intelligent
3327 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3328 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3330 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3337 /*std::vector<Package *> packages;
3338 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3339 [packages_ release];
3344 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3345 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3346 //packages.push_back(package);
3347 [packages_ addObject:package];
3351 /*if (packages.empty())
3352 packages_ = [[NSArray alloc] init];
3354 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3357 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3358 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3359 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3367 /*if (!packages.empty())
3368 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3369 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3371 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3373 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3375 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3381 - (void) configure {
3382 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3383 system([dpkg UTF8String]);
3387 // XXX: I don't remember this condition
3392 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3394 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3396 if ([self popErrorWithTitle:title])
3400 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3403 public pkgArchiveCleaner
3406 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3411 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3418 fetcher_->Shutdown();
3420 pkgRecords records(cache_);
3422 lock_ = new FileFd();
3423 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3425 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3427 if ([self popErrorWithTitle:title])
3431 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3434 manager_ = (_system->CreatePM(cache_));
3435 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3442 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3444 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3446 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3448 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3449 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3452 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3457 bool failed = false;
3458 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3459 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3461 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3464 std::string uri = (*item)->DescURI();
3465 std::string error = (*item)->ErrorText;
3467 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3470 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3471 withObject:[NSArray arrayWithObjects:
3472 [NSString stringWithUTF8String:error.c_str()],
3484 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3486 if (_error->PendingError()) {
3491 if (result == pkgPackageManager::Failed) {
3496 if (result != pkgPackageManager::Completed) {
3501 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3503 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3505 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3506 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3509 if (![before isEqualToArray:after])
3514 NSString *title(UCLocalize("UPGRADE"));
3515 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3521 [self updateWithStatus:status_];
3524 - (void) setVisible {
3525 for (Package *package in packages_)
3526 [package setVisible];
3529 - (void) updateWithStatus:(Status &)status {
3530 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3531 NSString *title(UCLocalize("REFRESHING_DATA"));
3534 if (!list.ReadMainList())
3535 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3538 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3539 if ([self popErrorWithTitle:title])
3542 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3543 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */;
3545 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3549 - (void) setDelegate:(id)delegate {
3550 delegate_ = delegate;
3551 status_.setDelegate(delegate);
3552 progress_.setDelegate(delegate);
3555 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3556 SourceMap::const_iterator i(sources_.find(file->ID));
3557 return i == sources_.end() ? nil : i->second;
3563 /* Confirmation View {{{ */
3564 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3565 if (!iterator.end())
3566 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3567 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3569 pkgCache::PkgIterator package(dep.TargetPkg());
3572 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3579 /* Web Scripting {{{ */
3580 @interface CydiaObject : NSObject {
3584 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3587 @implementation CydiaObject
3590 [indirect_ release];
3594 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3595 if ((self = [super init]) != nil) {
3596 indirect_ = [indirect retain];
3600 + (NSArray *) _attributeKeys {
3601 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3604 - (NSArray *) attributeKeys {
3605 return [[self class] _attributeKeys];
3608 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3609 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3612 - (NSString *) device {
3613 return [[UIDevice currentDevice] uniqueIdentifier];
3616 #if 0 // XXX: implement!
3617 - (NSString *) mac {
3618 if (![indirect_ promptForSensitive:@"Mac Address"])
3622 - (NSString *) serial {
3623 if (![indirect_ promptForSensitive:@"Serial #"])
3627 - (NSString *) firewire {
3628 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3632 - (NSString *) imei {
3633 if (![indirect_ promptForSensitive:@"IMEI"])
3638 + (NSString *) webScriptNameForSelector:(SEL)selector {
3639 if (selector == @selector(close))
3641 else if (selector == @selector(getInstalledPackages))
3642 return @"getInstalledPackages";
3643 else if (selector == @selector(getPackageById:))
3644 return @"getPackageById";
3645 else if (selector == @selector(setAutoPopup:))
3646 return @"setAutoPopup";
3647 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3648 return @"setButtonImage";
3649 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3650 return @"setButtonTitle";
3651 else if (selector == @selector(setFinishHook:))
3652 return @"setFinishHook";
3653 else if (selector == @selector(setPopupHook:))
3654 return @"setPopupHook";
3655 else if (selector == @selector(setSpecial:))
3656 return @"setSpecial";
3657 else if (selector == @selector(setViewportWidth:))
3658 return @"setViewportWidth";
3659 else if (selector == @selector(supports:))
3661 else if (selector == @selector(stringWithFormat:arguments:))
3663 else if (selector == @selector(localizedStringForKey:value:table:))
3665 else if (selector == @selector(du:))
3667 else if (selector == @selector(statfs:))
3673 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3674 return [self webScriptNameForSelector:selector] == nil;
3677 - (BOOL) supports:(NSString *)feature {
3678 return [feature isEqualToString:@"window.open"];
3681 - (NSArray *) getInstalledPackages {
3682 NSArray *packages([[Database sharedInstance] packages]);
3683 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3684 for (Package *package in installed)
3685 if ([package installed] != nil)
3686 [installed addObject:package];
3690 - (Package *) getPackageById:(NSString *)id {
3691 Package *package([[Database sharedInstance] packageWithName:id]);
3696 - (NSArray *) statfs:(NSString *)path {
3699 if (path == nil || statfs([path UTF8String], &stat) == -1)
3702 return [NSArray arrayWithObjects:
3703 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3704 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3705 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3709 - (NSNumber *) du:(NSString *)path {
3710 NSNumber *value(nil);
3713 _assert(pipe(fds) != -1);
3715 pid_t pid(ExecFork());
3717 _assert(dup2(fds[1], 1) != -1);
3718 _assert(close(fds[0]) != -1);
3719 _assert(close(fds[1]) != -1);
3720 /* XXX: this should probably not use du */
3721 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3726 _assert(close(fds[1]) != -1);
3728 if (FILE *du = fdopen(fds[0], "r")) {
3730 while (fgets(line, sizeof(line), du) != NULL) {
3731 size_t length(strlen(line));
3732 while (length != 0 && line[length - 1] == '\n')
3733 line[--length] = '\0';
3734 if (char *tab = strchr(line, '\t')) {
3736 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3741 } else _assert(close(fds[0]));
3745 if (waitpid(pid, &status, 0) == -1)
3748 else _assert(false);
3757 - (void) setAutoPopup:(BOOL)popup {
3758 [indirect_ setAutoPopup:popup];
3761 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3762 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3765 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3766 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3769 - (void) setSpecial:(id)function {
3770 [indirect_ setSpecial:function];
3773 - (void) setFinishHook:(id)function {
3774 [indirect_ setFinishHook:function];
3777 - (void) setPopupHook:(id)function {
3778 [indirect_ setPopupHook:function];
3781 - (void) setViewportWidth:(float)width {
3782 [indirect_ setViewportWidth:width];
3785 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3786 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3787 unsigned count([arguments count]);
3789 for (unsigned i(0); i != count; ++i)
3790 values[i] = [arguments objectAtIndex:i];
3791 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3794 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3795 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3797 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3799 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3805 @interface CydiaBrowserView : BrowserView {
3806 CydiaObject *cydia_;
3811 @implementation CydiaBrowserView
3818 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3819 [super webView:sender didClearWindowObject:window forFrame:frame];
3820 [window setValue:cydia_ forKey:@"cydia"];
3823 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3824 if (System_ != NULL)
3825 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3826 if (Machine_ != NULL)
3827 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3828 if (UniqueID_ != nil)
3829 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
3831 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3834 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3835 NSMutableURLRequest *copy = [request mutableCopy];
3836 [self _setMoreHeaders:copy];
3840 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
3841 if ((self = [super initWithBook:book forWidth:width ofClass:[CydiaBrowserView class]]) != nil) {
3842 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3844 WebView *webview([webview_ webView]);
3846 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3848 NSString *application = package == nil ? @"Cydia" : [NSString
3849 stringWithFormat:@"Cydia/%@",
3854 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3856 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3857 if (Product_ != nil)
3858 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3860 [webview setApplicationNameForUserAgent:application];
3866 @protocol ConfirmationViewDelegate
3872 @interface ConfirmationView : CydiaBrowserView {
3873 _transient Database *database_;
3874 UIActionSheet *essential_;
3881 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3885 @implementation ConfirmationView
3892 if (essential_ != nil)
3893 [essential_ release];
3899 [book_ popFromSuperviewAnimated:YES];
3902 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3903 NSString *context([sheet context]);
3905 if ([context isEqualToString:@"remove"]) {
3913 [delegate_ confirm];
3919 } else if ([context isEqualToString:@"unable"]) {
3923 [super alertSheet:sheet buttonClicked:button];
3926 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3927 [super webView:sender didClearWindowObject:window forFrame:frame];
3928 [window setValue:changes_ forKey:@"changes"];
3929 [window setValue:issues_ forKey:@"issues"];
3930 [window setValue:sizes_ forKey:@"sizes"];
3933 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3934 if ((self = [super initWithBook:book]) != nil) {
3935 database_ = database;
3937 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3938 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3939 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3940 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3941 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3945 pkgDepCache::Policy *policy([database_ policy]);
3947 pkgCacheFile &cache([database_ cache]);
3948 NSArray *packages = [database_ packages];
3949 for (Package *package in packages) {
3950 pkgCache::PkgIterator iterator = [package iterator];
3951 pkgDepCache::StateCache &state(cache[iterator]);
3953 NSString *name([package name]);
3955 if (state.NewInstall())
3956 [installing addObject:name];
3957 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3958 [reinstalling addObject:name];
3959 else if (state.Upgrade())
3960 [upgrading addObject:name];
3961 else if (state.Downgrade())
3962 [downgrading addObject:name];
3963 else if (state.Delete()) {
3964 if ([package essential])
3966 [removing addObject:name];
3969 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3970 substrate_ |= DepSubstrate(iterator.CurrentVer());
3975 else if (Advanced_) {
3976 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
3978 essential_ = [[UIActionSheet alloc]
3979 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
3980 buttons:[NSArray arrayWithObjects:
3981 [NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")],
3982 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
3984 defaultButtonIndex:0
3989 [essential_ setDestructiveButtonIndex:1];
3990 [essential_ setBodyText:UCLocalize("REMOVING_ESSENTIALS_EX")];
3992 essential_ = [[UIActionSheet alloc]
3993 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
3994 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
3995 defaultButtonIndex:0
4000 [essential_ setBodyText:UCLocalize("UNABLE_TO_COMPLY_EX")];
4003 changes_ = [[NSArray alloc] initWithObjects:
4011 issues_ = [database_ issues];
4013 issues_ = [issues_ retain];
4015 sizes_ = [[NSArray alloc] initWithObjects:
4016 SizeString([database_ fetcher].FetchNeeded()),
4017 SizeString([database_ fetcher].PartialPresent()),
4018 SizeString([database_ cache]->UsrSize()),
4021 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4025 - (NSString *) backButtonTitle {
4026 return UCLocalize("CONFIRM");
4029 - (NSString *) leftButtonTitle {
4030 return [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")];
4033 - (id) rightButtonTitle {
4034 return issues_ != nil ? nil : [super rightButtonTitle];
4037 - (id) _rightButtonTitle {
4038 #if AlwaysReload || IgnoreInstall
4039 return [super _rightButtonTitle];
4041 return UCLocalize("CONFIRM");
4045 - (void) _leftButtonClicked {
4050 - (void) _rightButtonClicked {
4052 return [super _rightButtonClicked];
4054 if (essential_ != nil)
4055 [essential_ popupAlertAnimated:YES];
4059 [delegate_ confirm];
4067 /* Progress Data {{{ */
4068 @interface ProgressData : NSObject {
4074 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4081 @implementation ProgressData
4083 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4084 if ((self = [super init]) != nil) {
4085 selector_ = selector;
4105 /* Progress View {{{ */
4106 @interface ProgressView : UIView <
4107 ConfigurationDelegate,
4110 _transient Database *database_;
4112 UIView *background_;
4113 UITransitionView *transition_;
4115 UINavigationBar *navbar_;
4116 UIProgressBar *progress_;
4117 UITextView *output_;
4118 UITextLabel *status_;
4119 UIPushButton *close_;
4122 SHA1SumValue springlist_;
4123 SHA1SumValue notifyconf_;
4127 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
4128 - (void) setContentView:(UIView *)view;
4131 - (void) _retachThread;
4132 - (void) _detachNewThreadData:(ProgressData *)data;
4133 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4139 @protocol ProgressViewDelegate
4140 - (void) progressViewIsComplete:(ProgressView *)sender;
4143 @implementation ProgressView
4146 [transition_ setDelegate:nil];
4147 [navbar_ setDelegate:nil];
4150 if (background_ != nil)
4151 [background_ release];
4152 [transition_ release];
4155 [progress_ release];
4164 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
4165 if ((self = [super initWithFrame:frame]) != nil) {
4166 database_ = database;
4167 delegate_ = delegate;
4169 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
4170 [transition_ setDelegate:self];
4172 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
4174 background_ = [[UIView alloc] initWithFrame:[self bounds]];
4175 [background_ setBackgroundColor:[UIColor blackColor]];
4176 [self addSubview:background_];
4178 [self addSubview:transition_];
4180 CGSize navsize = [UINavigationBar defaultSize];
4181 CGRect navrect = {{0, 0}, navsize};
4183 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
4184 [overlay_ addSubview:navbar_];
4186 [navbar_ setBarStyle:1];
4187 [navbar_ setDelegate:self];
4189 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
4190 [navbar_ pushNavigationItem:navitem];
4192 CGRect bounds = [overlay_ bounds];
4193 CGSize prgsize = [UIProgressBar defaultSize];
4196 (bounds.size.width - prgsize.width) / 2,
4197 bounds.size.height - prgsize.height - 20
4200 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
4201 [progress_ setStyle:0];
4203 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
4205 bounds.size.height - prgsize.height - 50,
4206 bounds.size.width - 20,
4210 [status_ setColor:[UIColor whiteColor]];
4211 [status_ setBackgroundColor:[UIColor clearColor]];
4213 [status_ setCentersHorizontally:YES];
4214 //[status_ setFont:font];
4216 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
4218 navrect.size.height + 20,
4219 bounds.size.width - 20,
4220 bounds.size.height - navsize.height - 62 - navrect.size.height
4223 //[output_ setTextFont:@"Courier New"];
4224 [output_ setFont:[[output_ font] fontWithSize:12]];
4226 [output_ setTextColor:[UIColor whiteColor]];
4227 [output_ setBackgroundColor:[UIColor clearColor]];
4229 [output_ setMarginTop:0];
4230 [output_ setAllowsRubberBanding:YES];
4231 [output_ setEditable:NO];
4233 [overlay_ addSubview:output_];
4235 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
4237 bounds.size.height - prgsize.height - 50,
4238 bounds.size.width - 20,
4242 [close_ setAutosizesToFit:NO];
4243 [close_ setDrawsShadow:YES];
4244 [close_ setStretchBackground:YES];
4245 [close_ setEnabled:YES];
4247 UIFont *bold = [UIFont boldSystemFontOfSize:22];
4248 [close_ setTitleFont:bold];
4250 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4251 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4252 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4256 - (void) setContentView:(UIView *)view {
4257 view_ = [view retain];
4260 - (void) resetView {
4261 [transition_ transition:6 toView:view_];
4264 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4265 NSString *context([sheet context]);
4267 if ([context isEqualToString:@"conffile"]) {
4268 FILE *input = [database_ input];
4272 fprintf(input, "N\n");
4276 fprintf(input, "Y\n");
4286 - (void) closeButtonPushed {
4295 [delegate_ terminateWithSuccess];
4296 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4297 [delegate_ suspendWithAnimation:YES];
4299 [delegate_ suspend];*/
4303 system("launchctl stop com.apple.SpringBoard");
4307 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4316 - (void) _retachThread {
4317 UINavigationItem *item([navbar_ topItem]);
4318 [item setTitle:UCLocalize("COMPLETE")];
4320 [overlay_ addSubview:close_];
4321 [progress_ removeFromSuperview];
4322 [status_ removeFromSuperview];
4324 [database_ popErrorWithTitle:title_];
4325 [delegate_ progressViewIsComplete:self];
4329 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4332 MMap mmap(file, MMap::ReadOnly);
4334 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4335 if (!(notifyconf_ == sha1.Result()))
4342 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4345 MMap mmap(file, MMap::ReadOnly);
4347 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4348 if (!(springlist_ == sha1.Result()))
4354 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break;
4355 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4356 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4357 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4358 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4361 system("su -c /usr/bin/uicache mobile");
4363 [delegate_ setStatusBarShowsProgress:NO];
4366 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4367 [[data target] performSelector:[data selector] withObject:[data object]];
4370 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4373 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4379 title_ = [title retain];
4381 UINavigationItem *item([navbar_ topItem]);
4382 [item setTitle:title_];
4384 [status_ setText:nil];
4385 [output_ setText:@""];
4386 [progress_ setProgress:0];
4388 [close_ removeFromSuperview];
4389 [overlay_ addSubview:progress_];
4390 [overlay_ addSubview:status_];
4392 [delegate_ setStatusBarShowsProgress:YES];
4397 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4400 MMap mmap(file, MMap::ReadOnly);
4402 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4403 notifyconf_ = sha1.Result();
4409 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4412 MMap mmap(file, MMap::ReadOnly);
4414 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4415 springlist_ = sha1.Result();
4419 [transition_ transition:6 toView:overlay_];
4422 detachNewThreadSelector:@selector(_detachNewThreadData:)
4424 withObject:[[ProgressData alloc]
4425 initWithSelector:selector
4432 - (void) repairWithSelector:(SEL)selector {
4434 detachNewThreadSelector:selector
4437 title:UCLocalize("REPAIRING")
4441 - (void) setConfigurationData:(NSString *)data {
4443 performSelectorOnMainThread:@selector(_setConfigurationData:)
4449 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4450 CYActionSheet *sheet([[[CYActionSheet alloc]
4452 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4453 defaultButtonIndex:0
4456 [sheet setBodyText:error];
4457 [sheet yieldToPopupAlertAnimated:YES];
4461 - (void) setProgressTitle:(NSString *)title {
4463 performSelectorOnMainThread:@selector(_setProgressTitle:)
4469 - (void) setProgressPercent:(float)percent {
4471 performSelectorOnMainThread:@selector(_setProgressPercent:)
4472 withObject:[NSNumber numberWithFloat:percent]
4477 - (void) startProgress {
4480 - (void) addProgressOutput:(NSString *)output {
4482 performSelectorOnMainThread:@selector(_addProgressOutput:)
4488 - (bool) isCancelling:(size_t)received {
4492 - (void) _setConfigurationData:(NSString *)data {
4493 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4495 if (!conffile_r(data)) {
4496 lprintf("E:invalid conffile\n");
4500 NSString *ofile = conffile_r[1];
4501 //NSString *nfile = conffile_r[2];
4503 UIActionSheet *sheet = [[[UIActionSheet alloc]
4504 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4505 buttons:[NSArray arrayWithObjects:
4506 UCLocalize("KEEP_OLD_COPY"),
4507 UCLocalize("ACCEPT_NEW_COPY"),
4508 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4510 defaultButtonIndex:0
4515 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4516 [sheet popupAlertAnimated:YES];
4519 - (void) _setProgressTitle:(NSString *)title {
4520 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4521 for (size_t i(0), e([words count]); i != e; ++i) {
4522 NSString *word([words objectAtIndex:i]);
4523 if (Package *package = [database_ packageWithName:word])
4524 [words replaceObjectAtIndex:i withObject:[package name]];
4527 [status_ setText:[words componentsJoinedByString:@" "]];
4530 - (void) _setProgressPercent:(NSNumber *)percent {
4531 [progress_ setProgress:[percent floatValue]];
4534 - (void) _addProgressOutput:(NSString *)output {
4535 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4536 CGSize size = [output_ contentSize];
4537 CGRect rect = {{0, size.height}, {size.width, 0}};
4538 [output_ scrollRectToVisible:rect animated:YES];
4541 - (BOOL) isRunning {
4548 /* Package Cell {{{ */
4549 @interface ContentView : UIView {
4550 _transient id delegate_;
4555 @interface PackageCell : UITableViewCell {
4558 NSString *description_;
4564 ContentView *content_;
4570 - (PackageCell *) init;
4571 - (void) setPackage:(Package *)package;
4573 + (int) heightForPackage:(Package *)package;
4574 - (void) drawContentRect:(CGRect)rect;
4578 @implementation ContentView
4580 - (id) initWithFrame:(CGRect)frame {
4581 if ((self = [super initWithFrame:frame]) != nil) {
4585 - (void) setDelegate:(id)delegate {
4586 delegate_ = delegate;
4589 - (void) drawRect:(CGRect)rect {
4590 [super drawRect:rect];
4591 [delegate_ drawContentRect:rect];
4596 @implementation PackageCell
4598 - (void) clearPackage {
4609 if (description_ != nil) {
4610 [description_ release];
4614 if (source_ != nil) {
4619 if (badge_ != nil) {
4624 if (placard_ != nil) {
4634 [self clearPackage];
4641 return faded_ ? [self selectionPercent] : fade_;
4644 - (PackageCell *) init {
4645 CGRect frame(CGRectMake(0, 0, 320, 74));
4646 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4647 UIView *content([self contentView]);
4648 CGRect bounds([content bounds]);
4649 content_ = [[ContentView alloc] initWithFrame:bounds];
4650 [content_ setDelegate:self];
4651 [content_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
4652 [content_ setOpaque:YES];
4653 [content addSubview:content_];
4654 if ([self respondsToSelector:@selector(selectionPercent)])
4659 - (void) _setBackgroundColor {
4661 if (NSString *mode = [package_ mode]) {
4662 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4663 color = remove ? RemovingColor_ : InstallingColor_;
4665 color = [UIColor whiteColor];
4667 [content_ setBackgroundColor:color];
4668 [self setNeedsDisplay];
4671 - (void) setPackage:(Package *)package {
4672 [self clearPackage];
4675 Source *source = [package source];
4677 icon_ = [[package icon] retain];
4678 name_ = [[package name] retain];
4679 description_ = [[package shortDescription] retain];
4680 commercial_ = [package isCommercial];
4682 package_ = [package retain];
4684 NSString *label = nil;
4685 bool trusted = false;
4687 if (source != nil) {
4688 label = [source label];
4689 trusted = [source trusted];
4690 } else if ([[package id] isEqualToString:@"firmware"])
4691 label = UCLocalize("APPLE");
4693 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4695 NSString *from(label);
4697 NSString *section = [package simpleSection];
4698 if (section != nil && ![section isEqualToString:label]) {
4699 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4700 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4703 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4704 source_ = [from retain];
4706 if (NSString *purpose = [package primaryPurpose])
4707 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4708 badge_ = [badge_ retain];
4710 if ([package installed] != nil)
4711 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4712 placard_ = [placard_ retain];
4714 [self _setBackgroundColor];
4715 [content_ setNeedsDisplay];
4718 - (void) drawContentRect:(CGRect)rect {
4719 bool selected([self isSelected]);
4722 CGContextRef context(UIGraphicsGetCurrentContext());
4723 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4724 CGContextFillRect(context, rect);
4729 rect.size = [icon_ size];
4731 rect.size.width /= 2;
4732 rect.size.height /= 2;
4734 rect.origin.x = 25 - rect.size.width / 2;
4735 rect.origin.y = 25 - rect.size.height / 2;
4737 [icon_ drawInRect:rect];
4740 if (badge_ != nil) {
4741 CGSize size = [badge_ size];
4743 [badge_ drawAtPoint:CGPointMake(
4744 36 - size.width / 2,
4745 36 - size.height / 2
4753 UISetColor(commercial_ ? Purple_ : Black_);
4754 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(placard_ == nil ? 240 : 214) withFont:Font18Bold_ ellipsis:2];
4755 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4758 UISetColor(commercial_ ? Purplish_ : Gray_);
4759 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:274 withFont:Font14_ ellipsis:2];
4761 if (placard_ != nil)
4762 [placard_ drawAtPoint:CGPointMake(268, 9)];
4765 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4766 //[self _setBackgroundColor];
4767 [super setSelected:selected animated:fade];
4768 [content_ setNeedsDisplay];
4771 + (int) heightForPackage:(Package *)package {
4777 /* Section Cell {{{ */
4778 @interface SectionCell : UISimpleTableCell {
4784 _UISwitchSlider *switch_;
4789 - (void) setSection:(Section *)section editing:(BOOL)editing;
4793 @implementation SectionCell
4795 - (void) clearSection {
4796 if (basic_ != nil) {
4801 if (section_ != nil) {
4811 if (count_ != nil) {
4818 [self clearSection];
4825 if ((self = [super init]) != nil) {
4826 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4827 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4828 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventTouchUpInside];
4832 - (void) onSwitch:(id)sender {
4833 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4834 if (metadata == nil) {
4835 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4836 [Sections_ setObject:metadata forKey:basic_];
4840 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4843 - (void) setSection:(Section *)section editing:(BOOL)editing {
4844 if (editing != editing_) {
4846 [switch_ removeFromSuperview];
4848 [self addSubview:switch_];
4852 [self clearSection];
4854 if (section == nil) {
4855 name_ = [UCLocalize("ALL_PACKAGES") retain];
4858 basic_ = [section name];
4860 basic_ = [basic_ retain];
4862 section_ = [section localized];
4863 if (section_ != nil)
4864 section_ = [section_ retain];
4866 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4867 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4870 [switch_ setValue:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4874 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4875 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4883 float width(rect.size.width + 23);
4887 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 170) withFont:Font22Bold_ ellipsis:2];
4889 CGSize size = [count_ sizeWithFont:Font14_];
4893 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4895 [super drawContentInRect:rect selected:selected];
4901 /* File Table {{{ */
4902 @interface FileTable : RVPage {
4903 _transient Database *database_;
4906 NSMutableArray *files_;
4910 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4911 - (void) setPackage:(Package *)package;
4915 @implementation FileTable
4918 if (package_ != nil)
4927 - (int) numberOfRowsInTable:(UITable *)table {
4928 return files_ == nil ? 0 : [files_ count];
4931 - (float) table:(UITable *)table heightForRow:(int)row {
4935 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4936 if (reusing == nil) {
4937 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4938 UIFont *font = [UIFont systemFontOfSize:16];
4939 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4941 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4945 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4949 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4950 if ((self = [super initWithBook:book]) != nil) {
4951 database_ = database;
4953 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4955 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4956 [self addSubview:list_];
4958 UITableColumn *column = [[[UITableColumn alloc]
4959 initWithTitle:UCLocalize("NAME")
4961 width:[self frame].size.width
4964 [list_ setDataSource:self];
4965 [list_ setSeparatorStyle:1];
4966 [list_ addTableColumn:column];
4967 [list_ setDelegate:self];
4968 [list_ setReusesTableCells:YES];
4972 - (void) setPackage:(Package *)package {
4973 if (package_ != nil) {
4974 [package_ autorelease];
4983 [files_ removeAllObjects];
4985 if (package != nil) {
4986 package_ = [package retain];
4987 name_ = [[package id] retain];
4989 if (NSArray *files = [package files])
4990 [files_ addObjectsFromArray:files];
4992 if ([files_ count] != 0) {
4993 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4994 [files_ removeObjectAtIndex:0];
4995 [files_ sortUsingSelector:@selector(compareByPath:)];
4997 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4998 [stack addObject:@"/"];
5000 for (int i(0), e([files_ count]); i != e; ++i) {
5001 NSString *file = [files_ objectAtIndex:i];
5002 while (![file hasPrefix:[stack lastObject]])
5003 [stack removeLastObject];
5004 NSString *directory = [stack lastObject];
5005 [stack addObject:[file stringByAppendingString:@"/"]];
5006 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5007 ([stack count] - 2) * 3, "",
5008 [file substringFromIndex:[directory length]]
5017 - (void) resetViewAnimated:(BOOL)animated {
5018 [list_ resetViewAnimated:animated];
5021 - (void) reloadData {
5022 [self setPackage:[database_ packageWithName:name_]];
5023 [self reloadButtons];
5026 - (NSString *) title {
5027 return UCLocalize("INSTALLED_FILES");
5030 - (NSString *) backButtonTitle {
5031 return UCLocalize("FILES");
5036 /* Package View {{{ */
5037 @interface PackageView : CydiaBrowserView {
5038 _transient Database *database_;
5042 NSMutableArray *buttons_;
5045 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5046 - (void) setPackage:(Package *)package;
5050 @implementation PackageView
5053 if (package_ != nil)
5062 if ([self retainCount] == 1)
5063 [delegate_ setPackageView:self];
5067 /* XXX: this is not safe at all... localization of /fail/ */
5068 - (void) _clickButtonWithName:(NSString *)name {
5069 if ([name isEqualToString:UCLocalize("CLEAR")])
5070 [delegate_ clearPackage:package_];
5071 else if ([name isEqualToString:UCLocalize("INSTALL")])
5072 [delegate_ installPackage:package_];
5073 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5074 [delegate_ installPackage:package_];
5075 else if ([name isEqualToString:UCLocalize("REMOVE")])
5076 [delegate_ removePackage:package_];
5077 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5078 [delegate_ installPackage:package_];
5079 else _assert(false);
5082 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5083 NSString *context([sheet context]);
5085 if ([context isEqualToString:@"modify"]) {
5086 int count = [buttons_ count];
5087 _assert(count != 0);
5088 _assert(button <= count + 1);
5090 if (count != button - 1)
5091 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
5095 [super alertSheet:sheet buttonClicked:button];
5098 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5099 return [super webView:sender didFinishLoadForFrame:frame];
5102 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5103 [super webView:sender didClearWindowObject:window forFrame:frame];
5104 [window setValue:package_ forKey:@"package"];
5107 - (bool) _allowJavaScriptPanel {
5112 - (void) __rightButtonClicked {
5113 int count([buttons_ count]);
5118 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5120 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
5121 [buttons addObjectsFromArray:buttons_];
5122 [buttons addObject:UCLocalize("CANCEL")];
5124 [delegate_ slideUp:[[[UIActionSheet alloc]
5127 defaultButtonIndex:([buttons count] - 1)
5134 - (void) _rightButtonClicked {
5136 [super _rightButtonClicked];
5138 [self __rightButtonClicked];
5142 - (id) _rightButtonTitle {
5143 int count = [buttons_ count];
5144 return count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0];
5147 - (NSString *) backButtonTitle {
5151 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5152 if ((self = [super initWithBook:book]) != nil) {
5153 database_ = database;
5154 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5155 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5159 - (void) setPackage:(Package *)package {
5160 if (package_ != nil) {
5161 [package_ autorelease];
5170 [buttons_ removeAllObjects];
5172 if (package != nil) {
5175 package_ = [package retain];
5176 name_ = [[package id] retain];
5177 commercial_ = [package isCommercial];
5179 if ([package_ mode] != nil)
5180 [buttons_ addObject:UCLocalize("CLEAR")];
5181 if ([package_ source] == nil);
5182 else if ([package_ upgradableAndEssential:NO])
5183 [buttons_ addObject:UCLocalize("UPGRADE")];
5184 else if ([package_ uninstalled])
5185 [buttons_ addObject:UCLocalize("INSTALL")];
5187 [buttons_ addObject:UCLocalize("REINSTALL")];
5188 if (![package_ uninstalled])
5189 [buttons_ addObject:UCLocalize("REMOVE")];
5191 if (special_ != NULL) {
5192 CGRect frame([webview_ frame]);
5193 frame.size.width = 320;
5194 frame.size.height = 0;
5195 [webview_ setFrame:frame];
5197 if ([scroller_ respondsToSelector:@selector(scrollPointVisibleAtTopLeft:)])
5198 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5200 [scroller_ scrollRectToVisible:CGRectZero animated:NO];
5203 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5205 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5207 [self setFinishHook:nil];
5208 [self setPopupHook:nil];
5211 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5212 [super callFunction:special_];
5216 [self reloadButtons];
5219 - (bool) isLoading {
5220 return commercial_ ? [super isLoading] : false;
5223 - (void) reloadData {
5224 [self setPackage:[database_ packageWithName:name_]];
5229 /* Package Table {{{ */
5230 @interface PackageTable : RVPage {
5231 _transient Database *database_;
5233 NSMutableArray *packages_;
5234 NSMutableArray *sections_;
5236 NSMutableArray *index_;
5237 NSMutableDictionary *indices_;
5240 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5242 - (void) setDelegate:(id)delegate;
5244 - (void) reloadData;
5245 - (void) resetCursor;
5247 - (UITableView *) list;
5249 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5253 @implementation PackageTable
5256 [list_ setDataSource:nil];
5259 [packages_ release];
5260 [sections_ release];
5267 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5268 NSInteger count([sections_ count]);
5269 return count == 0 ? 1 : count;
5272 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5273 if ([sections_ count] == 0)
5275 return [[sections_ objectAtIndex:section] name];
5278 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5279 if ([sections_ count] == 0)
5281 return [[sections_ objectAtIndex:section] count];
5284 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5285 Section *section([sections_ objectAtIndex:[path section]]);
5286 NSInteger row([path row]);
5287 Package *package([packages_ objectAtIndex:([section row] + row)]);
5291 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5292 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
5294 cell = [[[PackageCell alloc] init] autorelease];
5295 [cell setPackage:[self packageAtIndexPath:path]];
5299 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5301 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5304 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5305 Package *package([self packageAtIndexPath:path]);
5306 package = [database_ packageWithName:[package id]];
5307 PackageView *view([delegate_ packageView]);
5308 [view setPackage:package];
5309 [view setDelegate:delegate_];
5310 [book_ pushPage:view];
5314 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5315 return [packages_ count] > 20 ? index_ : nil;
5318 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5322 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5323 if ((self = [super initWithBook:book]) != nil) {
5324 database_ = database;
5325 title_ = [title retain];
5327 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5328 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5330 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5331 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5333 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5334 [list_ setDataSource:self];
5335 [list_ setDelegate:self];
5337 [self addSubview:list_];
5339 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5340 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5344 - (void) setDelegate:(id)delegate {
5345 delegate_ = delegate;
5348 - (bool) hasPackage:(Package *)package {
5352 - (void) reloadData {
5353 NSArray *packages = [database_ packages];
5355 [packages_ removeAllObjects];
5356 [sections_ removeAllObjects];
5358 _profile(PackageTable$reloadData$Filter)
5359 for (Package *package in packages)
5360 if ([self hasPackage:package])
5361 [packages_ addObject:package];
5364 [index_ removeAllObjects];
5365 [indices_ removeAllObjects];
5367 Section *section = nil;
5369 _profile(PackageTable$reloadData$Section)
5370 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5374 _profile(PackageTable$reloadData$Section$Package)
5375 package = [packages_ objectAtIndex:offset];
5376 index = [package index];
5379 if (section == nil || [section index] != index) {
5380 _profile(PackageTable$reloadData$Section$Allocate)
5381 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5384 [index_ addObject:[section name]];
5385 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5387 _profile(PackageTable$reloadData$Section$Add)
5388 [sections_ addObject:section];
5392 [section addToCount];
5396 _profile(PackageTable$reloadData$List)
5401 - (NSString *) title {
5405 - (void) resetViewAnimated:(BOOL)animated {
5406 [list_ resetViewAnimated:animated];
5409 - (void) resetCursor {
5410 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5413 - (UITableView *) list {
5417 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5418 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5423 /* Filtered Package Table {{{ */
5424 @interface FilteredPackageTable : PackageTable {
5430 - (void) setObject:(id)object;
5432 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5436 @implementation FilteredPackageTable
5444 - (void) setObject:(id)object {
5450 object_ = [object retain];
5453 - (bool) hasPackage:(Package *)package {
5454 _profile(FilteredPackageTable$hasPackage)
5455 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5459 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5460 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5462 object_ = object == nil ? nil : [object retain];
5464 /* XXX: this is an unsafe optimization of doomy hell */
5465 Method method(class_getInstanceMethod([Package class], filter));
5466 _assert(method != NULL);
5467 imp_ = method_getImplementation(method);
5468 _assert(imp_ != NULL);
5477 /* Add Source View {{{ */
5478 @interface AddSourceView : RVPage {
5479 _transient Database *database_;
5482 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5486 @implementation AddSourceView
5488 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5489 if ((self = [super initWithBook:book]) != nil) {
5490 database_ = database;
5496 /* Source Cell {{{ */
5497 @interface SourceCell : UITableCell {
5500 NSString *description_;
5506 - (SourceCell *) initWithSource:(Source *)source;
5510 @implementation SourceCell
5515 [description_ release];
5520 - (SourceCell *) initWithSource:(Source *)source {
5521 if ((self = [super init]) != nil) {
5523 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5525 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5526 icon_ = [icon_ retain];
5528 origin_ = [[source name] retain];
5529 label_ = [[source uri] retain];
5530 description_ = [[source description] retain];
5534 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5536 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5543 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5547 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5551 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5553 [super drawContentInRect:rect selected:selected];
5558 /* Source Table {{{ */
5559 @interface SourceTable : RVPage {
5560 _transient Database *database_;
5561 UISectionList *list_;
5562 NSMutableArray *sources_;
5563 UIActionSheet *alert_;
5567 UIProgressHUD *hud_;
5570 //NSURLConnection *installer_;
5571 NSURLConnection *trivial_;
5572 NSURLConnection *trivial_bz2_;
5573 NSURLConnection *trivial_gz_;
5574 //NSURLConnection *automatic_;
5579 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5583 @implementation SourceTable
5585 - (void) _deallocConnection:(NSURLConnection *)connection {
5586 if (connection != nil) {
5587 [connection cancel];
5588 //[connection setDelegate:nil];
5589 [connection release];
5594 [[list_ table] setDelegate:nil];
5595 [list_ setDataSource:nil];
5604 //[self _deallocConnection:installer_];
5605 [self _deallocConnection:trivial_];
5606 [self _deallocConnection:trivial_gz_];
5607 [self _deallocConnection:trivial_bz2_];
5608 //[self _deallocConnection:automatic_];
5615 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5616 return offset_ == 0 ? 1 : 2;
5619 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5620 switch (section + (offset_ == 0 ? 1 : 0)) {
5621 case 0: return UCLocalize("ENTERED_BY_USER");
5622 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5628 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5629 switch (section + (offset_ == 0 ? 1 : 0)) {
5631 case 1: return offset_;
5637 - (int) numberOfRowsInTable:(UITable *)table {
5638 return [sources_ count];
5641 - (float) table:(UITable *)table heightForRow:(int)row {
5642 Source *source = [sources_ objectAtIndex:row];
5643 return [source description] == nil ? 56 : 73;
5646 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5647 Source *source = [sources_ objectAtIndex:row];
5648 // XXX: weird warning, stupid selectors ;P
5649 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5652 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5656 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5660 - (void) tableRowSelected:(NSNotification*)notification {
5661 UITable *table([list_ table]);
5662 int row([table selectedRow]);
5666 Source *source = [sources_ objectAtIndex:row];
5668 PackageTable *packages = [[[FilteredPackageTable alloc]
5671 title:[source label]
5672 filter:@selector(isVisibleInSource:)
5676 [packages setDelegate:delegate_];
5678 [book_ pushPage:packages];
5681 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5682 Source *source = [sources_ objectAtIndex:row];
5683 return [source record] != nil;
5686 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5687 [[list_ table] setDeleteConfirmationRow:row];
5690 - (void) table:(UITable *)table deleteRow:(int)row {
5691 Source *source = [sources_ objectAtIndex:row];
5692 [Sources_ removeObjectForKey:[source key]];
5693 [delegate_ syncData];
5697 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5700 @"./", @"Distribution",
5701 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5703 [delegate_ syncData];
5706 - (NSString *) getWarning {
5707 NSString *href(href_);
5708 NSRange colon([href rangeOfString:@"://"]);
5709 if (colon.location != NSNotFound)
5710 href = [href substringFromIndex:(colon.location + 3)];
5711 href = [href stringByAddingPercentEscapes];
5712 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5713 href = [href stringByCachingURLWithCurrentCDN];
5715 NSURL *url([NSURL URLWithString:href]);
5717 NSStringEncoding encoding;
5718 NSError *error(nil);
5720 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5721 return [warning length] == 0 ? nil : warning;
5725 - (void) _endConnection:(NSURLConnection *)connection {
5726 NSURLConnection **field = NULL;
5727 if (connection == trivial_)
5729 else if (connection == trivial_bz2_)
5730 field = &trivial_bz2_;
5731 else if (connection == trivial_gz_)
5732 field = &trivial_gz_;
5733 _assert(field != NULL);
5734 [connection release];
5739 trivial_bz2_ == nil &&
5745 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5748 UIActionSheet *sheet = [[[UIActionSheet alloc]
5749 initWithTitle:UCLocalize("SOURCE_WARNING")
5750 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_ANYWAY"), UCLocalize("CANCEL"), nil]
5751 defaultButtonIndex:0
5756 [sheet setNumberOfRows:1];
5758 [sheet setBodyText:warning];
5759 [sheet popupAlertAnimated:YES];
5762 } else if (error_ != nil) {
5763 UIActionSheet *sheet = [[[UIActionSheet alloc]
5764 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5765 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5766 defaultButtonIndex:0
5771 [sheet setBodyText:[error_ localizedDescription]];
5772 [sheet popupAlertAnimated:YES];
5774 UIActionSheet *sheet = [[[UIActionSheet alloc]
5775 initWithTitle:UCLocalize("NOT_REPOSITORY")
5776 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5777 defaultButtonIndex:0
5782 [sheet setBodyText:UCLocalize("NOT_REPOSITORY_EX")];
5783 [sheet popupAlertAnimated:YES];
5786 [delegate_ setStatusBarShowsProgress:NO];
5787 [delegate_ removeProgressHUD:hud_];
5797 if (error_ != nil) {
5804 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5805 switch ([response statusCode]) {
5811 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5812 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5814 error_ = [error retain];
5815 [self _endConnection:connection];
5818 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5819 [self _endConnection:connection];
5822 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5823 NSMutableURLRequest *request = [NSMutableURLRequest
5824 requestWithURL:[NSURL URLWithString:href]
5825 cachePolicy:NSURLRequestUseProtocolCachePolicy
5826 timeoutInterval:20.0
5829 [request setHTTPMethod:method];
5831 if (Machine_ != NULL)
5832 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5833 if (UniqueID_ != nil)
5834 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5837 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5839 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5842 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5843 NSString *context([sheet context]);
5845 if ([context isEqualToString:@"source"]) {
5848 NSString *href = [[sheet textField] text];
5850 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5852 if (![href hasSuffix:@"/"])
5853 href_ = [href stringByAppendingString:@"/"];
5856 href_ = [href_ retain];
5858 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
5859 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5860 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5861 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5865 hud_ = [[delegate_ addProgressHUD] retain];
5866 [hud_ setText:UCLocalize("VERIFYING_URL")];
5876 } else if ([context isEqualToString:@"trivial"])
5878 else if ([context isEqualToString:@"urlerror"])
5880 else if ([context isEqualToString:@"warning"]) {
5899 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5900 if ((self = [super initWithBook:book]) != nil) {
5901 database_ = database;
5902 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5904 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5905 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5906 [list_ setShouldHideHeaderInShortLists:NO];
5908 [self addSubview:list_];
5909 [list_ setDataSource:self];
5911 UITableColumn *column = [[UITableColumn alloc]
5912 initWithTitle:UCLocalize("NAME")
5914 width:[self frame].size.width
5917 UITable *table = [list_ table];
5918 [table setSeparatorStyle:1];
5919 [table addTableColumn:column];
5920 [table setDelegate:self];
5924 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5925 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5929 - (void) reloadData {
5931 if (!list.ReadMainList())
5934 [sources_ removeAllObjects];
5935 [sources_ addObjectsFromArray:[database_ sources]];
5937 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5940 int count([sources_ count]);
5941 for (offset_ = 0; offset_ != count; ++offset_) {
5942 Source *source = [sources_ objectAtIndex:offset_];
5943 if ([source record] == nil)
5950 - (void) resetViewAnimated:(BOOL)animated {
5951 [list_ resetViewAnimated:animated];
5954 - (void) _leftButtonClicked {
5955 /*[book_ pushPage:[[[AddSourceView alloc]
5960 UIActionSheet *sheet = [[[UIActionSheet alloc]
5961 initWithTitle:UCLocalize("ENTER_APT_URL")
5962 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_SOURCE"), UCLocalize("CANCEL"), nil]
5963 defaultButtonIndex:0
5968 [sheet setNumberOfRows:1];
5970 [sheet addTextFieldWithValue:@"http://" label:@""];
5972 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5973 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5974 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5975 [traits setKeyboardType:UIKeyboardTypeURL];
5976 // XXX: UIReturnKeyDone
5977 [traits setReturnKeyType:UIReturnKeyNext];
5979 [sheet popupAlertAnimated:YES];
5982 - (void) _rightButtonClicked {
5983 UITable *table = [list_ table];
5984 BOOL editing = [table isRowDeletionEnabled];
5985 [table enableRowDeletion:!editing animated:YES];
5986 [book_ reloadButtonsForPage:self];
5989 - (NSString *) title {
5990 return UCLocalize("SOURCES");
5993 - (NSString *) leftButtonTitle {
5994 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("ADD") : nil;
5997 - (id) rightButtonTitle {
5998 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("DONE") : UCLocalize("EDIT");
6001 - (UINavigationButtonStyle) rightButtonStyle {
6002 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6008 /* Installed View {{{ */
6009 @interface InstalledView : RVPage {
6010 _transient Database *database_;
6011 FilteredPackageTable *packages_;
6015 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6019 @implementation InstalledView
6022 [packages_ release];
6026 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6027 if ((self = [super initWithBook:book]) != nil) {
6028 database_ = database;
6030 packages_ = [[FilteredPackageTable alloc]
6034 filter:@selector(isInstalledAndVisible:)
6035 with:[NSNumber numberWithBool:YES]
6038 [self addSubview:packages_];
6040 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6041 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6045 - (void) resetViewAnimated:(BOOL)animated {
6046 [packages_ resetViewAnimated:animated];
6049 - (void) reloadData {
6050 [packages_ reloadData];
6053 - (void) _rightButtonClicked {
6054 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6055 [packages_ reloadData];
6057 [book_ reloadButtonsForPage:self];
6060 - (NSString *) title {
6061 return UCLocalize("INSTALLED");
6064 - (NSString *) backButtonTitle {
6065 return UCLocalize("PACKAGES");
6068 - (id) rightButtonTitle {
6069 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE");
6072 - (UINavigationButtonStyle) rightButtonStyle {
6073 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6076 - (void) setDelegate:(id)delegate {
6077 [super setDelegate:delegate];
6078 [packages_ setDelegate:delegate];
6085 @interface HomeView : CydiaBrowserView {
6090 @implementation HomeView
6092 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6093 NSString *context([sheet context]);
6095 if ([context isEqualToString:@"about"])
6098 [super alertSheet:sheet buttonClicked:button];
6101 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6102 [super _setMoreHeaders:request];
6104 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6107 - (void) _leftButtonClicked {
6108 UIActionSheet *sheet = [[[UIActionSheet alloc]
6109 initWithTitle:UCLocalize("ABOUT_CYDIA")
6110 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
6111 defaultButtonIndex:0
6117 @"Copyright (C) 2008-2009\n"
6118 "Jay Freeman (saurik)\n"
6119 "saurik@saurik.com\n"
6120 "http://www.saurik.com/\n"
6123 "http://www.theokorigroup.com/\n"
6125 "College of Creative Studies,\n"
6126 "University of California,\n"
6128 "http://www.ccs.ucsb.edu/"
6131 [sheet popupAlertAnimated:YES];
6134 - (NSString *) leftButtonTitle {
6135 return UCLocalize("ABOUT");
6140 /* Manage View {{{ */
6141 @interface ManageView : CydiaBrowserView {
6146 @implementation ManageView
6148 - (NSString *) title {
6149 return UCLocalize("MANAGE");
6152 - (void) _leftButtonClicked {
6153 [delegate_ askForSettings];
6154 [delegate_ updateData];
6157 - (NSString *) leftButtonTitle {
6158 return UCLocalize("SETTINGS");
6162 - (id) _rightButtonTitle {
6163 return Queuing_ ? UCLocalize("QUEUE") : nil;
6166 - (UINavigationButtonStyle) rightButtonStyle {
6167 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6170 - (void) _rightButtonClicked {
6175 - (bool) isLoading {
6182 /* Cydia Book {{{ */
6183 @interface CYBook : RVBook <
6186 _transient Database *database_;
6187 UINavigationBar *overlay_;
6188 UINavigationBar *underlay_;
6189 UIProgressIndicator *indicator_;
6190 UITextLabel *prompt_;
6191 UIProgressBar *progress_;
6192 UINavigationButton *cancel_;
6196 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
6202 @implementation CYBook
6206 [indicator_ release];
6208 [progress_ release];
6213 - (NSString *) getTitleForPage:(RVPage *)page {
6214 return [super getTitleForPage:page];
6222 [UIView beginAnimations:nil context:NULL];
6224 CGRect ovrframe = [overlay_ frame];
6225 ovrframe.origin.y = 0;
6226 [overlay_ setFrame:ovrframe];
6228 CGRect barframe = [navbar_ frame];
6229 barframe.origin.y += ovrframe.size.height;
6230 [navbar_ setFrame:barframe];
6232 CGRect trnframe = [transition_ frame];
6233 trnframe.origin.y += ovrframe.size.height;
6234 trnframe.size.height -= ovrframe.size.height;
6235 [transition_ setFrame:trnframe];
6237 [UIView endAnimations];
6239 [indicator_ startAnimation];
6240 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6241 [progress_ setProgress:0];
6244 [overlay_ addSubview:cancel_];
6247 detachNewThreadSelector:@selector(_update)
6253 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6254 NSString *context([sheet context]);
6256 if ([context isEqualToString:@"refresh"])
6263 [indicator_ stopAnimation];
6265 [UIView beginAnimations:nil context:NULL];
6267 CGRect ovrframe = [overlay_ frame];
6268 ovrframe.origin.y = -ovrframe.size.height;
6269 [overlay_ setFrame:ovrframe];
6271 CGRect barframe = [navbar_ frame];
6272 barframe.origin.y -= ovrframe.size.height;
6273 [navbar_ setFrame:barframe];
6275 CGRect trnframe = [transition_ frame];
6276 trnframe.origin.y -= ovrframe.size.height;
6277 trnframe.size.height += ovrframe.size.height;
6278 [transition_ setFrame:trnframe];
6280 [UIView commitAnimations];
6282 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6285 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6286 if ((self = [super initWithFrame:frame]) != nil) {
6287 database_ = database;
6289 CGRect ovrrect([navbar_ bounds]);
6290 ovrrect.size.height = [UINavigationBar defaultSize].height;
6291 ovrrect.origin.y = -ovrrect.size.height;
6293 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6294 [self addSubview:overlay_];
6296 ovrrect.origin.y = frame.size.height;
6297 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6298 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6299 [self addSubview:underlay_];
6301 [overlay_ setBarStyle:1];
6302 [underlay_ setBarStyle:1];
6304 int barstyle([overlay_ _barStyle:NO]);
6305 bool ugly(barstyle == 0);
6307 UIProgressIndicatorStyle style = ugly ?
6308 UIProgressIndicatorStyleMediumBrown :
6309 UIProgressIndicatorStyleMediumWhite;
6311 CGSize indsize([UIProgressIndicator defaultSizeForStyle:style]);
6312 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6313 CGRect indrect = {{indoffset, indoffset}, indsize};
6315 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6316 [indicator_ setStyle:style];
6317 [overlay_ addSubview:indicator_];
6319 CGSize prmsize = {215, indsize.height + 4};
6322 indoffset * 2 + indsize.width,
6323 unsigned(ovrrect.size.height - prmsize.height) / 2 - 1
6326 UIFont *font([UIFont systemFontOfSize:15]);
6328 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6330 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6331 [prompt_ setBackgroundColor:[UIColor clearColor]];
6332 [prompt_ setFont:font];
6334 [overlay_ addSubview:prompt_];
6336 CGSize prgsize = {75, 100};
6339 ovrrect.size.width - prgsize.width - 10,
6340 (ovrrect.size.height - prgsize.height) / 2
6343 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6344 [progress_ setStyle:0];
6345 [overlay_ addSubview:progress_];
6347 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6348 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6350 CGRect frame = [cancel_ frame];
6351 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6352 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6353 [cancel_ setFrame:frame];
6355 [cancel_ setBarStyle:barstyle];
6359 - (void) _onCancel {
6361 [cancel_ removeFromSuperview];
6364 - (void) _update { _pooled
6366 status.setDelegate(self);
6367 [database_ updateWithStatus:status];
6370 performSelectorOnMainThread:@selector(_update_)
6376 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6377 [prompt_ setText:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6381 UIActionSheet *sheet = [[[UIActionSheet alloc]
6382 initWithTitle:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), UCLocalize("REFRESH")]
6383 buttons:[NSArray arrayWithObjects:
6386 defaultButtonIndex:0
6391 [sheet setBodyText:error];
6392 [sheet popupAlertAnimated:YES];
6394 [self reloadButtons];
6397 - (void) setProgressTitle:(NSString *)title {
6399 performSelectorOnMainThread:@selector(_setProgressTitle:)
6405 - (void) setProgressPercent:(float)percent {
6407 performSelectorOnMainThread:@selector(_setProgressPercent:)
6408 withObject:[NSNumber numberWithFloat:percent]
6413 - (void) startProgress {
6416 - (void) addProgressOutput:(NSString *)output {
6418 performSelectorOnMainThread:@selector(_addProgressOutput:)
6424 - (bool) isCancelling:(size_t)received {
6428 - (void) _setProgressTitle:(NSString *)title {
6429 [prompt_ setText:title];
6432 - (void) _setProgressPercent:(NSNumber *)percent {
6433 [progress_ setProgress:[percent floatValue]];
6436 - (void) _addProgressOutput:(NSString *)output {
6441 /* Cydia:// Protocol {{{ */
6442 @interface CydiaURLProtocol : NSURLProtocol {
6447 @implementation CydiaURLProtocol
6449 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6450 NSURL *url([request URL]);
6453 NSString *scheme([[url scheme] lowercaseString]);
6454 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6459 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6463 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6464 id<NSURLProtocolClient> client([self client]);
6466 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6468 NSData *data(UIImagePNGRepresentation(icon));
6470 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6471 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6472 [client URLProtocol:self didLoadData:data];
6473 [client URLProtocolDidFinishLoading:self];
6477 - (void) startLoading {
6478 id<NSURLProtocolClient> client([self client]);
6479 NSURLRequest *request([self request]);
6481 NSURL *url([request URL]);
6482 NSString *href([url absoluteString]);
6484 NSString *path([href substringFromIndex:8]);
6485 NSRange slash([path rangeOfString:@"/"]);
6488 if (slash.location == NSNotFound) {
6492 command = [path substringToIndex:slash.location];
6493 path = [path substringFromIndex:(slash.location + 1)];
6496 Database *database([Database sharedInstance]);
6498 if ([command isEqualToString:@"package-icon"]) {
6501 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6502 Package *package([database packageWithName:path]);
6505 UIImage *icon([package icon]);
6506 [self _returnPNGWithImage:icon forRequest:request];
6507 } else if ([command isEqualToString:@"source-icon"]) {
6510 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6511 NSString *source(Simplify(path));
6512 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6514 icon = [UIImage applicationImageNamed:@"unknown.png"];
6515 [self _returnPNGWithImage:icon forRequest:request];
6516 } else if ([command isEqualToString:@"uikit-image"]) {
6519 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6520 UIImage *icon(_UIImageWithName(path));
6521 [self _returnPNGWithImage:icon forRequest:request];
6522 } else if ([command isEqualToString:@"section-icon"]) {
6525 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6526 NSString *section(Simplify(path));
6527 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6529 icon = [UIImage applicationImageNamed:@"unknown.png"];
6530 [self _returnPNGWithImage:icon forRequest:request];
6532 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6536 - (void) stopLoading {
6542 /* Sections View {{{ */
6543 @interface SectionsView : RVPage {
6544 _transient Database *database_;
6545 NSMutableArray *sections_;
6546 NSMutableArray *filtered_;
6547 UITransitionView *transition_;
6553 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6554 - (void) reloadData;
6559 @implementation SectionsView
6562 [list_ setDataSource:nil];
6563 [list_ setDelegate:nil];
6565 [sections_ release];
6566 [filtered_ release];
6567 [transition_ release];
6569 [accessory_ release];
6573 - (int) numberOfRowsInTable:(UITable *)table {
6574 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6577 - (float) table:(UITable *)table heightForRow:(int)row {
6581 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6583 reusing = [[[SectionCell alloc] init] autorelease];
6584 [(SectionCell *)reusing setSection:(editing_ ?
6585 [sections_ objectAtIndex:row] :
6586 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6587 ) editing:editing_];
6591 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6595 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6599 - (void) tableRowSelected:(NSNotification *)notification {
6600 int row = [[notification object] selectedRow];
6611 title = UCLocalize("ALL_PACKAGES");
6613 section = [filtered_ objectAtIndex:(row - 1)];
6614 name = [section name];
6617 name = [NSString stringWithString:name];
6618 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6621 title = UCLocalize("NO_SECTION");
6625 PackageTable *table = [[[FilteredPackageTable alloc]
6629 filter:@selector(isVisibleInSection:)
6633 [table setDelegate:delegate_];
6635 [book_ pushPage:table];
6638 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6639 if ((self = [super initWithBook:book]) != nil) {
6640 database_ = database;
6642 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6643 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6645 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6646 [self addSubview:transition_];
6648 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6649 [transition_ transition:0 toView:list_];
6651 UITableColumn *column = [[[UITableColumn alloc]
6652 initWithTitle:UCLocalize("NAME")
6654 width:[self frame].size.width
6657 [list_ setDataSource:self];
6658 [list_ setSeparatorStyle:1];
6659 [list_ addTableColumn:column];
6660 [list_ setDelegate:self];
6661 [list_ setReusesTableCells:YES];
6665 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6666 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6670 - (void) reloadData {
6671 NSArray *packages = [database_ packages];
6673 [sections_ removeAllObjects];
6674 [filtered_ removeAllObjects];
6677 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6678 SectionMap sections;
6679 sections.resize(64);
6681 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6685 for (Package *package in packages) {
6686 NSString *name([package section]);
6687 NSString *key(name == nil ? @"" : name);
6692 _profile(SectionsView$reloadData$Section)
6693 section = §ions[key];
6694 if (*section == nil) {
6695 _profile(SectionsView$reloadData$Section$Allocate)
6696 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6701 [*section addToCount];
6703 _profile(SectionsView$reloadData$Filter)
6704 if (![package valid] || ![package visible])
6708 [*section addToRow];
6712 _profile(SectionsView$reloadData$Section)
6713 section = [sections objectForKey:key];
6714 if (section == nil) {
6715 _profile(SectionsView$reloadData$Section$Allocate)
6716 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6717 [sections setObject:section forKey:key];
6722 [section addToCount];
6724 _profile(SectionsView$reloadData$Filter)
6725 if (![package valid] || ![package visible])
6735 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6736 [sections_ addObject:i->second];
6738 [sections_ addObjectsFromArray:[sections allValues]];
6741 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6743 for (Section *section in sections_) {
6744 size_t count([section row]);
6748 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6749 [section setCount:count];
6750 [filtered_ addObject:section];
6757 - (void) resetView {
6759 [self _rightButtonClicked];
6762 - (void) resetViewAnimated:(BOOL)animated {
6763 [list_ resetViewAnimated:animated];
6766 - (void) _rightButtonClicked {
6767 if ((editing_ = !editing_))
6770 [delegate_ updateData];
6771 [book_ reloadTitleForPage:self];
6772 [book_ reloadButtonsForPage:self];
6775 - (NSString *) title {
6776 return editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS");
6779 - (NSString *) backButtonTitle {
6780 return UCLocalize("SECTIONS");
6783 - (id) rightButtonTitle {
6784 return [sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT");
6787 - (UINavigationButtonStyle) rightButtonStyle {
6788 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6791 - (UIView *) accessoryView {
6797 /* Changes View {{{ */
6798 @interface ChangesView : RVPage {
6799 _transient Database *database_;
6800 NSMutableArray *packages_;
6801 NSMutableArray *sections_;
6806 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6807 - (void) reloadData;
6811 @implementation ChangesView
6814 [list_ setDelegate:nil];
6815 [list_ setDataSource:nil];
6817 [packages_ release];
6818 [sections_ release];
6823 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6824 NSInteger count([sections_ count]);
6825 return count == 0 ? 1 : count;
6828 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6829 if ([sections_ count] == 0)
6831 return [[sections_ objectAtIndex:section] name];
6834 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6835 if ([sections_ count] == 0)
6837 return [[sections_ objectAtIndex:section] count];
6840 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6841 Section *section([sections_ objectAtIndex:[path section]]);
6842 NSInteger row([path row]);
6843 return [packages_ objectAtIndex:([section row] + row)];
6846 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6847 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
6849 cell = [[[PackageCell alloc] init] autorelease];
6850 [cell setPackage:[self packageAtIndexPath:path]];
6854 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6856 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6859 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6860 Package *package([self packageAtIndexPath:path]);
6861 PackageView *view([delegate_ packageView]);
6862 [view setDelegate:delegate_];
6863 [view setPackage:package];
6864 [book_ pushPage:view];
6868 - (void) _leftButtonClicked {
6869 [(CYBook *)book_ update];
6870 [self reloadButtons];
6873 - (void) _rightButtonClicked {
6874 [delegate_ distUpgrade];
6877 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6878 if ((self = [super initWithBook:book]) != nil) {
6879 database_ = database;
6881 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6882 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6884 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
6885 [self addSubview:list_];
6887 //XXX:[list_ setShouldHideHeaderInShortLists:NO];
6888 [list_ setDataSource:self];
6889 [list_ setDelegate:self];
6890 //[list_ setSectionListStyle:1];
6894 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6895 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6899 - (void) reloadData {
6900 NSArray *packages = [database_ packages];
6902 [packages_ removeAllObjects];
6903 [sections_ removeAllObjects];
6906 for (Package *package in packages)
6908 [package uninstalled] && [package valid] && [package visible] ||
6909 [package upgradableAndEssential:YES]
6911 [packages_ addObject:package];
6914 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6917 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6918 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6919 Section *section = nil;
6923 bool unseens = false;
6925 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6927 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6928 Package *package = [packages_ objectAtIndex:offset];
6930 BOOL uae = [package upgradableAndEssential:YES];
6936 _profile(ChangesView$reloadData$Remember)
6937 seen = [package seen];
6940 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6945 name = UCLocalize("UNKNOWN");
6947 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6951 _profile(ChangesView$reloadData$Allocate)
6952 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
6953 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6954 [sections_ addObject:section];
6958 [section addToCount];
6959 } else if ([package ignored])
6960 [ignored addToCount];
6963 [upgradable addToCount];
6968 CFRelease(formatter);
6971 Section *last = [sections_ lastObject];
6972 size_t count = [last count];
6973 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6974 [sections_ removeLastObject];
6977 if ([ignored count] != 0)
6978 [sections_ insertObject:ignored atIndex:0];
6980 [sections_ insertObject:upgradable atIndex:0];
6983 [self reloadButtons];
6986 - (void) resetViewAnimated:(BOOL)animated {
6987 [list_ resetViewAnimated:animated];
6990 - (NSString *) leftButtonTitle {
6991 return [(CYBook *)book_ updating] ? nil : UCLocalize("REFRESH");
6994 - (id) rightButtonTitle {
6995 return upgrades_ == 0 ? nil : [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6998 - (NSString *) title {
6999 return UCLocalize("CHANGES");
7004 /* Search View {{{ */
7005 @protocol SearchViewDelegate
7006 - (void) showKeyboard:(BOOL)show;
7009 @interface SearchView : RVPage {
7011 UISearchField *field_;
7012 FilteredPackageTable *table_;
7017 - (id) initWithBook:(RVBook *)book database:(Database *)database;
7018 - (void) reloadData;
7022 @implementation SearchView
7025 [field_ setDelegate:nil];
7027 [accessory_ release];
7034 - (void) _showKeyboard:(BOOL)show {
7035 CGSize keysize = [UIKeyboard defaultSize];
7036 CGRect keydown = [book_ pageBounds];
7037 CGRect keyup = keydown;
7038 keyup.size.height -= keysize.height - ButtonBarHeight_;
7040 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
7042 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
7043 [animation setSignificantRectFields:8];
7046 [animation setStartFrame:keydown];
7047 [animation setEndFrame:keyup];
7049 [animation setStartFrame:keyup];
7050 [animation setEndFrame:keydown];
7053 UIAnimator *animator = [UIAnimator sharedAnimator];
7056 addAnimations:[NSArray arrayWithObjects:animation, nil]
7057 withDuration:(KeyboardTime_ - delay)
7062 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
7064 [delegate_ showKeyboard:show];
7067 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
7068 [self _showKeyboard:YES];
7071 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
7072 [self _showKeyboard:NO];
7075 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
7077 NSString *text([field_ text]);
7078 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
7084 - (void) textFieldClearButtonPressed:(UITextField *)field {
7088 - (void) keyboardInputShouldDelete:(id)input {
7092 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
7093 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
7097 [field_ resignFirstResponder];
7102 - (id) initWithBook:(RVBook *)book database:(Database *)database {
7103 if ((self = [super initWithBook:book]) != nil) {
7104 CGRect pageBounds = [book_ pageBounds];
7106 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
7107 CGColor dimmed(space_, 0, 0, 0, 0.5);
7108 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
7110 table_ = [[FilteredPackageTable alloc]
7114 filter:@selector(isUnfilteredAndSearchedForBy:)
7118 [table_ setShouldHideHeaderInShortLists:NO];
7119 [self addSubview:table_];
7121 CGRect cnfrect = {{7, 38}, {17, 18}};
7128 area.size.width = [self bounds].size.width - area.origin.x * 2;
7129 area.size.height = [UISearchField defaultHeight];
7131 field_ = [[UISearchField alloc] initWithFrame:area];
7133 UIFont *font = [UIFont systemFontOfSize:16];
7134 [field_ setFont:font];
7136 [field_ setPlaceholder:UCLocalize("SEARCH_EX")];
7137 [field_ setDelegate:self];
7139 [field_ setPaddingTop:5];
7141 UITextInputTraits *traits([field_ textInputTraits]);
7142 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7143 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7144 [traits setReturnKeyType:UIReturnKeySearch];
7146 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
7148 accessory_ = [[UIView alloc] initWithFrame:accrect];
7149 [accessory_ addSubview:field_];
7151 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7152 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7156 - (void) resetViewAnimated:(BOOL)animated {
7157 [table_ resetViewAnimated:animated];
7160 - (void) _reloadData {
7163 - (void) reloadData {
7164 [table_ setObject:[field_ text]];
7165 _profile(SearchView$reloadData)
7166 [table_ reloadData];
7169 [table_ resetCursor];
7172 - (UIView *) accessoryView {
7176 - (NSString *) title {
7180 - (NSString *) backButtonTitle {
7181 return UCLocalize("SEARCH");
7184 - (void) setDelegate:(id)delegate {
7185 [table_ setDelegate:delegate];
7186 [super setDelegate:delegate];
7191 /* Settings View {{{ */
7192 @interface SettingsView : RVPage {
7193 _transient Database *database_;
7196 UIPreferencesTable *table_;
7197 _UISwitchSlider *subscribedSwitch_;
7198 _UISwitchSlider *ignoredSwitch_;
7199 UIPreferencesControlTableCell *subscribedCell_;
7200 UIPreferencesControlTableCell *ignoredCell_;
7203 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7207 @implementation SettingsView
7210 [table_ setDataSource:nil];
7213 if (package_ != nil)
7216 [subscribedSwitch_ release];
7217 [ignoredSwitch_ release];
7218 [subscribedCell_ release];
7219 [ignoredCell_ release];
7223 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7224 if (package_ == nil)
7230 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7231 if (package_ == nil)
7244 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7245 if (package_ == nil)
7258 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7259 if (package_ == nil)
7272 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7273 if (package_ == nil)
7276 _UISwitchSlider *slider([cell control]);
7277 BOOL value([slider value] != 0);
7278 NSMutableDictionary *metadata([package_ metadata]);
7281 if (NSNumber *number = [metadata objectForKey:key])
7282 before = [number boolValue];
7286 if (value != before) {
7287 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7289 [delegate_ updateData];
7293 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7294 [self onSomething:cell withKey:@"IsSubscribed"];
7297 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7298 [self onSomething:cell withKey:@"IsIgnored"];
7301 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7302 if (package_ == nil)
7306 case 0: switch (row) {
7308 return subscribedCell_;
7310 return ignoredCell_;
7314 case 1: switch (row) {
7316 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7317 [cell setShowSelection:NO];
7318 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7331 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7332 if ((self = [super initWithBook:book])) {
7333 database_ = database;
7334 name_ = [package retain];
7336 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7337 [self addSubview:table_];
7339 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7340 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
7342 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7343 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
7345 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7346 [subscribedCell_ setShowSelection:NO];
7347 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7348 [subscribedCell_ setControl:subscribedSwitch_];
7350 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7351 [ignoredCell_ setShowSelection:NO];
7352 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7353 [ignoredCell_ setControl:ignoredSwitch_];
7355 [table_ setDataSource:self];
7360 - (void) resetViewAnimated:(BOOL)animated {
7361 [table_ resetViewAnimated:animated];
7364 - (void) reloadData {
7365 if (package_ != nil)
7366 [package_ autorelease];
7367 package_ = [database_ packageWithName:name_];
7368 if (package_ != nil) {
7370 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7371 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7374 [table_ reloadData];
7377 - (NSString *) title {
7378 return UCLocalize("SETTINGS");
7384 /* Signature View {{{ */
7385 @interface SignatureView : CydiaBrowserView {
7386 _transient Database *database_;
7390 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7394 @implementation SignatureView
7401 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7403 [super webView:sender didClearWindowObject:window forFrame:frame];
7406 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7407 if ((self = [super initWithBook:book]) != nil) {
7408 database_ = database;
7409 package_ = [package retain];
7414 - (void) resetViewAnimated:(BOOL)animated {
7417 - (void) reloadData {
7418 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7424 @interface Cydia : UIApplication <
7425 ConfirmationViewDelegate,
7426 ProgressViewDelegate,
7435 UIToolbar *toolbar_;
7439 NSMutableArray *essential_;
7440 NSMutableArray *broken_;
7442 Database *database_;
7443 ProgressView *progress_;
7447 UIKeyboard *keyboard_;
7448 UIProgressHUD *hud_;
7450 SectionsView *sections_;
7451 ChangesView *changes_;
7452 ManageView *manage_;
7453 SearchView *search_;
7455 #if RecyclePackageViews
7456 NSMutableArray *details_;
7460 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7461 - (void) setPage:(RVPage *)page;
7465 static _finline void _setHomePage(Cydia *self) {
7466 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeView class]]];
7469 @implementation Cydia
7472 if ([broken_ count] != 0) {
7473 int count = [broken_ count];
7475 UIActionSheet *sheet = [[[UIActionSheet alloc]
7476 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7477 buttons:[NSArray arrayWithObjects:
7478 UCLocalize("FORCIBLY_CLEAR"),
7479 UCLocalize("TEMPORARY_IGNORE"),
7481 defaultButtonIndex:0
7486 [sheet setBodyText:UCLocalize("HALFINSTALLED_PACKAGE_EX")];
7487 [sheet popupAlertAnimated:YES];
7488 } else if (!Ignored_ && [essential_ count] != 0) {
7489 int count = [essential_ count];
7491 UIActionSheet *sheet = [[[UIActionSheet alloc]
7492 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7493 buttons:[NSArray arrayWithObjects:
7494 UCLocalize("UPGRADE_ESSENTIAL"),
7495 UCLocalize("COMPLETE_UPGRADE"),
7496 UCLocalize("TEMPORARY_IGNORE"),
7498 defaultButtonIndex:0
7503 [sheet setBodyText:UCLocalize("ESSENTIAL_UPGRADE_EX")];
7504 [sheet popupAlertAnimated:YES];
7508 - (void) _saveConfig {
7511 NSString *error(nil);
7512 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7514 NSError *error(nil);
7515 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7516 NSLog(@"failure to save metadata data: %@", error);
7519 NSLog(@"failure to serialize metadata: %@", error);
7527 - (void) _updateData {
7530 /* XXX: this is just stupid */
7531 if (tag_ != 2 && sections_ != nil)
7532 [sections_ reloadData];
7533 if (tag_ != 3 && changes_ != nil)
7534 [changes_ reloadData];
7535 if (tag_ != 5 && search_ != nil)
7536 [search_ reloadData];
7541 - (void) _reloadData {
7544 static bool loaded(false);
7545 UIProgressHUD *hud([self addProgressHUD]);
7546 [hud setText:(loaded ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7548 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7551 [self removeProgressHUD:hud];
7555 [essential_ removeAllObjects];
7556 [broken_ removeAllObjects];
7558 NSArray *packages([database_ packages]);
7559 for (Package *package in packages) {
7561 [broken_ addObject:package];
7562 if ([package upgradableAndEssential:NO]) {
7563 if ([package essential])
7564 [essential_ addObject:package];
7570 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7571 [toolbar_ setBadgeValue:badge forButton:3];
7572 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7573 [toolbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7574 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7575 [self setApplicationBadge:badge];
7577 [self setApplicationBadgeString:badge];
7579 [toolbar_ setBadgeValue:nil forButton:3];
7580 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7581 [toolbar_ setBadgeAnimated:NO forButton:3];
7582 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7583 [self removeApplicationBadge];
7584 else // XXX: maybe use setApplicationBadgeString also?
7585 [self setApplicationIconBadgeNumber:0];
7589 [toolbar_ setBadgeValue:nil forButton:4];
7593 if (loaded || ManualRefresh) loaded:
7598 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7599 NSTimeInterval interval([update timeIntervalSinceNow]);
7600 if (interval <= 0 && interval > -(15*60))
7608 - (void) updateData {
7609 [database_ setVisible];
7618 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
7619 _assert(file != NULL);
7621 for (NSString *key in [Sources_ allKeys]) {
7622 NSDictionary *source([Sources_ objectForKey:key]);
7624 fprintf(file, "%s %s %s\n",
7625 [[source objectForKey:@"Type"] UTF8String],
7626 [[source objectForKey:@"URI"] UTF8String],
7627 [[source objectForKey:@"Distribution"] UTF8String]
7636 detachNewThreadSelector:@selector(update_)
7639 title:UCLocalize("UPDATING_SOURCES")
7643 - (void) reloadData {
7644 @synchronized (self) {
7645 if (confirm_ == nil)
7651 pkgProblemResolver *resolver = [database_ resolver];
7653 resolver->InstallProtect();
7654 if (!resolver->Resolve(true))
7658 - (void) popUpBook:(RVBook *)book {
7659 [underlay_ popSubview:book];
7662 - (CGRect) popUpBounds {
7663 return [underlay_ bounds];
7667 if (![database_ prepare])
7670 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7671 [confirm_ setDelegate:self];
7673 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7674 [page setDelegate:self];
7676 [confirm_ setPage:page];
7677 [self popUpBook:confirm_];
7683 @synchronized (self) {
7688 - (void) clearPackage:(Package *)package {
7689 @synchronized (self) {
7696 - (void) installPackage:(Package *)package {
7697 @synchronized (self) {
7704 - (void) removePackage:(Package *)package {
7705 @synchronized (self) {
7712 - (void) distUpgrade {
7713 @synchronized (self) {
7714 if (![database_ upgrade])
7721 [self slideUp:[[[UIActionSheet alloc]
7723 buttons:[NSArray arrayWithObjects:UCLocalize("CONTINUE_QUEUING"), UCLocalize("CANCEL_CLEAR"), nil]
7724 defaultButtonIndex:1
7731 @synchronized (self) {
7734 if (confirm_ != nil) {
7742 [overlay_ removeFromSuperview];
7746 detachNewThreadSelector:@selector(perform)
7749 title:UCLocalize("RUNNING")
7753 - (void) progressViewIsComplete:(ProgressView *)progress {
7754 if (confirm_ != nil) {
7755 [underlay_ addSubview:overlay_];
7756 [confirm_ popFromSuperviewAnimated:NO];
7762 - (void) setPage:(RVPage *)page {
7763 [page resetViewAnimated:NO];
7764 [page setDelegate:self];
7765 [book_ setPage:page];
7768 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7769 CydiaBrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7770 [browser loadURL:url];
7774 - (SectionsView *) sectionsView {
7775 if (sections_ == nil)
7776 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7780 - (void) buttonBarItemTapped:(id)sender {
7781 unsigned tag = [sender tag];
7783 [book_ resetViewAnimated:YES];
7785 } else if (tag_ == 2)
7786 [[self sectionsView] resetView];
7789 case 1: _setHomePage(self); break;
7791 case 2: [self setPage:[self sectionsView]]; break;
7792 case 3: [self setPage:changes_]; break;
7793 case 4: [self setPage:manage_]; break;
7794 case 5: [self setPage:search_]; break;
7802 - (void) askForSettings {
7803 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
7805 CYActionSheet *role([[[CYActionSheet alloc]
7806 initWithTitle:UCLocalize("WHO_ARE_YOU")
7807 buttons:[NSArray arrayWithObjects:
7808 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
7809 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
7810 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
7812 defaultButtonIndex:-1
7815 [role setBodyText:UCLocalize("ROLE_EX")];
7817 int button([role yieldToPopupAlertAnimated:YES]);
7820 case 1: Role_ = @"User"; break;
7821 case 2: Role_ = @"Hacker"; break;
7822 case 3: Role_ = @"Developer"; break;
7827 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7831 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7838 - (void) setPackageView:(PackageView *)view {
7840 [view setPackage:nil];
7841 #if RecyclePackageViews
7842 if ([details_ count] < 3)
7843 [details_ addObject:view];
7848 - (PackageView *) _packageView {
7849 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7852 - (PackageView *) packageView {
7853 #if RecyclePackageViews
7855 size_t count([details_ count]);
7858 view = [self _packageView];
7860 [details_ addObject:[self _packageView]];
7862 view = [[[details_ lastObject] retain] autorelease];
7863 [details_ removeLastObject];
7870 return [self _packageView];
7874 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7875 NSString *context([sheet context]);
7877 if ([context isEqualToString:@"missing"])
7879 else if ([context isEqualToString:@"cancel"]) {
7896 @synchronized (self) {
7901 [toolbar_ setBadgeValue:UCLocalize("Q_D") forButton:4];
7905 if (confirm_ != nil) {
7910 } else if ([context isEqualToString:@"fixhalf"]) {
7913 @synchronized (self) {
7914 for (Package *broken in broken_) {
7917 NSString *id = [broken id];
7918 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7919 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7920 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7921 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7930 [broken_ removeAllObjects];
7938 } else if ([context isEqualToString:@"upgrade"]) {
7941 @synchronized (self) {
7942 for (Package *essential in essential_)
7943 [essential install];
7965 - (void) system:(NSString *)command { _pooled
7966 system([command UTF8String]);
7969 - (void) applicationWillSuspend {
7971 [super applicationWillSuspend];
7974 - (void) applicationSuspend:(__GSEvent *)event {
7975 if (hud_ == nil && ![progress_ isRunning])
7976 [super applicationSuspend:event];
7979 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7981 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7984 - (void) _setSuspended:(BOOL)value {
7986 [super _setSuspended:value];
7989 - (UIProgressHUD *) addProgressHUD {
7990 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
7991 [window_ setUserInteractionEnabled:NO];
7993 [progress_ addSubview:hud];
7997 - (void) removeProgressHUD:(UIProgressHUD *)hud {
7999 [hud removeFromSuperview];
8000 [window_ setUserInteractionEnabled:YES];
8003 - (RVPage *) pageForPackage:(NSString *)name {
8004 if (Package *package = [database_ packageWithName:name]) {
8005 PackageView *view([self packageView]);
8006 [view setPackage:package];
8009 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8010 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8011 return [self _pageForURL:url withClass:[CydiaBrowserView class]];
8015 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8019 NSString *href([url absoluteString]);
8020 if ([href hasPrefix:@"apptapp://package/"])
8021 return [self pageForPackage:[href substringFromIndex:18]];
8023 NSString *scheme([[url scheme] lowercaseString]);
8024 if (![scheme isEqualToString:@"cydia"])
8026 NSString *path([url absoluteString]);
8027 if ([path length] < 8)
8029 path = [path substringFromIndex:8];
8030 if (![path hasPrefix:@"/"])
8031 path = [@"/" stringByAppendingString:path];
8033 if ([path isEqualToString:@"/add-source"])
8034 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8035 else if ([path isEqualToString:@"/storage"])
8036 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CydiaBrowserView class]];
8037 else if ([path isEqualToString:@"/sources"])
8038 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8039 else if ([path isEqualToString:@"/packages"])
8040 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8041 else if ([path hasPrefix:@"/url/"])
8042 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CydiaBrowserView class]];
8043 else if ([path hasPrefix:@"/launch/"])
8044 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8045 else if ([path hasPrefix:@"/package-settings/"])
8046 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8047 else if ([path hasPrefix:@"/package-signature/"])
8048 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8049 else if ([path hasPrefix:@"/package/"])
8050 return [self pageForPackage:[path substringFromIndex:9]];
8051 else if ([path hasPrefix:@"/files/"]) {
8052 NSString *name = [path substringFromIndex:7];
8054 if (Package *package = [database_ packageWithName:name]) {
8055 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8056 [files setPackage:package];
8064 - (void) applicationOpenURL:(NSURL *)url {
8065 [super applicationOpenURL:url];
8067 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8068 [self setPage:page];
8069 [toolbar_ showSelectionForButton:tag];
8074 - (void) applicationDidFinishLaunching:(id)unused {
8075 [BrowserView _initialize];
8077 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8079 Font12_ = [[UIFont systemFontOfSize:12] retain];
8080 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8081 Font14_ = [[UIFont systemFontOfSize:14] retain];
8082 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8083 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8087 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8088 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8090 window_ = [[UIWindow alloc] initWithContentRect:[UIHardware fullScreenApplicationContentRect]];
8091 [window_ orderFront:self];
8092 [window_ makeKey:self];
8093 [window_ setHidden:NO];
8095 database_ = [Database sharedInstance];
8097 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8098 [database_ setDelegate:progress_];
8099 [window_ setContentView:progress_];
8101 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8102 [progress_ setContentView:underlay_];
8104 [progress_ resetView];
8107 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8108 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8109 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8110 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8111 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8112 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8113 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8114 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8115 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8118 [self setIdleTimerDisabled:YES];
8120 hud_ = [self addProgressHUD];
8121 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8122 [self setStatusBarShowsProgress:YES];
8124 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8126 [self setStatusBarShowsProgress:NO];
8127 [self removeProgressHUD:hud_];
8130 if (ExecFork() == 0) {
8131 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8132 perror("launchctl stop");
8139 [self askForSettings];
8142 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
8144 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8145 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
8146 0, 0, screenrect.size.width, screenrect.size.height - 48
8147 ) database:database_];
8149 [book_ setDelegate:self];
8151 [overlay_ addSubview:book_];
8153 NSArray *buttonitems = [NSArray arrayWithObjects:
8154 [NSDictionary dictionaryWithObjectsAndKeys:
8155 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8156 @"home-up.png", kUIButtonBarButtonInfo,
8157 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
8158 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
8159 self, kUIButtonBarButtonTarget,
8160 @"Cydia", kUIButtonBarButtonTitle,
8161 @"0", kUIButtonBarButtonType,
8164 [NSDictionary dictionaryWithObjectsAndKeys:
8165 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8166 @"install-up.png", kUIButtonBarButtonInfo,
8167 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
8168 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
8169 self, kUIButtonBarButtonTarget,
8170 UCLocalize("SECTIONS"), kUIButtonBarButtonTitle,
8171 @"0", kUIButtonBarButtonType,
8174 [NSDictionary dictionaryWithObjectsAndKeys:
8175 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8176 @"changes-up.png", kUIButtonBarButtonInfo,
8177 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
8178 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
8179 self, kUIButtonBarButtonTarget,
8180 UCLocalize("CHANGES"), kUIButtonBarButtonTitle,
8181 @"0", kUIButtonBarButtonType,
8184 [NSDictionary dictionaryWithObjectsAndKeys:
8185 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8186 @"manage-up.png", kUIButtonBarButtonInfo,
8187 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
8188 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
8189 self, kUIButtonBarButtonTarget,
8190 UCLocalize("MANAGE"), kUIButtonBarButtonTitle,
8191 @"0", kUIButtonBarButtonType,
8194 [NSDictionary dictionaryWithObjectsAndKeys:
8195 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8196 @"search-up.png", kUIButtonBarButtonInfo,
8197 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
8198 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
8199 self, kUIButtonBarButtonTarget,
8200 UCLocalize("SEARCH"), kUIButtonBarButtonTitle,
8201 @"0", kUIButtonBarButtonType,
8205 toolbar_ = [[UIToolbar alloc]
8207 withFrame:CGRectMake(
8208 0, screenrect.size.height - ButtonBarHeight_,
8209 screenrect.size.width, ButtonBarHeight_
8211 withItemList:buttonitems
8214 [toolbar_ setDelegate:self];
8215 [toolbar_ setBarStyle:1];
8216 [toolbar_ setButtonBarTrackingMode:2];
8218 int buttons[5] = {1, 2, 3, 4, 5};
8219 [toolbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
8220 [toolbar_ showButtonGroup:0 withDuration:0];
8222 for (int i = 0; i != 5; ++i)
8223 [[toolbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
8224 i * (screenrect.size.width / 5) + (screenrect.size.width / 5 - ButtonBarWidth_) / 2, 1,
8225 ButtonBarWidth_, ButtonBarHeight_
8228 [toolbar_ showSelectionForButton:1];
8229 [overlay_ addSubview:toolbar_];
8231 [UIKeyboard initImplementationNow];
8232 CGSize keysize = [UIKeyboard defaultSize];
8233 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
8234 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
8235 [overlay_ addSubview:keyboard_];
8237 [underlay_ addSubview:overlay_];
8241 [self sectionsView];
8242 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
8243 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
8245 manage_ = (ManageView *) [[self
8246 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8247 withClass:[ManageView class]
8250 #if RecyclePackageViews
8251 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8252 [details_ addObject:[self _packageView]];
8253 [details_ addObject:[self _packageView]];
8261 - (void) showKeyboard:(BOOL)show {
8262 CGSize keysize([UIKeyboard defaultSize]);
8263 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8264 CGRect keyup(keydown);
8265 keyup.origin.y -= keysize.height;
8267 UIFrameAnimation *animation([[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease]);
8268 [animation setSignificantRectFields:2];
8271 [animation setStartFrame:keydown];
8272 [animation setEndFrame:keyup];
8273 [keyboard_ activate];
8275 [animation setStartFrame:keyup];
8276 [animation setEndFrame:keydown];
8277 [keyboard_ deactivate];
8280 [[UIAnimator sharedAnimator]
8281 addAnimations:[NSArray arrayWithObjects:animation, nil]
8282 withDuration:KeyboardTime_
8287 - (void) slideUp:(UIActionSheet *)alert {
8288 [alert presentSheetInView:overlay_];
8294 id Alloc_(id self, SEL selector) {
8295 id object = alloc_(self, selector);
8296 lprintf("[%s]A-%p\n", self->isa->name, object);
8301 id Dealloc_(id self, SEL selector) {
8302 id object = dealloc_(self, selector);
8303 lprintf("[%s]D-%p\n", self->isa->name, object);
8307 Class $WebDefaultUIKitDelegate;
8309 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8310 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8311 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8312 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8315 int main(int argc, char *argv[]) { _pooled
8318 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8320 /* Library Hacks {{{ */
8321 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8323 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8324 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8325 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8326 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8327 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8330 /* Set Locale {{{ */
8331 Locale_ = CFLocaleCopyCurrent();
8332 Languages_ = [NSLocale preferredLanguages];
8333 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8334 //NSLog(@"%@", [Languages_ description]);
8337 if (Languages_ == nil || [Languages_ count] == 0)
8338 // XXX: consider just setting to C and then falling through?
8341 lang = [[Languages_ objectAtIndex:0] UTF8String];
8342 setenv("LANG", lang, true);
8345 //std::setlocale(LC_ALL, lang);
8346 NSLog(@"Setting Language: %s", lang);
8349 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8351 /* Parse Arguments {{{ */
8352 bool substrate(false);
8358 for (int argi(1); argi != argc; ++argi)
8359 if (strcmp(argv[argi], "--") == 0) {
8361 argv[argi] = argv[0];
8367 for (int argi(1); argi != arge; ++argi)
8368 if (strcmp(args[argi], "--substrate") == 0)
8371 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8375 App_ = [[NSBundle mainBundle] bundlePath];
8376 Home_ = NSHomeDirectory();
8382 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8383 alloc_ = alloc->method_imp;
8384 alloc->method_imp = (IMP) &Alloc_;*/
8386 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8387 dealloc_ = dealloc->method_imp;
8388 dealloc->method_imp = (IMP) &Dealloc_;*/
8390 /* System Information {{{ */
8394 size = sizeof(maxproc);
8395 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8396 perror("sysctlbyname(\"kern.maxproc\", ?)");
8397 else if (maxproc < 64) {
8399 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8400 perror("sysctlbyname(\"kern.maxproc\", #)");
8403 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8404 char *osversion = new char[size];
8405 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8406 perror("sysctlbyname(\"kern.osversion\", ?)");
8408 System_ = [NSString stringWithUTF8String:osversion];
8410 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8411 char *machine = new char[size];
8412 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8413 perror("sysctlbyname(\"hw.machine\", ?)");
8417 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8418 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8419 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8420 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8424 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8425 NSData *data((NSData *) ecid);
8426 size_t length([data length]);
8427 uint8_t bytes[length];
8428 [data getBytes:bytes];
8429 char string[length * 2 + 1];
8430 for (size_t i(0); i != length; ++i)
8431 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8432 ChipID_ = [NSString stringWithUTF8String:string];
8436 IOObjectRelease(service);
8440 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8442 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8443 Build_ = [system objectForKey:@"ProductBuildVersion"];
8444 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8445 Product_ = [info objectForKey:@"SafariProductVersion"];
8446 Safari_ = [info objectForKey:@"CFBundleVersion"];
8449 /* Load Database {{{ */
8451 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8453 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8456 if (Metadata_ == NULL)
8457 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8459 Settings_ = [Metadata_ objectForKey:@"Settings"];
8461 Packages_ = [Metadata_ objectForKey:@"Packages"];
8462 Sections_ = [Metadata_ objectForKey:@"Sections"];
8463 Sources_ = [Metadata_ objectForKey:@"Sources"];
8466 if (Settings_ != nil)
8467 Role_ = [Settings_ objectForKey:@"Role"];
8469 if (Packages_ == nil) {
8470 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8471 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8474 if (Sections_ == nil) {
8475 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8476 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8479 if (Sources_ == nil) {
8480 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8481 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8486 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8489 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8491 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8492 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8493 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8494 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8496 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8497 unlink("/tmp/.cydia.fw");
8499 } else if (access("/User", F_OK) != 0) {
8502 system("/usr/libexec/cydia/firmware.sh");
8506 _assert([[NSFileManager defaultManager]
8507 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8508 withIntermediateDirectories:YES
8513 if (access("/tmp/cydia.chk", F_OK) == 0) {
8514 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8515 _assert(errno == ENOENT);
8516 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8517 _assert(errno == ENOENT);
8520 /* APT Initialization {{{ */
8521 _assert(pkgInitConfig(*_config));
8522 _assert(pkgInitSystem(*_config, _system));
8525 _config->Set("APT::Acquire::Translation", lang);
8526 _config->Set("Acquire::http::Timeout", 15);
8527 _config->Set("Acquire::http::MaxParallel", 3);
8529 /* Color Choices {{{ */
8530 space_ = CGColorSpaceCreateDeviceRGB();
8532 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8533 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8534 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8535 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8536 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8537 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8538 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8539 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8540 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8542 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8543 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8545 /* UIKit Configuration {{{ */
8546 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8547 if ($GSFontSetUseLegacyFontMetrics != NULL)
8548 $GSFontSetUseLegacyFontMetrics(YES);
8550 UIKeyboardDisableAutomaticAppearance();
8553 Colon_ = UCLocalize("COLON_DELIMITED");
8554 Error_ = UCLocalize("ERROR");
8555 Warning_ = UCLocalize("WARNING");
8558 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8560 CGColorSpaceRelease(space_);