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 (0 && !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);
803 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
807 _finline operator id() {
808 return (NSString *) static_cast<CFStringRef>(*this);
812 /* C++ NSString Algorithm Adapters {{{ */
814 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
817 struct NSStringMapHash :
818 std::unary_function<NSString *, size_t>
820 _finline size_t operator ()(NSString *value) const {
821 return CFStringHashNSString((CFStringRef) value);
825 struct NSStringMapLess :
826 std::binary_function<NSString *, NSString *, bool>
828 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
829 return [lhs compare:rhs] == NSOrderedAscending;
833 struct NSStringMapEqual :
834 std::binary_function<NSString *, NSString *, bool>
836 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
837 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
838 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
839 //[lhs isEqualToString:rhs];
844 /* Perl-Compatible RegEx {{{ */
854 Pcre(const char *regex) :
859 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
862 lprintf("%d:%s\n", offset, error);
866 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
867 matches_ = new int[(capture_ + 1) * 3];
875 NSString *operator [](size_t match) {
876 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
879 bool operator ()(NSString *data) {
880 // XXX: length is for characters, not for bytes
881 return operator ()([data UTF8String], [data length]);
884 bool operator ()(const char *data, size_t size) {
886 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
890 /* Mime Addresses {{{ */
891 @interface Address : NSObject {
897 - (NSString *) address;
899 - (void) setAddress:(NSString *)address;
901 + (Address *) addressWithString:(NSString *)string;
902 - (Address *) initWithString:(NSString *)string;
905 @implementation Address
914 - (NSString *) name {
918 - (NSString *) address {
922 - (void) setAddress:(NSString *)address {
924 [address_ autorelease];
928 address_ = [address retain];
931 + (Address *) addressWithString:(NSString *)string {
932 return [[[Address alloc] initWithString:string] autorelease];
935 + (NSArray *) _attributeKeys {
936 return [NSArray arrayWithObjects:@"address", @"name", nil];
939 - (NSArray *) attributeKeys {
940 return [[self class] _attributeKeys];
943 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
944 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
947 - (Address *) initWithString:(NSString *)string {
948 if ((self = [super init]) != nil) {
949 const char *data = [string UTF8String];
950 size_t size = [string length];
952 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
954 if (address_r(data, size)) {
955 name_ = [address_r[1] retain];
956 address_ = [address_r[2] retain];
958 name_ = [string retain];
966 /* CoreGraphics Primitives {{{ */
977 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
980 Set(space, red, green, blue, alpha);
985 CGColorRelease(color_);
992 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
994 float color[] = {red, green, blue, alpha};
995 color_ = CGColorCreate(space, color);
998 operator CGColorRef() {
1004 /* Random Global Variables {{{ */
1005 static const int PulseInterval_ = 50000;
1006 static const int ButtonBarWidth_ = 60;
1007 static const int ButtonBarHeight_ = 48;
1008 static const float KeyboardTime_ = 0.3f;
1011 static NSArray *Finishes_;
1013 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1014 #define NotifyConfig_ "/etc/notify.conf"
1016 static bool Queuing_;
1018 static CGColor Blue_;
1019 static CGColor Blueish_;
1020 static CGColor Black_;
1021 static CGColor Off_;
1022 static CGColor White_;
1023 static CGColor Gray_;
1024 static CGColor Green_;
1025 static CGColor Purple_;
1026 static CGColor Purplish_;
1028 static UIColor *InstallingColor_;
1029 static UIColor *RemovingColor_;
1031 static NSString *App_;
1032 static NSString *Home_;
1034 static BOOL Advanced_;
1035 static BOOL Ignored_;
1037 static UIFont *Font12_;
1038 static UIFont *Font12Bold_;
1039 static UIFont *Font14_;
1040 static UIFont *Font18Bold_;
1041 static UIFont *Font22Bold_;
1043 static const char *Machine_ = NULL;
1044 static const NSString *System_ = NULL;
1045 static const NSString *SerialNumber_ = nil;
1046 static const NSString *ChipID_ = nil;
1047 static const NSString *Token_ = nil;
1048 static const NSString *UniqueID_ = nil;
1049 static const NSString *Build_ = nil;
1050 static const NSString *Product_ = nil;
1051 static const NSString *Safari_ = nil;
1053 static CFLocaleRef Locale_;
1054 static NSArray *Languages_;
1055 static CGColorSpaceRef space_;
1057 static bool reload_;
1059 static NSDictionary *SectionMap_;
1060 static NSMutableDictionary *Metadata_;
1061 static _transient NSMutableDictionary *Settings_;
1062 static _transient NSString *Role_;
1063 static _transient NSMutableDictionary *Packages_;
1064 static _transient NSMutableDictionary *Sections_;
1065 static _transient NSMutableDictionary *Sources_;
1066 static bool Changed_;
1067 static NSDate *now_;
1069 static bool IsWildcat_;
1072 static NSMutableArray *Documents_;
1076 /* Display Helpers {{{ */
1077 inline float Interpolate(float begin, float end, float fraction) {
1078 return (end - begin) * fraction + begin;
1081 /* XXX: localize this! */
1082 NSString *SizeString(double size) {
1083 bool negative = size < 0;
1088 while (size > 1024) {
1093 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1095 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1098 static _finline CFStringRef CFCString(const char *value) {
1099 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1102 const char *StripVersion_(const char *version) {
1103 const char *colon(strchr(version, ':'));
1105 version = colon + 1;
1109 CFStringRef StripVersion(const char *version) {
1110 const char *colon(strchr(version, ':'));
1112 version = colon + 1;
1113 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1115 return CFCString(version);
1118 NSString *LocalizeSection(NSString *section) {
1119 static Pcre title_r("^(.*?) \\((.*)\\)$");
1120 if (title_r(section)) {
1121 NSString *parent(title_r[1]);
1122 NSString *child(title_r[2]);
1124 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1125 LocalizeSection(parent),
1126 LocalizeSection(child)
1130 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1133 NSString *Simplify(NSString *title) {
1134 const char *data = [title UTF8String];
1135 size_t size = [title length];
1137 static Pcre square_r("^\\[(.*)\\]$");
1138 if (square_r(data, size))
1139 return Simplify(square_r[1]);
1141 static Pcre paren_r("^\\((.*)\\)$");
1142 if (paren_r(data, size))
1143 return Simplify(paren_r[1]);
1145 static Pcre title_r("^(.*?) \\((.*)\\)$");
1146 if (title_r(data, size))
1147 return Simplify(title_r[1]);
1153 NSString *GetLastUpdate() {
1154 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1157 return UCLocalize("NEVER_OR_UNKNOWN");
1159 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1160 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1162 CFRelease(formatter);
1164 return [(NSString *) formatted autorelease];
1167 bool isSectionVisible(NSString *section) {
1168 NSDictionary *metadata([Sections_ objectForKey:section]);
1169 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1170 return hidden == nil || ![hidden boolValue];
1173 /* Delegate Prototypes {{{ */
1177 @interface NSObject (ProgressDelegate)
1180 @protocol ProgressDelegate
1181 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1182 - (void) setProgressTitle:(NSString *)title;
1183 - (void) setProgressPercent:(float)percent;
1184 - (void) startProgress;
1185 - (void) addProgressOutput:(NSString *)output;
1186 - (bool) isCancelling:(size_t)received;
1189 @protocol ConfigurationDelegate
1190 - (void) repairWithSelector:(SEL)selector;
1191 - (void) setConfigurationData:(NSString *)data;
1196 @protocol CydiaDelegate
1197 - (void) setPackageView:(PackageView *)view;
1198 - (void) clearPackage:(Package *)package;
1199 - (void) installPackage:(Package *)package;
1200 - (void) removePackage:(Package *)package;
1201 - (void) slideUp:(UIActionSheet *)alert;
1202 - (void) distUpgrade;
1203 - (void) updateData;
1205 - (void) askForSettings;
1206 - (UIProgressHUD *) addProgressHUD;
1207 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1208 - (RVPage *) pageForPackage:(NSString *)name;
1209 - (PackageView *) packageView;
1213 /* Status Delegation {{{ */
1215 public pkgAcquireStatus
1218 _transient NSObject<ProgressDelegate> *delegate_;
1226 void setDelegate(id delegate) {
1227 delegate_ = delegate;
1230 NSObject<ProgressDelegate> *getDelegate() const {
1234 virtual bool MediaChange(std::string media, std::string drive) {
1238 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1241 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1242 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1243 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1246 virtual void Done(pkgAcquire::ItemDesc &item) {
1249 virtual void Fail(pkgAcquire::ItemDesc &item) {
1251 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1252 item.Owner->Status == pkgAcquire::Item::StatDone
1256 std::string &error(item.Owner->ErrorText);
1260 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1261 NSArray *fields([description componentsSeparatedByString:@" "]);
1262 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1264 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1265 withObject:[NSArray arrayWithObjects:
1266 [NSString stringWithUTF8String:error.c_str()],
1273 virtual bool Pulse(pkgAcquire *Owner) {
1274 bool value = pkgAcquireStatus::Pulse(Owner);
1277 double(CurrentBytes + CurrentItems) /
1278 double(TotalBytes + TotalItems)
1281 [delegate_ setProgressPercent:percent];
1282 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1285 virtual void Start() {
1286 [delegate_ startProgress];
1289 virtual void Stop() {
1293 /* Progress Delegation {{{ */
1298 _transient id<ProgressDelegate> delegate_;
1302 virtual void Update() {
1303 /*if (abs(Percent - percent_) > 2)
1304 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1308 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1309 [delegate_ setProgressPercent:(Percent / 100)];*/
1319 void setDelegate(id delegate) {
1320 delegate_ = delegate;
1323 id getDelegate() const {
1327 virtual void Done() {
1329 //[delegate_ setProgressPercent:1];
1334 /* Database Interface {{{ */
1335 typedef std::map< unsigned long, _H<Source> > SourceMap;
1337 @interface Database : NSObject {
1343 pkgCacheFile cache_;
1344 pkgDepCache::Policy *policy_;
1345 pkgRecords *records_;
1346 pkgProblemResolver *resolver_;
1347 pkgAcquire *fetcher_;
1349 SPtr<pkgPackageManager> manager_;
1350 pkgSourceList *list_;
1353 NSMutableArray *packages_;
1355 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1364 + (Database *) sharedInstance;
1367 - (void) _readCydia:(NSNumber *)fd;
1368 - (void) _readStatus:(NSNumber *)fd;
1369 - (void) _readOutput:(NSNumber *)fd;
1373 - (Package *) packageWithName:(NSString *)name;
1375 - (pkgCacheFile &) cache;
1376 - (pkgDepCache::Policy *) policy;
1377 - (pkgRecords *) records;
1378 - (pkgProblemResolver *) resolver;
1379 - (pkgAcquire &) fetcher;
1380 - (pkgSourceList &) list;
1381 - (NSArray *) packages;
1382 - (NSArray *) sources;
1383 - (void) reloadData;
1391 - (void) setVisible;
1393 - (void) updateWithStatus:(Status &)status;
1395 - (void) setDelegate:(id)delegate;
1396 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1399 /* Delegate Helpers {{{ */
1400 @implementation NSObject(ProgressDelegate)
1402 - (void) _setProgressErrorPackage:(NSArray *)args {
1403 [self performSelector:@selector(setProgressError:forPackage:)
1404 withObject:[args objectAtIndex:0]
1405 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1409 - (void) _setProgressErrorTitle:(NSArray *)args {
1410 [self performSelector:@selector(setProgressError:withTitle:)
1411 withObject:[args objectAtIndex:0]
1412 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1416 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1417 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1418 withObject:[NSArray arrayWithObjects:error, title, nil]
1423 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1424 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1425 // XXX: holy typecast batman!
1426 [(id<ProgressDelegate>)self setProgressError:error withTitle:(package == nil ? id : [package name])];
1432 /* Source Class {{{ */
1433 @interface Source : NSObject {
1434 CYString depiction_;
1435 CYString description_;
1441 CYString distribution_;
1446 NSString *authority_;
1448 CYString defaultIcon_;
1450 NSDictionary *record_;
1454 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1456 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1458 - (NSString *) depictionForPackage:(NSString *)package;
1459 - (NSString *) supportForPackage:(NSString *)package;
1461 - (NSDictionary *) record;
1465 - (NSString *) distribution;
1466 - (NSString *) type;
1468 - (NSString *) host;
1470 - (NSString *) name;
1471 - (NSString *) description;
1472 - (NSString *) label;
1473 - (NSString *) origin;
1474 - (NSString *) version;
1476 - (NSString *) defaultIcon;
1480 @implementation Source
1484 distribution_.clear();
1487 description_.clear();
1493 defaultIcon_.clear();
1495 if (record_ != nil) {
1505 if (authority_ != nil) {
1506 [authority_ release];
1516 + (NSArray *) _attributeKeys {
1517 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1520 - (NSArray *) attributeKeys {
1521 return [[self class] _attributeKeys];
1524 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1525 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1528 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1531 trusted_ = index->IsTrusted();
1533 uri_.set(pool, index->GetURI());
1534 distribution_.set(pool, index->GetDist());
1535 type_.set(pool, index->GetType());
1537 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1538 if (dindex != NULL) {
1540 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1543 pkgTagFile tags(&fd);
1545 pkgTagSection section;
1552 {"default-icon", &defaultIcon_},
1553 {"depiction", &depiction_},
1554 {"description", &description_},
1556 {"origin", &origin_},
1557 {"support", &support_},
1558 {"version", &version_},
1561 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1562 const char *start, *end;
1564 if (section.Find(names[i].name_, start, end)) {
1565 CYString &value(*names[i].value_);
1566 value.set(pool, start, end - start);
1572 record_ = [Sources_ objectForKey:[self key]];
1574 record_ = [record_ retain];
1576 NSURL *url([NSURL URLWithString:uri_]);
1580 host_ = [[host_ lowercaseString] retain];
1585 authority_ = [url path];
1587 if (authority_ != nil)
1588 authority_ = [authority_ retain];
1591 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1592 if ((self = [super init]) != nil) {
1593 [self setMetaIndex:index inPool:pool];
1597 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1598 NSDictionary *lhr = [self record];
1599 NSDictionary *rhr = [source record];
1602 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1604 NSString *lhs = [self name];
1605 NSString *rhs = [source name];
1607 if ([lhs length] != 0 && [rhs length] != 0) {
1608 unichar lhc = [lhs characterAtIndex:0];
1609 unichar rhc = [rhs characterAtIndex:0];
1611 if (isalpha(lhc) && !isalpha(rhc))
1612 return NSOrderedAscending;
1613 else if (!isalpha(lhc) && isalpha(rhc))
1614 return NSOrderedDescending;
1617 return [lhs compare:rhs options:LaxCompareOptions_];
1620 - (NSString *) depictionForPackage:(NSString *)package {
1621 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1624 - (NSString *) supportForPackage:(NSString *)package {
1625 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1628 - (NSDictionary *) record {
1636 - (NSString *) uri {
1640 - (NSString *) distribution {
1641 return distribution_;
1644 - (NSString *) type {
1648 - (NSString *) key {
1649 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1652 - (NSString *) host {
1656 - (NSString *) name {
1657 return origin_.empty() ? authority_ : origin_;
1660 - (NSString *) description {
1661 return description_;
1664 - (NSString *) label {
1665 return label_.empty() ? authority_ : label_;
1668 - (NSString *) origin {
1672 - (NSString *) version {
1676 - (NSString *) defaultIcon {
1677 return defaultIcon_;
1682 /* Relationship Class {{{ */
1683 @interface Relationship : NSObject {
1688 - (NSString *) type;
1690 - (NSString *) name;
1694 @implementation Relationship
1702 - (NSString *) type {
1710 - (NSString *) name {
1717 /* Package Class {{{ */
1718 @interface Package : NSObject {
1722 pkgCache::VerIterator version_;
1723 pkgCache::PkgIterator iterator_;
1724 _transient Database *database_;
1725 pkgCache::VerFileIterator file_;
1732 NSString *section$_;
1739 CYString installed_;
1745 CYString depiction_;
1756 NSMutableArray *tags_;
1759 NSArray *relationships_;
1761 NSMutableDictionary *metadata_;
1762 _transient NSDate *firstSeen_;
1763 _transient NSDate *lastSeen_;
1767 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1768 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1770 - (pkgCache::PkgIterator) iterator;
1773 - (NSString *) section;
1774 - (NSString *) simpleSection;
1776 - (NSString *) longSection;
1777 - (NSString *) shortSection;
1781 - (Address *) maintainer;
1783 - (NSString *) longDescription;
1784 - (NSString *) shortDescription;
1787 - (NSMutableDictionary *) metadata;
1789 - (BOOL) subscribed;
1792 - (NSString *) latest;
1793 - (NSString *) installed;
1794 - (BOOL) uninstalled;
1797 - (BOOL) upgradableAndEssential:(BOOL)essential;
1800 - (BOOL) unfiltered;
1804 - (BOOL) halfConfigured;
1805 - (BOOL) halfInstalled;
1807 - (NSString *) mode;
1809 - (void) setVisible;
1812 - (NSString *) name;
1814 - (NSString *) homepage;
1815 - (NSString *) depiction;
1816 - (Address *) author;
1818 - (NSString *) support;
1820 - (NSArray *) files;
1821 - (NSArray *) relationships;
1822 - (NSArray *) warnings;
1823 - (NSArray *) applications;
1825 - (Source *) source;
1826 - (NSString *) role;
1828 - (BOOL) matches:(NSString *)text;
1830 - (bool) hasSupportingRole;
1831 - (BOOL) hasTag:(NSString *)tag;
1832 - (NSString *) primaryPurpose;
1833 - (NSArray *) purposes;
1834 - (bool) isCommercial;
1836 - (CYString &) cyname;
1838 - (uint32_t) compareBySection:(NSArray *)sections;
1840 - (uint32_t) compareForChanges;
1845 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1846 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1847 - (bool) isInstalledAndVisible:(NSNumber *)number;
1848 - (bool) isVisibleInSection:(NSString *)section;
1849 - (bool) isVisibleInSource:(Source *)source;
1853 uint32_t PackageChangesRadix(Package *self, void *) {
1858 uint32_t timestamp : 30;
1859 uint32_t ignored : 1;
1860 uint32_t upgradable : 1;
1864 bool upgradable([self upgradableAndEssential:YES]);
1865 value.bits.upgradable = upgradable ? 1 : 0;
1868 value.bits.timestamp = 0;
1869 value.bits.ignored = [self ignored] ? 0 : 1;
1870 value.bits.upgradable = 1;
1872 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1873 value.bits.ignored = 0;
1874 value.bits.upgradable = 0;
1877 return _not(uint32_t) - value.key;
1880 _finline static void Stifle(uint8_t &value) {
1883 uint32_t PackagePrefixRadix(Package *self, void *context) {
1884 size_t offset(reinterpret_cast<size_t>(context));
1885 CYString &name([self cyname]);
1887 size_t size(name.size());
1890 char *text(name.data());
1893 if (!isdigit(text[0]))
1897 while (size != digits && isdigit(text[digits]))
1907 if (offset == 0 && zeros != 0) {
1908 memset(data, '0', zeros);
1909 memcpy(data + zeros, text, 4 - zeros);
1911 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1912 if (size <= offset - zeros)
1915 text += offset - zeros;
1916 size -= offset - zeros;
1919 memcpy(data, text, 4);
1921 memcpy(data, text, size);
1922 memset(data + size, 0, 4 - size);
1925 for (size_t i(0); i != 4; ++i)
1926 if (isalpha(data[i]))
1931 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1933 /* XXX: ntohl may be more honest */
1934 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1937 CYString &(*PackageName)(Package *self, SEL sel);
1939 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1940 _profile(PackageNameCompare)
1941 CYString &lhi(PackageName(lhs, @selector(cyname)));
1942 CYString &rhi(PackageName(rhs, @selector(cyname)));
1943 CFStringRef lhn(lhi), rhn(rhi);
1946 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1947 else if (rhn == NULL)
1948 return NSOrderedDescending;
1950 _profile(PackageNameCompare$NumbersLast)
1951 if (!lhi.empty() && !rhi.empty()) {
1952 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1953 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1954 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1955 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1956 return lha ? NSOrderedAscending : NSOrderedDescending;
1960 CFIndex length = CFStringGetLength(lhn);
1962 _profile(PackageNameCompare$Compare)
1963 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1968 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1969 return PackageNameCompare(*lhs, *rhs, context);
1972 struct PackageNameOrdering :
1973 std::binary_function<Package *, Package *, bool>
1975 _finline bool operator ()(Package *lhs, Package *rhs) const {
1976 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1980 @implementation Package
1982 - (NSString *) description {
1983 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1989 if (section$_ != nil)
1990 [section$_ release];
1995 if (sponsor$_ != nil)
1996 [sponsor$_ release];
1997 if (author$_ != nil)
2004 if (relationships_ != nil)
2005 [relationships_ release];
2006 if (metadata_ != nil)
2007 [metadata_ release];
2012 + (NSString *) webScriptNameForSelector:(SEL)selector {
2013 if (selector == @selector(hasTag:))
2019 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2020 return [self webScriptNameForSelector:selector] == nil;
2023 + (NSArray *) _attributeKeys {
2024 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];
2027 - (NSArray *) attributeKeys {
2028 return [[self class] _attributeKeys];
2031 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2032 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2042 _profile(Package$parse)
2043 pkgRecords::Parser *parser;
2045 _profile(Package$parse$Lookup)
2046 parser = &[database_ records]->Lookup(file_);
2051 _profile(Package$parse$Find)
2057 {"depiction", &depiction_},
2058 {"homepage", &homepage_},
2059 {"website", &website},
2061 {"support", &support_},
2062 {"sponsor", &sponsor_},
2063 {"author", &author_},
2066 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2067 const char *start, *end;
2069 if (parser->Find(names[i].name_, start, end)) {
2070 CYString &value(*names[i].value_);
2071 _profile(Package$parse$Value)
2072 value.set(pool_, start, end - start);
2078 _profile(Package$parse$Tagline)
2079 const char *start, *end;
2080 if (parser->ShortDesc(start, end)) {
2081 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2084 while (stop != start && stop[-1] == '\r')
2086 tagline_.set(pool_, start, stop - start);
2090 _profile(Package$parse$Retain)
2091 if (homepage_.empty())
2092 homepage_ = website;
2093 if (homepage_ == depiction_)
2099 - (void) setVisible {
2100 visible_ = required_ && [self unfiltered];
2103 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2104 if ((self = [super init]) != nil) {
2105 _profile(Package$initWithVersion)
2106 @synchronized (database) {
2107 era_ = [database era];
2111 iterator_ = version.ParentPkg();
2112 database_ = database;
2114 _profile(Package$initWithVersion$Latest)
2115 latest_ = (NSString *) StripVersion(version_.VerStr());
2118 pkgCache::VerIterator current;
2119 _profile(Package$initWithVersion$Versions)
2120 current = iterator_.CurrentVer();
2122 installed_.set(pool_, StripVersion_(current.VerStr()));
2124 if (!version_.end())
2125 file_ = version_.FileList();
2127 pkgCache &cache([database_ cache]);
2128 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2132 _profile(Package$initWithVersion$Name)
2133 id_.set(pool_, iterator_.Name());
2134 name_.set(pool, iterator_.Display());
2138 _profile(Package$initWithVersion$Source)
2139 source_ = [database_ getSource:file_.File()];
2148 _profile(Package$initWithVersion$Tags)
2149 pkgCache::TagIterator tag(iterator_.TagList());
2151 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2153 const char *name(tag.Name());
2154 [tags_ addObject:(NSString *)CFCString(name)];
2155 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2156 role_ = (NSString *) CFCString(name + 6);
2157 if (required_ && strncmp(name, "require::", 9) == 0 && (
2162 } while (!tag.end());
2166 bool changed(false);
2167 NSString *key([id_ lowercaseString]);
2169 _profile(Package$initWithVersion$Metadata)
2170 metadata_ = [Packages_ objectForKey:key];
2172 if (metadata_ == nil) {
2175 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2176 firstSeen_, @"FirstSeen",
2177 latest_, @"LastVersion",
2182 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2183 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2185 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2186 subscribed_ = [subscribed boolValue];
2188 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2190 if (firstSeen_ == nil) {
2191 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2192 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2196 if (version == nil) {
2197 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2199 } else if (![version isEqualToString:latest_]) {
2200 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2202 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2207 metadata_ = [metadata_ retain];
2210 [Packages_ setObject:metadata_ forKey:key];
2215 _profile(Package$initWithVersion$Section)
2216 section_.set(pool_, iterator_.Section());
2219 obsolete_ = [self hasTag:@"cydia::obsolete"];
2220 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2222 } _end } return self;
2225 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2226 @synchronized ([Database class]) {
2227 pkgCache::VerIterator version;
2229 _profile(Package$packageWithIterator$GetCandidateVer)
2230 version = [database policy]->GetCandidateVer(iterator);
2236 return [[[Package alloc]
2237 initWithVersion:version
2244 - (pkgCache::PkgIterator) iterator {
2248 - (NSString *) section {
2249 if (section$_ == nil) {
2250 if (section_.empty())
2253 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2254 NSString *name(section_);
2257 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2258 if (NSString *rename = [value objectForKey:@"Rename"]) {
2263 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2267 - (NSString *) simpleSection {
2268 if (NSString *section = [self section])
2269 return Simplify(section);
2274 - (NSString *) longSection {
2275 return LocalizeSection([self section]);
2278 - (NSString *) shortSection {
2279 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2282 - (NSString *) uri {
2285 pkgIndexFile *index;
2286 pkgCache::PkgFileIterator file(file_.File());
2287 if (![database_ list].FindIndex(file, index))
2289 return [NSString stringWithUTF8String:iterator_->Path];
2290 //return [NSString stringWithUTF8String:file.Site()];
2291 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2295 - (Address *) maintainer {
2298 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2299 const std::string &maintainer(parser->Maintainer());
2300 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2304 return version_.end() ? 0 : version_->InstalledSize;
2307 - (NSString *) longDescription {
2310 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2311 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2313 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2314 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2315 if ([lines count] < 2)
2318 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2319 for (size_t i(1), e([lines count]); i != e; ++i) {
2320 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2321 [trimmed addObject:trim];
2324 return [trimmed componentsJoinedByString:@"\n"];
2327 - (NSString *) shortDescription {
2332 _profile(Package$index)
2333 CFStringRef name((CFStringRef) [self name]);
2334 if (CFStringGetLength(name) == 0)
2336 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2337 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2339 return toupper(character);
2343 - (NSMutableDictionary *) metadata {
2348 if (subscribed_ && lastSeen_ != nil)
2353 - (BOOL) subscribed {
2358 NSDictionary *metadata([self metadata]);
2359 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2360 return [ignored boolValue];
2365 - (NSString *) latest {
2369 - (NSString *) installed {
2373 - (BOOL) uninstalled {
2374 return installed_.empty();
2378 return !version_.end();
2381 - (BOOL) upgradableAndEssential:(BOOL)essential {
2382 _profile(Package$upgradableAndEssential)
2383 pkgCache::VerIterator current(iterator_.CurrentVer());
2385 return essential && essential_ && visible_;
2387 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2391 - (BOOL) essential {
2396 return [database_ cache][iterator_].InstBroken();
2399 - (BOOL) unfiltered {
2400 NSString *section([self section]);
2401 return !obsolete_ && [self hasSupportingRole] && (section == nil || isSectionVisible(section));
2409 unsigned char current(iterator_->CurrentState);
2410 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2413 - (BOOL) halfConfigured {
2414 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2417 - (BOOL) halfInstalled {
2418 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2422 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2423 return state.Mode != pkgDepCache::ModeKeep;
2426 - (NSString *) mode {
2427 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2429 switch (state.Mode) {
2430 case pkgDepCache::ModeDelete:
2431 if ((state.iFlags & pkgDepCache::Purge) != 0)
2435 case pkgDepCache::ModeKeep:
2436 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2437 return @"REINSTALL";
2438 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2442 case pkgDepCache::ModeInstall:
2443 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2444 return @"REINSTALL";
2445 else*/ switch (state.Status) {
2447 return @"DOWNGRADE";
2453 return @"NEW_INSTALL";
2464 - (NSString *) name {
2465 return name_.empty() ? id_ : name_;
2468 - (UIImage *) icon {
2469 NSString *section = [self simpleSection];
2473 if ([icon_ hasPrefix:@"file:///"])
2474 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2475 if (icon == nil) if (section != nil)
2476 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2477 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2478 if ([dicon hasPrefix:@"file:///"])
2479 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2481 icon = [UIImage applicationImageNamed:@"unknown.png"];
2485 - (NSString *) homepage {
2489 - (NSString *) depiction {
2490 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2493 - (Address *) sponsor {
2494 if (sponsor$_ == nil) {
2495 if (sponsor_.empty())
2497 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2501 - (Address *) author {
2502 if (author$_ == nil) {
2503 if (author_.empty())
2505 author$_ = [[Address addressWithString:author_] retain];
2509 - (NSString *) support {
2510 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2513 - (NSArray *) files {
2514 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2515 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2518 fin.open([path UTF8String]);
2523 while (std::getline(fin, line))
2524 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2529 - (NSArray *) relationships {
2530 return relationships_;
2533 - (NSArray *) warnings {
2534 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2535 const char *name(iterator_.Name());
2537 size_t length(strlen(name));
2538 if (length < 2) invalid:
2539 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2540 else for (size_t i(0); i != length; ++i)
2542 /* XXX: technically this is not allowed */
2543 (name[i] < 'A' || name[i] > 'Z') &&
2544 (name[i] < 'a' || name[i] > 'z') &&
2545 (name[i] < '0' || name[i] > '9') &&
2546 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2549 if (strcmp(name, "cydia") != 0) {
2552 bool _private = false;
2555 bool repository = [[self section] isEqualToString:@"Repositories"];
2557 if (NSArray *files = [self files])
2558 for (NSString *file in files)
2559 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2561 else if (!user && [file isEqualToString:@"/User"])
2563 else if (!_private && [file isEqualToString:@"/private"])
2565 else if (!stash && [file isEqualToString:@"/var/stash"])
2568 /* XXX: this is not sensitive enough. only some folders are valid. */
2569 if (cydia && !repository)
2570 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2572 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2574 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2576 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2579 return [warnings count] == 0 ? nil : warnings;
2582 - (NSArray *) applications {
2583 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2585 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2587 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2588 if (NSArray *files = [self files])
2589 for (NSString *file in files)
2590 if (application_r(file)) {
2591 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2592 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2593 if ([id isEqualToString:me])
2596 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2598 display = application_r[1];
2600 NSString *bundle([file stringByDeletingLastPathComponent]);
2601 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2602 if (icon == nil || [icon length] == 0)
2604 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2606 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2607 [applications addObject:application];
2609 [application addObject:id];
2610 [application addObject:display];
2611 [application addObject:url];
2614 return [applications count] == 0 ? nil : applications;
2617 - (Source *) source {
2619 @synchronized (database_) {
2620 if ([database_ era] != era_ || file_.end())
2623 source_ = [database_ getSource:file_.File()];
2635 - (NSString *) role {
2639 - (BOOL) matches:(NSString *)text {
2645 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2646 if (range.location != NSNotFound)
2649 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2650 if (range.location != NSNotFound)
2653 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2654 if (range.location != NSNotFound)
2660 - (bool) hasSupportingRole {
2663 if ([role_ isEqualToString:@"enduser"])
2665 if ([Role_ isEqualToString:@"User"])
2667 if ([role_ isEqualToString:@"hacker"])
2669 if ([Role_ isEqualToString:@"Hacker"])
2671 if ([role_ isEqualToString:@"developer"])
2673 if ([Role_ isEqualToString:@"Developer"])
2678 - (BOOL) hasTag:(NSString *)tag {
2679 return tags_ == nil ? NO : [tags_ containsObject:tag];
2682 - (NSString *) primaryPurpose {
2683 for (NSString *tag in tags_)
2684 if ([tag hasPrefix:@"purpose::"])
2685 return [tag substringFromIndex:9];
2689 - (NSArray *) purposes {
2690 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2691 for (NSString *tag in tags_)
2692 if ([tag hasPrefix:@"purpose::"])
2693 [purposes addObject:[tag substringFromIndex:9]];
2694 return [purposes count] == 0 ? nil : purposes;
2697 - (bool) isCommercial {
2698 return [self hasTag:@"cydia::commercial"];
2701 - (CYString &) cyname {
2702 return name_.empty() ? id_ : name_;
2705 - (uint32_t) compareBySection:(NSArray *)sections {
2706 NSString *section([self section]);
2707 for (size_t i(0), e([sections count]); i != e; ++i) {
2708 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2712 return _not(uint32_t);
2715 - (uint32_t) compareForChanges {
2720 uint32_t timestamp : 30;
2721 uint32_t ignored : 1;
2722 uint32_t upgradable : 1;
2726 bool upgradable([self upgradableAndEssential:YES]);
2727 value.bits.upgradable = upgradable ? 1 : 0;
2730 value.bits.timestamp = 0;
2731 value.bits.ignored = [self ignored] ? 0 : 1;
2732 value.bits.upgradable = 1;
2734 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2735 value.bits.ignored = 0;
2736 value.bits.upgradable = 0;
2739 return _not(uint32_t) - value.key;
2743 pkgProblemResolver *resolver = [database_ resolver];
2744 resolver->Clear(iterator_);
2745 resolver->Protect(iterator_);
2749 pkgProblemResolver *resolver = [database_ resolver];
2750 resolver->Clear(iterator_);
2751 resolver->Protect(iterator_);
2752 pkgCacheFile &cache([database_ cache]);
2753 cache->MarkInstall(iterator_, false);
2754 pkgDepCache::StateCache &state((*cache)[iterator_]);
2755 if (!state.Install())
2756 cache->SetReInstall(iterator_, true);
2760 pkgProblemResolver *resolver = [database_ resolver];
2761 resolver->Clear(iterator_);
2762 resolver->Protect(iterator_);
2763 resolver->Remove(iterator_);
2764 [database_ cache]->MarkDelete(iterator_, true);
2767 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2768 _profile(Package$isUnfilteredAndSearchedForBy)
2771 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2772 value &= [self unfiltered];
2775 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2776 value &= [self matches:search];
2783 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2784 if ([search length] == 0)
2787 _profile(Package$isUnfilteredAndSelectedForBy)
2790 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2791 value &= [self unfiltered];
2794 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2795 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2802 - (bool) isInstalledAndVisible:(NSNumber *)number {
2803 return (![number boolValue] || [self visible]) && ![self uninstalled];
2806 - (bool) isVisibleInSection:(NSString *)name {
2807 NSString *section = [self section];
2812 section == nil && [name length] == 0 ||
2813 [name isEqualToString:section]
2817 - (bool) isVisibleInSource:(Source *)source {
2818 return [self source] == source && [self visible];
2823 /* Section Class {{{ */
2824 @interface Section : NSObject {
2829 NSString *localized_;
2832 - (NSComparisonResult) compareByLocalized:(Section *)section;
2833 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2834 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2835 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2836 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2837 - (NSString *) name;
2844 - (void) addToCount;
2846 - (void) setCount:(size_t)count;
2847 - (NSString *) localized;
2851 @implementation Section
2855 if (localized_ != nil)
2856 [localized_ release];
2860 - (NSComparisonResult) compareByLocalized:(Section *)section {
2861 NSString *lhs(localized_);
2862 NSString *rhs([section localized]);
2864 /*if ([lhs length] != 0 && [rhs length] != 0) {
2865 unichar lhc = [lhs characterAtIndex:0];
2866 unichar rhc = [rhs characterAtIndex:0];
2868 if (isalpha(lhc) && !isalpha(rhc))
2869 return NSOrderedAscending;
2870 else if (!isalpha(lhc) && isalpha(rhc))
2871 return NSOrderedDescending;
2874 return [lhs compare:rhs options:LaxCompareOptions_];
2877 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2878 if ((self = [self initWithName:name localize:NO]) != nil) {
2879 if (localized != nil)
2880 localized_ = [localized retain];
2884 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2885 return [self initWithName:name row:0 localize:localize];
2888 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2889 if ((self = [super init]) != nil) {
2890 name_ = [name retain];
2894 localized_ = [LocalizeSection(name_) retain];
2898 /* XXX: localize the index thingees */
2899 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2900 if ((self = [super init]) != nil) {
2901 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2907 - (NSString *) name {
2927 - (void) addToCount {
2931 - (void) setCount:(size_t)count {
2935 - (NSString *) localized {
2942 static NSString *Colon_;
2943 static NSString *Error_;
2944 static NSString *Warning_;
2946 /* Database Implementation {{{ */
2947 @implementation Database
2949 + (Database *) sharedInstance {
2950 static Database *instance;
2951 if (instance == nil)
2952 instance = [[Database alloc] init];
2962 NSRecycleZone(zone_);
2963 // XXX: malloc_destroy_zone(zone_);
2964 apr_pool_destroy(pool_);
2968 - (void) _readCydia:(NSNumber *)fd { _pooled
2969 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2970 std::istream is(&ib);
2973 static Pcre finish_r("^finish:([^:]*)$");
2975 while (std::getline(is, line)) {
2976 const char *data(line.c_str());
2977 size_t size = line.size();
2978 lprintf("C:%s\n", data);
2980 if (finish_r(data, size)) {
2981 NSString *finish = finish_r[1];
2982 int index = [Finishes_ indexOfObject:finish];
2983 if (index != INT_MAX && index > Finish_)
2991 - (void) _readStatus:(NSNumber *)fd { _pooled
2992 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2993 std::istream is(&ib);
2996 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2997 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2999 while (std::getline(is, line)) {
3000 const char *data(line.c_str());
3001 size_t size(line.size());
3002 lprintf("S:%s\n", data);
3004 if (conffile_r(data, size)) {
3005 [delegate_ setConfigurationData:conffile_r[1]];
3006 } else if (strncmp(data, "status: ", 8) == 0) {
3007 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3008 [delegate_ setProgressTitle:string];
3009 } else if (pmstatus_r(data, size)) {
3010 std::string type([pmstatus_r[1] UTF8String]);
3011 NSString *id = pmstatus_r[2];
3013 float percent([pmstatus_r[3] floatValue]);
3014 [delegate_ setProgressPercent:(percent / 100)];
3016 NSString *string = pmstatus_r[4];
3018 if (type == "pmerror")
3019 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3020 withObject:[NSArray arrayWithObjects:string, id, nil]
3023 else if (type == "pmstatus") {
3024 [delegate_ setProgressTitle:string];
3025 } else if (type == "pmconffile")
3026 [delegate_ setConfigurationData:string];
3028 lprintf("E:unknown pmstatus\n");
3030 lprintf("E:unknown status\n");
3036 - (void) _readOutput:(NSNumber *)fd { _pooled
3037 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3038 std::istream is(&ib);
3041 while (std::getline(is, line)) {
3042 lprintf("O:%s\n", line.c_str());
3043 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3053 - (Package *) packageWithName:(NSString *)name {
3054 @synchronized ([Database class]) {
3055 if (static_cast<pkgDepCache *>(cache_) == NULL)
3057 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3058 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3061 - (Database *) init {
3062 if ((self = [super init]) != nil) {
3069 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3070 apr_pool_create(&pool_, NULL);
3072 packages_ = [[NSMutableArray alloc] init];
3076 _assert(pipe(fds) != -1);
3079 _config->Set("APT::Keep-Fds::", cydiafd_);
3080 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3083 detachNewThreadSelector:@selector(_readCydia:)
3085 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3088 _assert(pipe(fds) != -1);
3092 detachNewThreadSelector:@selector(_readStatus:)
3094 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3097 _assert(pipe(fds) != -1);
3098 _assert(dup2(fds[0], 0) != -1);
3099 _assert(close(fds[0]) != -1);
3101 input_ = fdopen(fds[1], "a");
3103 _assert(pipe(fds) != -1);
3104 _assert(dup2(fds[1], 1) != -1);
3105 _assert(close(fds[1]) != -1);
3108 detachNewThreadSelector:@selector(_readOutput:)
3110 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3115 - (pkgCacheFile &) cache {
3119 - (pkgDepCache::Policy *) policy {
3123 - (pkgRecords *) records {
3127 - (pkgProblemResolver *) resolver {
3131 - (pkgAcquire &) fetcher {
3135 - (pkgSourceList &) list {
3139 - (NSArray *) packages {
3143 - (NSArray *) sources {
3144 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3145 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3146 [sources addObject:i->second];
3150 - (NSArray *) issues {
3151 if (cache_->BrokenCount() == 0)
3154 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3156 for (Package *package in packages_) {
3157 if (![package broken])
3159 pkgCache::PkgIterator pkg([package iterator]);
3161 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3162 [entry addObject:[package name]];
3163 [issues addObject:entry];
3165 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3169 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3170 pkgCache::DepIterator start;
3171 pkgCache::DepIterator end;
3172 dep.GlobOr(start, end); // ++dep
3174 if (!cache_->IsImportantDep(end))
3176 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3179 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3180 [entry addObject:failure];
3181 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3183 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3184 if (Package *package = [self packageWithName:name])
3185 name = [package name];
3186 [failure addObject:name];
3188 pkgCache::PkgIterator target(start.TargetPkg());
3189 if (target->ProvidesList != 0)
3190 [failure addObject:@"?"];
3192 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3194 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3195 else if (!cache_[target].CandidateVerIter(cache_).end())
3196 [failure addObject:@"-"];
3197 else if (target->ProvidesList == 0)
3198 [failure addObject:@"!"];
3200 [failure addObject:@"%"];
3204 if (start.TargetVer() != 0)
3205 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3216 - (bool) popErrorWithTitle:(NSString *)title {
3218 std::string message;
3220 while (!_error->empty()) {
3222 bool warning(!_error->PopMessage(error));
3226 size_t size(error.size());
3227 if (size == 0 || error[size - 1] != '\n')
3229 error.resize(size - 1);
3231 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3233 if (!message.empty())
3238 if (fatal && !message.empty())
3239 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3244 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3245 return [self popErrorWithTitle:title] || !success;
3248 - (void) reloadData { _pooled
3249 @synchronized ([Database class]) {
3250 @synchronized (self) {
3254 [packages_ removeAllObjects];
3280 apr_pool_clear(pool_);
3281 NSRecycleZone(zone_);
3283 int chk(creat("/tmp/cydia.chk", 0644));
3287 NSString *title(UCLocalize("DATABASE"));
3290 if (!cache_.Open(progress_, true)) { pop:
3292 bool warning(!_error->PopMessage(error));
3293 lprintf("cache_.Open():[%s]\n", error.c_str());
3295 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3296 [delegate_ repairWithSelector:@selector(configure)];
3297 else if (error == "The package lists or status file could not be parsed or opened.")
3298 [delegate_ repairWithSelector:@selector(update)];
3299 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3300 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3301 // else if (error == "The list of sources could not be read.")
3303 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3312 unlink("/tmp/cydia.chk");
3314 now_ = [[NSDate date] retain];
3316 policy_ = new pkgDepCache::Policy();
3317 records_ = new pkgRecords(cache_);
3318 resolver_ = new pkgProblemResolver(cache_);
3319 fetcher_ = new pkgAcquire(&status_);
3322 list_ = new pkgSourceList();
3323 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3326 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3327 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3331 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3334 if (cache_->BrokenCount() != 0) {
3335 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3338 if (cache_->BrokenCount() != 0) {
3339 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3343 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3349 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3350 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3351 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3352 // XXX: this could be more intelligent
3353 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3354 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3356 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3363 /*std::vector<Package *> packages;
3364 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3365 [packages_ release];
3370 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3371 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3372 //packages.push_back(package);
3373 [packages_ addObject:package];
3377 /*if (packages.empty())
3378 packages_ = [[NSArray alloc] init];
3380 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3383 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3384 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3385 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3393 /*if (!packages.empty())
3394 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3395 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3397 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3399 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3401 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3407 - (void) configure {
3408 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3409 system([dpkg UTF8String]);
3413 // XXX: I don't remember this condition
3418 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3420 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3422 if ([self popErrorWithTitle:title])
3426 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3429 public pkgArchiveCleaner
3432 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3437 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3444 fetcher_->Shutdown();
3446 pkgRecords records(cache_);
3448 lock_ = new FileFd();
3449 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3451 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3453 if ([self popErrorWithTitle:title])
3457 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3460 manager_ = (_system->CreatePM(cache_));
3461 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3468 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3470 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3472 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3474 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3475 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3478 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3483 bool failed = false;
3484 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3485 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3487 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3490 std::string uri = (*item)->DescURI();
3491 std::string error = (*item)->ErrorText;
3493 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3496 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3497 withObject:[NSArray arrayWithObjects:
3498 [NSString stringWithUTF8String:error.c_str()],
3510 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3512 if (_error->PendingError()) {
3517 if (result == pkgPackageManager::Failed) {
3522 if (result != pkgPackageManager::Completed) {
3527 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3529 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3531 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3532 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3535 if (![before isEqualToArray:after])
3540 NSString *title(UCLocalize("UPGRADE"));
3541 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3547 [self updateWithStatus:status_];
3550 - (void) setVisible {
3551 for (Package *package in packages_)
3552 [package setVisible];
3555 - (void) updateWithStatus:(Status &)status {
3556 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3557 NSString *title(UCLocalize("REFRESHING_DATA"));
3560 if (!list.ReadMainList())
3561 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3564 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3565 if ([self popErrorWithTitle:title])
3568 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3569 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */;
3571 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3575 - (void) setDelegate:(id)delegate {
3576 delegate_ = delegate;
3577 status_.setDelegate(delegate);
3578 progress_.setDelegate(delegate);
3581 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3582 SourceMap::const_iterator i(sources_.find(file->ID));
3583 return i == sources_.end() ? nil : i->second;
3589 /* Confirmation View {{{ */
3590 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3591 if (!iterator.end())
3592 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3593 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3595 pkgCache::PkgIterator package(dep.TargetPkg());
3598 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3605 /* Web Scripting {{{ */
3606 @interface CydiaObject : NSObject {
3610 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3613 @implementation CydiaObject
3616 [indirect_ release];
3620 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3621 if ((self = [super init]) != nil) {
3622 indirect_ = [indirect retain];
3626 + (NSArray *) _attributeKeys {
3627 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3630 - (NSArray *) attributeKeys {
3631 return [[self class] _attributeKeys];
3634 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3635 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3638 - (NSString *) device {
3639 return [[UIDevice currentDevice] uniqueIdentifier];
3642 #if 0 // XXX: implement!
3643 - (NSString *) mac {
3644 if (![indirect_ promptForSensitive:@"Mac Address"])
3648 - (NSString *) serial {
3649 if (![indirect_ promptForSensitive:@"Serial #"])
3653 - (NSString *) firewire {
3654 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3658 - (NSString *) imei {
3659 if (![indirect_ promptForSensitive:@"IMEI"])
3664 + (NSString *) webScriptNameForSelector:(SEL)selector {
3665 if (selector == @selector(close))
3667 else if (selector == @selector(getInstalledPackages))
3668 return @"getInstalledPackages";
3669 else if (selector == @selector(getPackageById:))
3670 return @"getPackageById";
3671 else if (selector == @selector(setAutoPopup:))
3672 return @"setAutoPopup";
3673 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3674 return @"setButtonImage";
3675 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3676 return @"setButtonTitle";
3677 else if (selector == @selector(setFinishHook:))
3678 return @"setFinishHook";
3679 else if (selector == @selector(setPopupHook:))
3680 return @"setPopupHook";
3681 else if (selector == @selector(setSpecial:))
3682 return @"setSpecial";
3683 else if (selector == @selector(setToken:))
3685 else if (selector == @selector(setViewportWidth:))
3686 return @"setViewportWidth";
3687 else if (selector == @selector(supports:))
3689 else if (selector == @selector(stringWithFormat:arguments:))
3691 else if (selector == @selector(localizedStringForKey:value:table:))
3693 else if (selector == @selector(du:))
3695 else if (selector == @selector(statfs:))
3701 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3702 return [self webScriptNameForSelector:selector] == nil;
3705 - (BOOL) supports:(NSString *)feature {
3706 return [feature isEqualToString:@"window.open"];
3709 - (NSArray *) getInstalledPackages {
3710 NSArray *packages([[Database sharedInstance] packages]);
3711 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3712 for (Package *package in installed)
3713 if ([package installed] != nil)
3714 [installed addObject:package];
3718 - (Package *) getPackageById:(NSString *)id {
3719 Package *package([[Database sharedInstance] packageWithName:id]);
3724 - (NSArray *) statfs:(NSString *)path {
3727 if (path == nil || statfs([path UTF8String], &stat) == -1)
3730 return [NSArray arrayWithObjects:
3731 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3732 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3733 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3737 - (NSNumber *) du:(NSString *)path {
3738 NSNumber *value(nil);
3741 _assert(pipe(fds) != -1);
3743 pid_t pid(ExecFork());
3745 _assert(dup2(fds[1], 1) != -1);
3746 _assert(close(fds[0]) != -1);
3747 _assert(close(fds[1]) != -1);
3748 /* XXX: this should probably not use du */
3749 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3754 _assert(close(fds[1]) != -1);
3756 if (FILE *du = fdopen(fds[0], "r")) {
3758 while (fgets(line, sizeof(line), du) != NULL) {
3759 size_t length(strlen(line));
3760 while (length != 0 && line[length - 1] == '\n')
3761 line[--length] = '\0';
3762 if (char *tab = strchr(line, '\t')) {
3764 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3769 } else _assert(close(fds[0]));
3773 if (waitpid(pid, &status, 0) == -1)
3776 else _assert(false);
3785 - (void) setAutoPopup:(BOOL)popup {
3786 [indirect_ setAutoPopup:popup];
3789 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3790 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3793 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3794 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3797 - (void) setSpecial:(id)function {
3798 [indirect_ setSpecial:function];
3801 - (void) setToken:(NSString *)token {
3804 Token_ = [token retain];
3806 [Metadata_ setObject:Token_ forKey:@"Token"];
3810 - (void) setFinishHook:(id)function {
3811 [indirect_ setFinishHook:function];
3814 - (void) setPopupHook:(id)function {
3815 [indirect_ setPopupHook:function];
3818 - (void) setViewportWidth:(float)width {
3819 [indirect_ setViewportWidth:width];
3822 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3823 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3824 unsigned count([arguments count]);
3826 for (unsigned i(0); i != count; ++i)
3827 values[i] = [arguments objectAtIndex:i];
3828 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3831 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3832 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3834 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3836 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3842 @interface CydiaBrowserView : BrowserView {
3843 CydiaObject *cydia_;
3848 @implementation CydiaBrowserView
3855 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3858 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3859 [super webView:sender didClearWindowObject:window forFrame:frame];
3861 WebDataSource *source([frame dataSource]);
3862 NSURLResponse *response([source response]);
3863 NSURL *url([response URL]);
3864 NSString *scheme([url scheme]);
3866 NSHTTPURLResponse *http;
3867 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3868 http = (NSHTTPURLResponse *) response;
3872 NSDictionary *headers([http allHeaderFields]);
3873 NSString *host([url host]);
3874 [self setHeaders:headers forHost:host];
3876 if ([host isEqualToString:@"cydia.saurik.com"] || [scheme isEqualToString:@"file"])
3877 [window setValue:cydia_ forKey:@"cydia"];
3880 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3881 if (System_ != NULL)
3882 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3883 if (Machine_ != NULL)
3884 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3886 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3888 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3891 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3892 NSMutableURLRequest *copy = [request mutableCopy];
3893 [self _setMoreHeaders:copy];
3897 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
3898 if ((self = [super initWithBook:book forWidth:width ofClass:[CydiaBrowserView class]]) != nil) {
3899 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3901 WebView *webview([webview_ webView]);
3903 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3905 NSString *application = package == nil ? @"Cydia" : [NSString
3906 stringWithFormat:@"Cydia/%@",
3911 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3913 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3914 if (Product_ != nil)
3915 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3917 [webview setApplicationNameForUserAgent:application];
3923 @protocol ConfirmationViewDelegate
3929 @interface ConfirmationView : CydiaBrowserView {
3930 _transient Database *database_;
3931 UIActionSheet *essential_;
3938 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3942 @implementation ConfirmationView
3949 if (essential_ != nil)
3950 [essential_ release];
3956 [book_ popFromSuperviewAnimated:YES];
3959 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3960 NSString *context([sheet context]);
3962 if ([context isEqualToString:@"remove"]) {
3970 [delegate_ confirm];
3976 } else if ([context isEqualToString:@"unable"]) {
3980 [super alertSheet:sheet buttonClicked:button];
3983 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3984 [super webView:sender didClearWindowObject:window forFrame:frame];
3985 [window setValue:changes_ forKey:@"changes"];
3986 [window setValue:issues_ forKey:@"issues"];
3987 [window setValue:sizes_ forKey:@"sizes"];
3990 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3991 if ((self = [super initWithBook:book]) != nil) {
3992 database_ = database;
3994 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3995 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3996 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3997 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3998 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4002 pkgDepCache::Policy *policy([database_ policy]);
4004 pkgCacheFile &cache([database_ cache]);
4005 NSArray *packages = [database_ packages];
4006 for (Package *package in packages) {
4007 pkgCache::PkgIterator iterator = [package iterator];
4008 pkgDepCache::StateCache &state(cache[iterator]);
4010 NSString *name([package name]);
4012 if (state.NewInstall())
4013 [installing addObject:name];
4014 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4015 [reinstalling addObject:name];
4016 else if (state.Upgrade())
4017 [upgrading addObject:name];
4018 else if (state.Downgrade())
4019 [downgrading addObject:name];
4020 else if (state.Delete()) {
4021 if ([package essential])
4023 [removing addObject:name];
4026 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4027 substrate_ |= DepSubstrate(iterator.CurrentVer());
4032 else if (Advanced_) {
4033 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4035 essential_ = [[UIActionSheet alloc]
4036 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4037 buttons:[NSArray arrayWithObjects:
4038 [NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")],
4039 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4041 defaultButtonIndex:0
4046 [essential_ setDestructiveButtonIndex:1];
4047 [essential_ setBodyText:UCLocalize("REMOVING_ESSENTIALS_EX")];
4049 essential_ = [[UIActionSheet alloc]
4050 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4051 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4052 defaultButtonIndex:0
4057 [essential_ setBodyText:UCLocalize("UNABLE_TO_COMPLY_EX")];
4060 changes_ = [[NSArray alloc] initWithObjects:
4068 issues_ = [database_ issues];
4070 issues_ = [issues_ retain];
4072 sizes_ = [[NSArray alloc] initWithObjects:
4073 SizeString([database_ fetcher].FetchNeeded()),
4074 SizeString([database_ fetcher].PartialPresent()),
4075 SizeString([database_ cache]->UsrSize()),
4078 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4082 - (NSString *) backButtonTitle {
4083 return UCLocalize("CONFIRM");
4086 - (NSString *) leftButtonTitle {
4087 return [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")];
4090 - (id) rightButtonTitle {
4091 return issues_ != nil ? nil : [super rightButtonTitle];
4094 - (id) _rightButtonTitle {
4095 #if AlwaysReload || IgnoreInstall
4096 return [super _rightButtonTitle];
4098 return UCLocalize("CONFIRM");
4102 - (void) _leftButtonClicked {
4107 - (void) _rightButtonClicked {
4109 return [super _rightButtonClicked];
4111 if (essential_ != nil)
4112 [essential_ popupAlertAnimated:YES];
4116 [delegate_ confirm];
4124 /* Progress Data {{{ */
4125 @interface ProgressData : NSObject {
4131 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4138 @implementation ProgressData
4140 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4141 if ((self = [super init]) != nil) {
4142 selector_ = selector;
4162 /* Progress View {{{ */
4163 @interface ProgressView : UIView <
4164 ConfigurationDelegate,
4167 _transient Database *database_;
4169 UIView *background_;
4170 UITransitionView *transition_;
4172 UINavigationBar *navbar_;
4173 UIProgressBar *progress_;
4174 UITextView *output_;
4175 UITextLabel *status_;
4176 UIPushButton *close_;
4179 SHA1SumValue springlist_;
4180 SHA1SumValue notifyconf_;
4184 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
4185 - (void) setContentView:(UIView *)view;
4188 - (void) _retachThread;
4189 - (void) _detachNewThreadData:(ProgressData *)data;
4190 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4196 @protocol ProgressViewDelegate
4197 - (void) progressViewIsComplete:(ProgressView *)sender;
4200 @implementation ProgressView
4203 [transition_ setDelegate:nil];
4204 [navbar_ setDelegate:nil];
4207 if (background_ != nil)
4208 [background_ release];
4209 [transition_ release];
4212 [progress_ release];
4221 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
4222 if ((self = [super initWithFrame:frame]) != nil) {
4223 database_ = database;
4224 delegate_ = delegate;
4226 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
4227 [transition_ setDelegate:self];
4229 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
4231 background_ = [[UIView alloc] initWithFrame:[self bounds]];
4232 [background_ setBackgroundColor:[UIColor blackColor]];
4233 [self addSubview:background_];
4235 [self addSubview:transition_];
4237 CGSize navsize = [UINavigationBar defaultSize];
4238 CGRect navrect = {{0, 0}, navsize};
4240 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
4241 [overlay_ addSubview:navbar_];
4243 [navbar_ setBarStyle:1];
4244 [navbar_ setDelegate:self];
4246 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
4247 [navbar_ pushNavigationItem:navitem];
4249 CGRect bounds = [overlay_ bounds];
4250 CGSize prgsize = [UIProgressBar defaultSize];
4253 (bounds.size.width - prgsize.width) / 2,
4254 bounds.size.height - prgsize.height - 20
4257 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
4258 [progress_ setStyle:0];
4260 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
4262 bounds.size.height - prgsize.height - 50,
4263 bounds.size.width - 20,
4267 [status_ setColor:[UIColor whiteColor]];
4268 [status_ setBackgroundColor:[UIColor clearColor]];
4270 [status_ setCentersHorizontally:YES];
4271 //[status_ setFont:font];
4273 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
4275 navrect.size.height + 20,
4276 bounds.size.width - 20,
4277 bounds.size.height - navsize.height - 62 - navrect.size.height
4280 //[output_ setTextFont:@"Courier New"];
4281 [output_ setFont:[[output_ font] fontWithSize:12]];
4283 [output_ setTextColor:[UIColor whiteColor]];
4284 [output_ setBackgroundColor:[UIColor clearColor]];
4286 [output_ setMarginTop:0];
4287 [output_ setAllowsRubberBanding:YES];
4288 [output_ setEditable:NO];
4290 [overlay_ addSubview:output_];
4292 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
4294 bounds.size.height - prgsize.height - 50,
4295 bounds.size.width - 20,
4299 [close_ setAutosizesToFit:NO];
4300 [close_ setDrawsShadow:YES];
4301 [close_ setStretchBackground:YES];
4302 [close_ setEnabled:YES];
4304 UIFont *bold = [UIFont boldSystemFontOfSize:22];
4305 [close_ setTitleFont:bold];
4307 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4308 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4309 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4313 - (void) setContentView:(UIView *)view {
4314 view_ = [view retain];
4317 - (void) resetView {
4318 [transition_ transition:6 toView:view_];
4321 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4322 NSString *context([sheet context]);
4324 if ([context isEqualToString:@"conffile"]) {
4325 FILE *input = [database_ input];
4329 fprintf(input, "N\n");
4333 fprintf(input, "Y\n");
4343 - (void) closeButtonPushed {
4352 [delegate_ terminateWithSuccess];
4353 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4354 [delegate_ suspendWithAnimation:YES];
4356 [delegate_ suspend];*/
4360 system("launchctl stop com.apple.SpringBoard");
4364 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4373 - (void) _retachThread {
4374 UINavigationItem *item([navbar_ topItem]);
4375 [item setTitle:UCLocalize("COMPLETE")];
4377 [overlay_ addSubview:close_];
4378 [progress_ removeFromSuperview];
4379 [status_ removeFromSuperview];
4381 [database_ popErrorWithTitle:title_];
4382 [delegate_ progressViewIsComplete:self];
4386 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4389 MMap mmap(file, MMap::ReadOnly);
4391 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4392 if (!(notifyconf_ == sha1.Result()))
4399 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4402 MMap mmap(file, MMap::ReadOnly);
4404 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4405 if (!(springlist_ == sha1.Result()))
4411 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break;
4412 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4413 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4414 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4415 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4418 system("su -c /usr/bin/uicache mobile");
4420 [delegate_ setStatusBarShowsProgress:NO];
4423 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4424 [[data target] performSelector:[data selector] withObject:[data object]];
4427 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4430 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4436 title_ = [title retain];
4438 UINavigationItem *item([navbar_ topItem]);
4439 [item setTitle:title_];
4441 [status_ setText:nil];
4442 [output_ setText:@""];
4443 [progress_ setProgress:0];
4445 [close_ removeFromSuperview];
4446 [overlay_ addSubview:progress_];
4447 [overlay_ addSubview:status_];
4449 [delegate_ setStatusBarShowsProgress:YES];
4454 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4457 MMap mmap(file, MMap::ReadOnly);
4459 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4460 notifyconf_ = sha1.Result();
4466 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4469 MMap mmap(file, MMap::ReadOnly);
4471 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4472 springlist_ = sha1.Result();
4476 [transition_ transition:6 toView:overlay_];
4479 detachNewThreadSelector:@selector(_detachNewThreadData:)
4481 withObject:[[ProgressData alloc]
4482 initWithSelector:selector
4489 - (void) repairWithSelector:(SEL)selector {
4491 detachNewThreadSelector:selector
4494 title:UCLocalize("REPAIRING")
4498 - (void) setConfigurationData:(NSString *)data {
4500 performSelectorOnMainThread:@selector(_setConfigurationData:)
4506 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4507 CYActionSheet *sheet([[[CYActionSheet alloc]
4509 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4510 defaultButtonIndex:0
4513 [sheet setBodyText:error];
4514 [sheet yieldToPopupAlertAnimated:YES];
4518 - (void) setProgressTitle:(NSString *)title {
4520 performSelectorOnMainThread:@selector(_setProgressTitle:)
4526 - (void) setProgressPercent:(float)percent {
4528 performSelectorOnMainThread:@selector(_setProgressPercent:)
4529 withObject:[NSNumber numberWithFloat:percent]
4534 - (void) startProgress {
4537 - (void) addProgressOutput:(NSString *)output {
4539 performSelectorOnMainThread:@selector(_addProgressOutput:)
4545 - (bool) isCancelling:(size_t)received {
4549 - (void) _setConfigurationData:(NSString *)data {
4550 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4552 if (!conffile_r(data)) {
4553 lprintf("E:invalid conffile\n");
4557 NSString *ofile = conffile_r[1];
4558 //NSString *nfile = conffile_r[2];
4560 UIActionSheet *sheet = [[[UIActionSheet alloc]
4561 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4562 buttons:[NSArray arrayWithObjects:
4563 UCLocalize("KEEP_OLD_COPY"),
4564 UCLocalize("ACCEPT_NEW_COPY"),
4565 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4567 defaultButtonIndex:0
4572 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4573 [sheet popupAlertAnimated:YES];
4576 - (void) _setProgressTitle:(NSString *)title {
4577 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4578 for (size_t i(0), e([words count]); i != e; ++i) {
4579 NSString *word([words objectAtIndex:i]);
4580 if (Package *package = [database_ packageWithName:word])
4581 [words replaceObjectAtIndex:i withObject:[package name]];
4584 [status_ setText:[words componentsJoinedByString:@" "]];
4587 - (void) _setProgressPercent:(NSNumber *)percent {
4588 [progress_ setProgress:[percent floatValue]];
4591 - (void) _addProgressOutput:(NSString *)output {
4592 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4593 CGSize size = [output_ contentSize];
4594 CGRect rect = {{0, size.height}, {size.width, 0}};
4595 [output_ scrollRectToVisible:rect animated:YES];
4598 - (BOOL) isRunning {
4605 /* Package Cell {{{ */
4606 @interface ContentView : UIView {
4607 _transient id delegate_;
4612 @interface PackageCell : UITableViewCell {
4615 NSString *description_;
4621 ContentView *content_;
4627 - (PackageCell *) init;
4628 - (void) setPackage:(Package *)package;
4630 + (int) heightForPackage:(Package *)package;
4631 - (void) drawContentRect:(CGRect)rect;
4635 @implementation ContentView
4637 - (id) initWithFrame:(CGRect)frame {
4638 if ((self = [super initWithFrame:frame]) != nil) {
4642 - (void) setDelegate:(id)delegate {
4643 delegate_ = delegate;
4646 - (void) drawRect:(CGRect)rect {
4647 [super drawRect:rect];
4648 [delegate_ drawContentRect:rect];
4653 @implementation PackageCell
4655 - (void) clearPackage {
4666 if (description_ != nil) {
4667 [description_ release];
4671 if (source_ != nil) {
4676 if (badge_ != nil) {
4681 if (placard_ != nil) {
4691 [self clearPackage];
4698 return faded_ ? [self selectionPercent] : fade_;
4701 - (PackageCell *) init {
4702 CGRect frame(CGRectMake(0, 0, 320, 74));
4703 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4704 UIView *content([self contentView]);
4705 CGRect bounds([content bounds]);
4706 content_ = [[ContentView alloc] initWithFrame:bounds];
4707 [content_ setDelegate:self];
4708 [content_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
4709 [content_ setOpaque:YES];
4710 [content addSubview:content_];
4711 if ([self respondsToSelector:@selector(selectionPercent)])
4716 - (void) _setBackgroundColor {
4718 if (NSString *mode = [package_ mode]) {
4719 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4720 color = remove ? RemovingColor_ : InstallingColor_;
4722 color = [UIColor whiteColor];
4724 [content_ setBackgroundColor:color];
4725 [self setNeedsDisplay];
4728 - (void) setPackage:(Package *)package {
4729 [self clearPackage];
4732 Source *source = [package source];
4734 icon_ = [[package icon] retain];
4735 name_ = [[package name] retain];
4738 description_ = [package longDescription];
4739 if (description_ == nil)
4740 description_ = [package shortDescription];
4741 if (description_ != nil)
4742 description_ = [description_ retain];
4744 commercial_ = [package isCommercial];
4746 package_ = [package retain];
4748 NSString *label = nil;
4749 bool trusted = false;
4751 if (source != nil) {
4752 label = [source label];
4753 trusted = [source trusted];
4754 } else if ([[package id] isEqualToString:@"firmware"])
4755 label = UCLocalize("APPLE");
4757 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4759 NSString *from(label);
4761 NSString *section = [package simpleSection];
4762 if (section != nil && ![section isEqualToString:label]) {
4763 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4764 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4767 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4768 source_ = [from retain];
4770 if (NSString *purpose = [package primaryPurpose])
4771 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4772 badge_ = [badge_ retain];
4774 if ([package installed] != nil)
4775 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4776 placard_ = [placard_ retain];
4778 [self _setBackgroundColor];
4779 [content_ setNeedsDisplay];
4782 - (void) drawContentRect:(CGRect)rect {
4783 bool selected([self isSelected]);
4784 float width([self bounds].size.width);
4787 CGContextRef context(UIGraphicsGetCurrentContext());
4788 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4789 CGContextFillRect(context, rect);
4794 rect.size = [icon_ size];
4796 rect.size.width /= 2;
4797 rect.size.height /= 2;
4799 rect.origin.x = 25 - rect.size.width / 2;
4800 rect.origin.y = 25 - rect.size.height / 2;
4802 [icon_ drawInRect:rect];
4805 if (badge_ != nil) {
4806 CGSize size = [badge_ size];
4808 [badge_ drawAtPoint:CGPointMake(
4809 36 - size.width / 2,
4810 36 - size.height / 2
4818 UISetColor(commercial_ ? Purple_ : Black_);
4819 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ ellipsis:2];
4820 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ ellipsis:2];
4823 UISetColor(commercial_ ? Purplish_ : Gray_);
4824 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ ellipsis:2];
4826 if (placard_ != nil)
4827 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4830 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4831 //[self _setBackgroundColor];
4832 [super setSelected:selected animated:fade];
4833 [content_ setNeedsDisplay];
4836 + (int) heightForPackage:(Package *)package {
4842 /* Section Cell {{{ */
4843 @interface SectionCell : UISimpleTableCell {
4849 _UISwitchSlider *switch_;
4854 - (void) setSection:(Section *)section editing:(BOOL)editing;
4858 @implementation SectionCell
4860 - (void) clearSection {
4861 if (basic_ != nil) {
4866 if (section_ != nil) {
4876 if (count_ != nil) {
4883 [self clearSection];
4890 if ((self = [super init]) != nil) {
4891 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4892 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4893 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventTouchUpInside];
4897 - (void) onSwitch:(id)sender {
4898 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4899 if (metadata == nil) {
4900 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4901 [Sections_ setObject:metadata forKey:basic_];
4905 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4908 - (void) setSection:(Section *)section editing:(BOOL)editing {
4909 if (editing != editing_) {
4911 [switch_ removeFromSuperview];
4913 [self addSubview:switch_];
4917 [self clearSection];
4919 if (section == nil) {
4920 name_ = [UCLocalize("ALL_PACKAGES") retain];
4923 basic_ = [section name];
4925 basic_ = [basic_ retain];
4927 section_ = [section localized];
4928 if (section_ != nil)
4929 section_ = [section_ retain];
4931 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4932 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4935 [switch_ setValue:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4939 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4940 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4948 float width(rect.size.width + 23);
4952 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ ellipsis:2];
4954 CGSize size = [count_ sizeWithFont:Font14_];
4958 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4960 [super drawContentInRect:rect selected:selected];
4966 /* File Table {{{ */
4967 @interface FileTable : RVPage {
4968 _transient Database *database_;
4971 NSMutableArray *files_;
4975 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4976 - (void) setPackage:(Package *)package;
4980 @implementation FileTable
4983 if (package_ != nil)
4992 - (int) numberOfRowsInTable:(UITable *)table {
4993 return files_ == nil ? 0 : [files_ count];
4996 - (float) table:(UITable *)table heightForRow:(int)row {
5000 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
5001 if (reusing == nil) {
5002 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
5003 UIFont *font = [UIFont systemFontOfSize:16];
5004 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
5006 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
5010 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5014 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5015 if ((self = [super initWithBook:book]) != nil) {
5016 database_ = database;
5018 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5020 list_ = [[UITable alloc] initWithFrame:[self bounds]];
5021 [self addSubview:list_];
5023 UITableColumn *column = [[[UITableColumn alloc]
5024 initWithTitle:UCLocalize("NAME")
5026 width:[self frame].size.width
5029 [list_ setDataSource:self];
5030 [list_ setSeparatorStyle:1];
5031 [list_ addTableColumn:column];
5032 [list_ setDelegate:self];
5033 [list_ setReusesTableCells:YES];
5037 - (void) setPackage:(Package *)package {
5038 if (package_ != nil) {
5039 [package_ autorelease];
5048 [files_ removeAllObjects];
5050 if (package != nil) {
5051 package_ = [package retain];
5052 name_ = [[package id] retain];
5054 if (NSArray *files = [package files])
5055 [files_ addObjectsFromArray:files];
5057 if ([files_ count] != 0) {
5058 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5059 [files_ removeObjectAtIndex:0];
5060 [files_ sortUsingSelector:@selector(compareByPath:)];
5062 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5063 [stack addObject:@"/"];
5065 for (int i(0), e([files_ count]); i != e; ++i) {
5066 NSString *file = [files_ objectAtIndex:i];
5067 while (![file hasPrefix:[stack lastObject]])
5068 [stack removeLastObject];
5069 NSString *directory = [stack lastObject];
5070 [stack addObject:[file stringByAppendingString:@"/"]];
5071 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5072 ([stack count] - 2) * 3, "",
5073 [file substringFromIndex:[directory length]]
5082 - (void) resetViewAnimated:(BOOL)animated {
5083 [list_ resetViewAnimated:animated];
5086 - (void) reloadData {
5087 [self setPackage:[database_ packageWithName:name_]];
5088 [self reloadButtons];
5091 - (NSString *) title {
5092 return UCLocalize("INSTALLED_FILES");
5095 - (NSString *) backButtonTitle {
5096 return UCLocalize("FILES");
5101 /* Package View {{{ */
5102 @interface PackageView : CydiaBrowserView {
5103 _transient Database *database_;
5107 NSMutableArray *buttons_;
5110 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5111 - (void) setPackage:(Package *)package;
5115 @implementation PackageView
5118 if (package_ != nil)
5127 if ([self retainCount] == 1)
5128 [delegate_ setPackageView:self];
5132 /* XXX: this is not safe at all... localization of /fail/ */
5133 - (void) _clickButtonWithName:(NSString *)name {
5134 if ([name isEqualToString:UCLocalize("CLEAR")])
5135 [delegate_ clearPackage:package_];
5136 else if ([name isEqualToString:UCLocalize("INSTALL")])
5137 [delegate_ installPackage:package_];
5138 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5139 [delegate_ installPackage:package_];
5140 else if ([name isEqualToString:UCLocalize("REMOVE")])
5141 [delegate_ removePackage:package_];
5142 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5143 [delegate_ installPackage:package_];
5144 else _assert(false);
5147 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5148 NSString *context([sheet context]);
5150 if ([context isEqualToString:@"modify"]) {
5151 int count = [buttons_ count];
5152 _assert(count != 0);
5153 _assert(button <= count + 1);
5155 if (count != button - 1)
5156 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
5160 [super alertSheet:sheet buttonClicked:button];
5163 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5164 return [super webView:sender didFinishLoadForFrame:frame];
5167 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5168 [super webView:sender didClearWindowObject:window forFrame:frame];
5169 [window setValue:package_ forKey:@"package"];
5172 - (bool) _allowJavaScriptPanel {
5177 - (void) __rightButtonClicked {
5178 int count([buttons_ count]);
5183 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5185 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
5186 [buttons addObjectsFromArray:buttons_];
5187 [buttons addObject:UCLocalize("CANCEL")];
5189 [delegate_ slideUp:[[[UIActionSheet alloc]
5192 defaultButtonIndex:([buttons count] - 1)
5199 - (void) _rightButtonClicked {
5201 [super _rightButtonClicked];
5203 [self __rightButtonClicked];
5207 - (id) _rightButtonTitle {
5208 int count = [buttons_ count];
5209 return count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0];
5212 - (NSString *) backButtonTitle {
5216 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5217 if ((self = [super initWithBook:book]) != nil) {
5218 database_ = database;
5219 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5220 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5224 - (void) setPackage:(Package *)package {
5225 if (package_ != nil) {
5226 [package_ autorelease];
5235 [buttons_ removeAllObjects];
5237 if (package != nil) {
5240 package_ = [package retain];
5241 name_ = [[package id] retain];
5242 commercial_ = [package isCommercial];
5244 if ([package_ mode] != nil)
5245 [buttons_ addObject:UCLocalize("CLEAR")];
5246 if ([package_ source] == nil);
5247 else if ([package_ upgradableAndEssential:NO])
5248 [buttons_ addObject:UCLocalize("UPGRADE")];
5249 else if ([package_ uninstalled])
5250 [buttons_ addObject:UCLocalize("INSTALL")];
5252 [buttons_ addObject:UCLocalize("REINSTALL")];
5253 if (![package_ uninstalled])
5254 [buttons_ addObject:UCLocalize("REMOVE")];
5256 if (special_ != NULL) {
5257 CGRect frame([webview_ frame]);
5258 frame.size.width = 320;
5259 frame.size.height = 0;
5260 [webview_ setFrame:frame];
5262 if ([scroller_ respondsToSelector:@selector(scrollPointVisibleAtTopLeft:)])
5263 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5265 [scroller_ scrollRectToVisible:CGRectZero animated:NO];
5268 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5270 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5272 [self setFinishHook:nil];
5273 [self setPopupHook:nil];
5276 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5277 [super callFunction:special_];
5281 [self reloadButtons];
5284 - (bool) isLoading {
5285 return commercial_ ? [super isLoading] : false;
5288 - (void) reloadData {
5289 [self setPackage:[database_ packageWithName:name_]];
5294 /* Package Table {{{ */
5295 @interface PackageTable : RVPage {
5296 _transient Database *database_;
5298 NSMutableArray *packages_;
5299 NSMutableArray *sections_;
5301 NSMutableArray *index_;
5302 NSMutableDictionary *indices_;
5305 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5307 - (void) setDelegate:(id)delegate;
5309 - (void) reloadData;
5310 - (void) resetCursor;
5312 - (UITableView *) list;
5314 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5318 @implementation PackageTable
5321 [list_ setDataSource:nil];
5324 [packages_ release];
5325 [sections_ release];
5332 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5333 NSInteger count([sections_ count]);
5334 return count == 0 ? 1 : count;
5337 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5338 if ([sections_ count] == 0)
5340 return [[sections_ objectAtIndex:section] name];
5343 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5344 if ([sections_ count] == 0)
5346 return [[sections_ objectAtIndex:section] count];
5349 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5350 Section *section([sections_ objectAtIndex:[path section]]);
5351 NSInteger row([path row]);
5352 Package *package([packages_ objectAtIndex:([section row] + row)]);
5356 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5357 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
5359 cell = [[[PackageCell alloc] init] autorelease];
5360 [cell setPackage:[self packageAtIndexPath:path]];
5364 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5366 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5369 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5370 Package *package([self packageAtIndexPath:path]);
5371 package = [database_ packageWithName:[package id]];
5372 PackageView *view([delegate_ packageView]);
5373 [view setPackage:package];
5374 [view setDelegate:delegate_];
5375 [book_ pushPage:view];
5379 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5380 return [packages_ count] > 20 ? index_ : nil;
5383 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5387 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5388 if ((self = [super initWithBook:book]) != nil) {
5389 database_ = database;
5390 title_ = [title retain];
5392 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5393 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5395 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5396 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5398 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5399 [list_ setDataSource:self];
5400 [list_ setDelegate:self];
5402 [self addSubview:list_];
5404 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5405 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5409 - (void) setDelegate:(id)delegate {
5410 delegate_ = delegate;
5413 - (bool) hasPackage:(Package *)package {
5417 - (void) reloadData {
5418 NSArray *packages = [database_ packages];
5420 [packages_ removeAllObjects];
5421 [sections_ removeAllObjects];
5423 _profile(PackageTable$reloadData$Filter)
5424 for (Package *package in packages)
5425 if ([self hasPackage:package])
5426 [packages_ addObject:package];
5429 [index_ removeAllObjects];
5430 [indices_ removeAllObjects];
5432 Section *section = nil;
5434 _profile(PackageTable$reloadData$Section)
5435 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5439 _profile(PackageTable$reloadData$Section$Package)
5440 package = [packages_ objectAtIndex:offset];
5441 index = [package index];
5444 if (section == nil || [section index] != index) {
5445 _profile(PackageTable$reloadData$Section$Allocate)
5446 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5449 [index_ addObject:[section name]];
5450 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5452 _profile(PackageTable$reloadData$Section$Add)
5453 [sections_ addObject:section];
5457 [section addToCount];
5461 _profile(PackageTable$reloadData$List)
5466 - (NSString *) title {
5470 - (void) resetViewAnimated:(BOOL)animated {
5471 [list_ resetViewAnimated:animated];
5474 - (void) resetCursor {
5475 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5478 - (UITableView *) list {
5482 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5483 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5488 /* Filtered Package Table {{{ */
5489 @interface FilteredPackageTable : PackageTable {
5495 - (void) setObject:(id)object;
5496 - (void) setObject:(id)object forFilter:(SEL)filter;
5498 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5502 @implementation FilteredPackageTable
5510 - (void) setFilter:(SEL)filter {
5513 /* XXX: this is an unsafe optimization of doomy hell */
5514 Method method(class_getInstanceMethod([Package class], filter));
5515 _assert(method != NULL);
5516 imp_ = method_getImplementation(method);
5517 _assert(imp_ != NULL);
5520 - (void) setObject:(id)object {
5526 object_ = [object retain];
5529 - (void) setObject:(id)object forFilter:(SEL)filter {
5530 [self setFilter:filter];
5531 [self setObject:object];
5535 - (bool) hasPackage:(Package *)package {
5536 _profile(FilteredPackageTable$hasPackage)
5537 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5541 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5542 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5543 [self setFilter:filter];
5544 object_ = object == nil ? nil : [object retain];
5552 /* Add Source View {{{ */
5553 @interface AddSourceView : RVPage {
5554 _transient Database *database_;
5557 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5561 @implementation AddSourceView
5563 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5564 if ((self = [super initWithBook:book]) != nil) {
5565 database_ = database;
5571 /* Source Cell {{{ */
5572 @interface SourceCell : UITableCell {
5575 NSString *description_;
5581 - (SourceCell *) initWithSource:(Source *)source;
5585 @implementation SourceCell
5590 [description_ release];
5595 - (SourceCell *) initWithSource:(Source *)source {
5596 if ((self = [super init]) != nil) {
5598 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5600 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5601 icon_ = [icon_ retain];
5603 origin_ = [[source name] retain];
5604 label_ = [[source uri] retain];
5605 description_ = [[source description] retain];
5609 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5610 float width(rect.size.width);
5613 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5620 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ ellipsis:2];
5624 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ ellipsis:2];
5628 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ ellipsis:2];
5630 [super drawContentInRect:rect selected:selected];
5635 /* Source Table {{{ */
5636 @interface SourceTable : RVPage {
5637 _transient Database *database_;
5638 UISectionList *list_;
5639 NSMutableArray *sources_;
5640 UIActionSheet *alert_;
5644 UIProgressHUD *hud_;
5647 //NSURLConnection *installer_;
5648 NSURLConnection *trivial_;
5649 NSURLConnection *trivial_bz2_;
5650 NSURLConnection *trivial_gz_;
5651 //NSURLConnection *automatic_;
5656 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5660 @implementation SourceTable
5662 - (void) _deallocConnection:(NSURLConnection *)connection {
5663 if (connection != nil) {
5664 [connection cancel];
5665 //[connection setDelegate:nil];
5666 [connection release];
5671 [[list_ table] setDelegate:nil];
5672 [list_ setDataSource:nil];
5681 //[self _deallocConnection:installer_];
5682 [self _deallocConnection:trivial_];
5683 [self _deallocConnection:trivial_gz_];
5684 [self _deallocConnection:trivial_bz2_];
5685 //[self _deallocConnection:automatic_];
5692 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5693 return offset_ == 0 ? 1 : 2;
5696 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5697 switch (section + (offset_ == 0 ? 1 : 0)) {
5698 case 0: return UCLocalize("ENTERED_BY_USER");
5699 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5705 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5706 switch (section + (offset_ == 0 ? 1 : 0)) {
5708 case 1: return offset_;
5714 - (int) numberOfRowsInTable:(UITable *)table {
5715 return [sources_ count];
5718 - (float) table:(UITable *)table heightForRow:(int)row {
5719 Source *source = [sources_ objectAtIndex:row];
5720 return [source description] == nil ? 56 : 73;
5723 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5724 Source *source = [sources_ objectAtIndex:row];
5725 // XXX: weird warning, stupid selectors ;P
5726 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5729 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5733 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5737 - (void) tableRowSelected:(NSNotification*)notification {
5738 UITable *table([list_ table]);
5739 int row([table selectedRow]);
5743 Source *source = [sources_ objectAtIndex:row];
5745 PackageTable *packages = [[[FilteredPackageTable alloc]
5748 title:[source label]
5749 filter:@selector(isVisibleInSource:)
5753 [packages setDelegate:delegate_];
5755 [book_ pushPage:packages];
5758 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5759 Source *source = [sources_ objectAtIndex:row];
5760 return [source record] != nil;
5763 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5764 [[list_ table] setDeleteConfirmationRow:row];
5767 - (void) table:(UITable *)table deleteRow:(int)row {
5768 Source *source = [sources_ objectAtIndex:row];
5769 [Sources_ removeObjectForKey:[source key]];
5770 [delegate_ syncData];
5774 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5777 @"./", @"Distribution",
5778 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5780 [delegate_ syncData];
5783 - (NSString *) getWarning {
5784 NSString *href(href_);
5785 NSRange colon([href rangeOfString:@"://"]);
5786 if (colon.location != NSNotFound)
5787 href = [href substringFromIndex:(colon.location + 3)];
5788 href = [href stringByAddingPercentEscapes];
5789 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5790 href = [href stringByCachingURLWithCurrentCDN];
5792 NSURL *url([NSURL URLWithString:href]);
5794 NSStringEncoding encoding;
5795 NSError *error(nil);
5797 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5798 return [warning length] == 0 ? nil : warning;
5802 - (void) _endConnection:(NSURLConnection *)connection {
5803 NSURLConnection **field = NULL;
5804 if (connection == trivial_)
5806 else if (connection == trivial_bz2_)
5807 field = &trivial_bz2_;
5808 else if (connection == trivial_gz_)
5809 field = &trivial_gz_;
5810 _assert(field != NULL);
5811 [connection release];
5816 trivial_bz2_ == nil &&
5822 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5825 UIActionSheet *sheet = [[[UIActionSheet alloc]
5826 initWithTitle:UCLocalize("SOURCE_WARNING")
5827 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_ANYWAY"), UCLocalize("CANCEL"), nil]
5828 defaultButtonIndex:0
5833 [sheet setNumberOfRows:1];
5835 [sheet setBodyText:warning];
5836 [sheet popupAlertAnimated:YES];
5839 } else if (error_ != nil) {
5840 UIActionSheet *sheet = [[[UIActionSheet alloc]
5841 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5842 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5843 defaultButtonIndex:0
5848 [sheet setBodyText:[error_ localizedDescription]];
5849 [sheet popupAlertAnimated:YES];
5851 UIActionSheet *sheet = [[[UIActionSheet alloc]
5852 initWithTitle:UCLocalize("NOT_REPOSITORY")
5853 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5854 defaultButtonIndex:0
5859 [sheet setBodyText:UCLocalize("NOT_REPOSITORY_EX")];
5860 [sheet popupAlertAnimated:YES];
5863 [delegate_ setStatusBarShowsProgress:NO];
5864 [delegate_ removeProgressHUD:hud_];
5874 if (error_ != nil) {
5881 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5882 switch ([response statusCode]) {
5888 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5889 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5891 error_ = [error retain];
5892 [self _endConnection:connection];
5895 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5896 [self _endConnection:connection];
5899 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5900 NSMutableURLRequest *request = [NSMutableURLRequest
5901 requestWithURL:[NSURL URLWithString:href]
5902 cachePolicy:NSURLRequestUseProtocolCachePolicy
5903 timeoutInterval:20.0
5906 [request setHTTPMethod:method];
5908 if (Machine_ != NULL)
5909 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5911 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
5913 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5915 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5918 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5919 NSString *context([sheet context]);
5921 if ([context isEqualToString:@"source"]) {
5924 NSString *href = [[sheet textField] text];
5926 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5928 if (![href hasSuffix:@"/"])
5929 href_ = [href stringByAppendingString:@"/"];
5932 href_ = [href_ retain];
5934 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
5935 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5936 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5937 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5941 hud_ = [[delegate_ addProgressHUD] retain];
5942 [hud_ setText:UCLocalize("VERIFYING_URL")];
5952 } else if ([context isEqualToString:@"trivial"])
5954 else if ([context isEqualToString:@"urlerror"])
5956 else if ([context isEqualToString:@"warning"]) {
5975 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5976 if ((self = [super initWithBook:book]) != nil) {
5977 database_ = database;
5978 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5980 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5981 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5982 [list_ setShouldHideHeaderInShortLists:NO];
5984 [self addSubview:list_];
5985 [list_ setDataSource:self];
5987 UITableColumn *column = [[UITableColumn alloc]
5988 initWithTitle:UCLocalize("NAME")
5990 width:[self frame].size.width
5993 UITable *table = [list_ table];
5994 [table setSeparatorStyle:1];
5995 [table addTableColumn:column];
5996 [table setDelegate:self];
6000 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6001 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6005 - (void) reloadData {
6007 if (!list.ReadMainList())
6010 [sources_ removeAllObjects];
6011 [sources_ addObjectsFromArray:[database_ sources]];
6013 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6016 int count([sources_ count]);
6017 for (offset_ = 0; offset_ != count; ++offset_) {
6018 Source *source = [sources_ objectAtIndex:offset_];
6019 if ([source record] == nil)
6026 - (void) resetViewAnimated:(BOOL)animated {
6027 [list_ resetViewAnimated:animated];
6030 - (void) _leftButtonClicked {
6031 /*[book_ pushPage:[[[AddSourceView alloc]
6036 UIActionSheet *sheet = [[[UIActionSheet alloc]
6037 initWithTitle:UCLocalize("ENTER_APT_URL")
6038 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_SOURCE"), UCLocalize("CANCEL"), nil]
6039 defaultButtonIndex:0
6044 [sheet setNumberOfRows:1];
6046 [sheet addTextFieldWithValue:@"http://" label:@""];
6048 UITextInputTraits *traits = [[sheet textField] textInputTraits];
6049 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6050 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6051 [traits setKeyboardType:UIKeyboardTypeURL];
6052 // XXX: UIReturnKeyDone
6053 [traits setReturnKeyType:UIReturnKeyNext];
6055 [sheet popupAlertAnimated:YES];
6058 - (void) _rightButtonClicked {
6059 UITable *table = [list_ table];
6060 BOOL editing = [table isRowDeletionEnabled];
6061 [table enableRowDeletion:!editing animated:YES];
6062 [book_ reloadButtonsForPage:self];
6065 - (NSString *) title {
6066 return UCLocalize("SOURCES");
6069 - (NSString *) leftButtonTitle {
6070 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("ADD") : nil;
6073 - (id) rightButtonTitle {
6074 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("DONE") : UCLocalize("EDIT");
6077 - (UINavigationButtonStyle) rightButtonStyle {
6078 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6084 /* Installed View {{{ */
6085 @interface InstalledView : RVPage {
6086 _transient Database *database_;
6087 FilteredPackageTable *packages_;
6091 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6095 @implementation InstalledView
6098 [packages_ release];
6102 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6103 if ((self = [super initWithBook:book]) != nil) {
6104 database_ = database;
6106 packages_ = [[FilteredPackageTable alloc]
6110 filter:@selector(isInstalledAndVisible:)
6111 with:[NSNumber numberWithBool:YES]
6114 [self addSubview:packages_];
6116 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6117 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6121 - (void) resetViewAnimated:(BOOL)animated {
6122 [packages_ resetViewAnimated:animated];
6125 - (void) reloadData {
6126 [packages_ reloadData];
6129 - (void) _rightButtonClicked {
6130 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6131 [packages_ reloadData];
6133 [book_ reloadButtonsForPage:self];
6136 - (NSString *) title {
6137 return UCLocalize("INSTALLED");
6140 - (NSString *) backButtonTitle {
6141 return UCLocalize("PACKAGES");
6144 - (id) rightButtonTitle {
6145 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE");
6148 - (UINavigationButtonStyle) rightButtonStyle {
6149 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6152 - (void) setDelegate:(id)delegate {
6153 [super setDelegate:delegate];
6154 [packages_ setDelegate:delegate];
6161 @interface HomeView : CydiaBrowserView {
6166 @implementation HomeView
6168 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6169 NSString *context([sheet context]);
6171 if ([context isEqualToString:@"about"])
6174 [super alertSheet:sheet buttonClicked:button];
6177 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6178 [super _setMoreHeaders:request];
6180 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6181 if (UniqueID_ != nil)
6182 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6185 - (void) _leftButtonClicked {
6186 UIActionSheet *sheet = [[[UIActionSheet alloc]
6187 initWithTitle:UCLocalize("ABOUT_CYDIA")
6188 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
6189 defaultButtonIndex:0
6195 @"Copyright (C) 2008-2009\n"
6196 "Jay Freeman (saurik)\n"
6197 "saurik@saurik.com\n"
6198 "http://www.saurik.com/\n"
6201 "http://www.theokorigroup.com/\n"
6203 "College of Creative Studies,\n"
6204 "University of California,\n"
6206 "http://www.ccs.ucsb.edu/"
6209 [sheet popupAlertAnimated:YES];
6212 - (NSString *) leftButtonTitle {
6213 return UCLocalize("ABOUT");
6218 /* Manage View {{{ */
6219 @interface ManageView : CydiaBrowserView {
6224 @implementation ManageView
6226 - (NSString *) title {
6227 return UCLocalize("MANAGE");
6230 - (void) _leftButtonClicked {
6231 [delegate_ askForSettings];
6232 [delegate_ updateData];
6235 - (NSString *) leftButtonTitle {
6236 return UCLocalize("SETTINGS");
6240 - (id) _rightButtonTitle {
6241 return Queuing_ ? UCLocalize("QUEUE") : nil;
6244 - (UINavigationButtonStyle) rightButtonStyle {
6245 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6248 - (void) _rightButtonClicked {
6253 - (bool) isLoading {
6260 /* Cydia Book {{{ */
6261 @interface CYBook : RVBook <
6264 _transient Database *database_;
6265 UINavigationBar *overlay_;
6266 UINavigationBar *underlay_;
6267 UIProgressIndicator *indicator_;
6268 UITextLabel *prompt_;
6269 UIProgressBar *progress_;
6270 UINavigationButton *cancel_;
6275 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
6278 - (void) setUpdate:(NSDate *)date;
6282 @implementation CYBook
6286 [indicator_ release];
6288 [progress_ release];
6293 - (NSString *) getTitleForPage:(RVPage *)page {
6294 return [super getTitleForPage:page];
6306 [UIView beginAnimations:nil context:NULL];
6308 CGRect ovrframe = [overlay_ frame];
6309 ovrframe.origin.y = 0;
6310 [overlay_ setFrame:ovrframe];
6312 CGRect barframe = [navbar_ frame];
6313 barframe.origin.y += ovrframe.size.height;
6314 [navbar_ setFrame:barframe];
6316 CGRect trnframe = [transition_ frame];
6317 trnframe.origin.y += ovrframe.size.height;
6318 trnframe.size.height -= ovrframe.size.height;
6319 [transition_ setFrame:trnframe];
6321 [UIView endAnimations];
6329 [UIView beginAnimations:nil context:NULL];
6331 CGRect ovrframe = [overlay_ frame];
6332 ovrframe.origin.y = -ovrframe.size.height;
6333 [overlay_ setFrame:ovrframe];
6335 CGRect barframe = [navbar_ frame];
6336 barframe.origin.y -= ovrframe.size.height;
6337 [navbar_ setFrame:barframe];
6339 CGRect trnframe = [transition_ frame];
6340 trnframe.origin.y -= ovrframe.size.height;
6341 trnframe.size.height += ovrframe.size.height;
6342 [transition_ setFrame:trnframe];
6344 [UIView commitAnimations];
6347 - (void) setUpdate:(NSDate *)date {
6354 [indicator_ startAnimation];
6355 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6356 [progress_ setProgress:0];
6359 [overlay_ addSubview:cancel_];
6362 detachNewThreadSelector:@selector(_update)
6368 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6369 NSString *context([sheet context]);
6371 if ([context isEqualToString:@"refresh"])
6378 [indicator_ stopAnimation];
6382 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6385 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6386 if ((self = [super initWithFrame:frame]) != nil) {
6387 database_ = database;
6389 CGRect ovrrect([navbar_ bounds]);
6390 ovrrect.size.height = [UINavigationBar defaultSize].height;
6391 ovrrect.origin.y = -ovrrect.size.height;
6393 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6394 [self addSubview:overlay_];
6396 ovrrect.origin.y = frame.size.height;
6397 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6398 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6399 [self addSubview:underlay_];
6401 [overlay_ setBarStyle:1];
6402 [underlay_ setBarStyle:1];
6404 int barstyle([overlay_ _barStyle:NO]);
6405 bool ugly(barstyle == 0);
6407 UIProgressIndicatorStyle style = ugly ?
6408 UIProgressIndicatorStyleMediumBrown :
6409 UIProgressIndicatorStyleMediumWhite;
6411 CGSize indsize([UIProgressIndicator defaultSizeForStyle:style]);
6412 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6413 CGRect indrect = {{indoffset, indoffset}, indsize};
6415 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6416 [indicator_ setStyle:style];
6417 [overlay_ addSubview:indicator_];
6419 CGSize prmsize = {215, indsize.height + 4};
6422 indoffset * 2 + indsize.width,
6423 unsigned(ovrrect.size.height - prmsize.height) / 2 - 1
6426 UIFont *font([UIFont systemFontOfSize:15]);
6428 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6430 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6431 [prompt_ setBackgroundColor:[UIColor clearColor]];
6432 [prompt_ setFont:font];
6434 [overlay_ addSubview:prompt_];
6436 CGSize prgsize = {75, 100};
6439 ovrrect.size.width - prgsize.width - 10,
6440 (ovrrect.size.height - prgsize.height) / 2
6443 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6444 [progress_ setStyle:0];
6445 [overlay_ addSubview:progress_];
6447 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6448 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6450 CGRect frame = [cancel_ frame];
6451 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6452 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6453 [cancel_ setFrame:frame];
6455 [cancel_ setBarStyle:barstyle];
6459 - (void) _onCancel {
6461 [cancel_ removeFromSuperview];
6464 - (void) _update { _pooled
6466 status.setDelegate(self);
6467 [database_ updateWithStatus:status];
6470 performSelectorOnMainThread:@selector(_update_)
6476 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6477 [prompt_ setText:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6481 UIActionSheet *sheet = [[[UIActionSheet alloc]
6482 initWithTitle:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), UCLocalize("REFRESH")]
6483 buttons:[NSArray arrayWithObjects:
6486 defaultButtonIndex:0
6491 [sheet setBodyText:error];
6492 [sheet popupAlertAnimated:YES];
6494 [self reloadButtons];
6497 - (void) setProgressTitle:(NSString *)title {
6499 performSelectorOnMainThread:@selector(_setProgressTitle:)
6505 - (void) setProgressPercent:(float)percent {
6507 performSelectorOnMainThread:@selector(_setProgressPercent:)
6508 withObject:[NSNumber numberWithFloat:percent]
6513 - (void) startProgress {
6516 - (void) addProgressOutput:(NSString *)output {
6518 performSelectorOnMainThread:@selector(_addProgressOutput:)
6524 - (bool) isCancelling:(size_t)received {
6528 - (void) _setProgressTitle:(NSString *)title {
6529 [prompt_ setText:title];
6532 - (void) _setProgressPercent:(NSNumber *)percent {
6533 [progress_ setProgress:[percent floatValue]];
6536 - (void) _addProgressOutput:(NSString *)output {
6541 /* Cydia:// Protocol {{{ */
6542 @interface CydiaURLProtocol : NSURLProtocol {
6547 @implementation CydiaURLProtocol
6549 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6550 NSURL *url([request URL]);
6553 NSString *scheme([[url scheme] lowercaseString]);
6554 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6559 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6563 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6564 id<NSURLProtocolClient> client([self client]);
6566 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6568 NSData *data(UIImagePNGRepresentation(icon));
6570 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6571 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6572 [client URLProtocol:self didLoadData:data];
6573 [client URLProtocolDidFinishLoading:self];
6577 - (void) startLoading {
6578 id<NSURLProtocolClient> client([self client]);
6579 NSURLRequest *request([self request]);
6581 NSURL *url([request URL]);
6582 NSString *href([url absoluteString]);
6584 NSString *path([href substringFromIndex:8]);
6585 NSRange slash([path rangeOfString:@"/"]);
6588 if (slash.location == NSNotFound) {
6592 command = [path substringToIndex:slash.location];
6593 path = [path substringFromIndex:(slash.location + 1)];
6596 Database *database([Database sharedInstance]);
6598 if ([command isEqualToString:@"package-icon"]) {
6601 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6602 Package *package([database packageWithName:path]);
6605 UIImage *icon([package icon]);
6606 [self _returnPNGWithImage:icon forRequest:request];
6607 } else if ([command isEqualToString:@"source-icon"]) {
6610 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6611 NSString *source(Simplify(path));
6612 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6614 icon = [UIImage applicationImageNamed:@"unknown.png"];
6615 [self _returnPNGWithImage:icon forRequest:request];
6616 } else if ([command isEqualToString:@"uikit-image"]) {
6619 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6620 UIImage *icon(_UIImageWithName(path));
6621 [self _returnPNGWithImage:icon forRequest:request];
6622 } else if ([command isEqualToString:@"section-icon"]) {
6625 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6626 NSString *section(Simplify(path));
6627 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6629 icon = [UIImage applicationImageNamed:@"unknown.png"];
6630 [self _returnPNGWithImage:icon forRequest:request];
6632 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6636 - (void) stopLoading {
6642 /* Sections View {{{ */
6643 @interface SectionsView : RVPage {
6644 _transient Database *database_;
6645 NSMutableArray *sections_;
6646 NSMutableArray *filtered_;
6647 UITransitionView *transition_;
6653 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6654 - (void) reloadData;
6659 @implementation SectionsView
6662 [list_ setDataSource:nil];
6663 [list_ setDelegate:nil];
6665 [sections_ release];
6666 [filtered_ release];
6667 [transition_ release];
6669 [accessory_ release];
6673 - (int) numberOfRowsInTable:(UITable *)table {
6674 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6677 - (float) table:(UITable *)table heightForRow:(int)row {
6681 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6683 reusing = [[[SectionCell alloc] init] autorelease];
6684 [(SectionCell *)reusing setSection:(editing_ ?
6685 [sections_ objectAtIndex:row] :
6686 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6687 ) editing:editing_];
6691 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6695 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6699 - (void) tableRowSelected:(NSNotification *)notification {
6700 int row = [[notification object] selectedRow];
6711 title = UCLocalize("ALL_PACKAGES");
6713 section = [filtered_ objectAtIndex:(row - 1)];
6714 name = [section name];
6717 name = [NSString stringWithString:name];
6718 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6721 title = UCLocalize("NO_SECTION");
6725 PackageTable *table = [[[FilteredPackageTable alloc]
6729 filter:@selector(isVisibleInSection:)
6733 [table setDelegate:delegate_];
6735 [book_ pushPage:table];
6738 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6739 if ((self = [super initWithBook:book]) != nil) {
6740 database_ = database;
6742 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6743 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6745 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6746 [self addSubview:transition_];
6748 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6749 [transition_ transition:0 toView:list_];
6751 UITableColumn *column = [[[UITableColumn alloc]
6752 initWithTitle:UCLocalize("NAME")
6754 width:[self frame].size.width
6757 [list_ setDataSource:self];
6758 [list_ setSeparatorStyle:1];
6759 [list_ addTableColumn:column];
6760 [list_ setDelegate:self];
6761 [list_ setReusesTableCells:YES];
6765 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6766 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6770 - (void) reloadData {
6771 NSArray *packages = [database_ packages];
6773 [sections_ removeAllObjects];
6774 [filtered_ removeAllObjects];
6777 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6778 SectionMap sections;
6779 sections.resize(64);
6781 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6785 for (Package *package in packages) {
6786 NSString *name([package section]);
6787 NSString *key(name == nil ? @"" : name);
6792 _profile(SectionsView$reloadData$Section)
6793 section = §ions[key];
6794 if (*section == nil) {
6795 _profile(SectionsView$reloadData$Section$Allocate)
6796 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6801 [*section addToCount];
6803 _profile(SectionsView$reloadData$Filter)
6804 if (![package valid] || ![package visible])
6808 [*section addToRow];
6812 _profile(SectionsView$reloadData$Section)
6813 section = [sections objectForKey:key];
6814 if (section == nil) {
6815 _profile(SectionsView$reloadData$Section$Allocate)
6816 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6817 [sections setObject:section forKey:key];
6822 [section addToCount];
6824 _profile(SectionsView$reloadData$Filter)
6825 if (![package valid] || ![package visible])
6835 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6836 [sections_ addObject:i->second];
6838 [sections_ addObjectsFromArray:[sections allValues]];
6841 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6843 for (Section *section in sections_) {
6844 size_t count([section row]);
6848 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6849 [section setCount:count];
6850 [filtered_ addObject:section];
6857 - (void) resetView {
6859 [self _rightButtonClicked];
6862 - (void) resetViewAnimated:(BOOL)animated {
6863 [list_ resetViewAnimated:animated];
6866 - (void) _rightButtonClicked {
6867 if ((editing_ = !editing_))
6870 [delegate_ updateData];
6871 [book_ reloadTitleForPage:self];
6872 [book_ reloadButtonsForPage:self];
6875 - (NSString *) title {
6876 return editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS");
6879 - (NSString *) backButtonTitle {
6880 return UCLocalize("SECTIONS");
6883 - (id) rightButtonTitle {
6884 return [sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT");
6887 - (UINavigationButtonStyle) rightButtonStyle {
6888 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6891 - (UIView *) accessoryView {
6897 /* Changes View {{{ */
6898 @interface ChangesView : RVPage {
6899 _transient Database *database_;
6900 NSMutableArray *packages_;
6901 NSMutableArray *sections_;
6906 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6907 - (void) reloadData;
6911 @implementation ChangesView
6914 [list_ setDelegate:nil];
6915 [list_ setDataSource:nil];
6917 [packages_ release];
6918 [sections_ release];
6923 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6924 NSInteger count([sections_ count]);
6925 return count == 0 ? 1 : count;
6928 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6929 if ([sections_ count] == 0)
6931 return [[sections_ objectAtIndex:section] name];
6934 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6935 if ([sections_ count] == 0)
6937 return [[sections_ objectAtIndex:section] count];
6940 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6941 Section *section([sections_ objectAtIndex:[path section]]);
6942 NSInteger row([path row]);
6943 return [packages_ objectAtIndex:([section row] + row)];
6946 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6947 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
6949 cell = [[[PackageCell alloc] init] autorelease];
6950 [cell setPackage:[self packageAtIndexPath:path]];
6954 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6956 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6959 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6960 Package *package([self packageAtIndexPath:path]);
6961 PackageView *view([delegate_ packageView]);
6962 [view setDelegate:delegate_];
6963 [view setPackage:package];
6964 [book_ pushPage:view];
6968 - (void) _leftButtonClicked {
6969 [(CYBook *)book_ update];
6970 [self reloadButtons];
6973 - (void) _rightButtonClicked {
6974 [delegate_ distUpgrade];
6977 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6978 if ((self = [super initWithBook:book]) != nil) {
6979 database_ = database;
6981 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6982 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6984 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
6985 [self addSubview:list_];
6987 //XXX:[list_ setShouldHideHeaderInShortLists:NO];
6988 [list_ setDataSource:self];
6989 [list_ setDelegate:self];
6990 //[list_ setSectionListStyle:1];
6994 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6995 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6999 - (void) reloadData {
7000 NSArray *packages = [database_ packages];
7002 [packages_ removeAllObjects];
7003 [sections_ removeAllObjects];
7006 for (Package *package in packages)
7008 [package uninstalled] && [package valid] && [package visible] ||
7009 [package upgradableAndEssential:YES]
7011 [packages_ addObject:package];
7014 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7017 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7018 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7019 Section *section = nil;
7023 bool unseens = false;
7025 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7027 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7028 Package *package = [packages_ objectAtIndex:offset];
7030 BOOL uae = [package upgradableAndEssential:YES];
7036 _profile(ChangesView$reloadData$Remember)
7037 seen = [package seen];
7040 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7045 name = UCLocalize("UNKNOWN");
7047 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7051 _profile(ChangesView$reloadData$Allocate)
7052 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7053 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7054 [sections_ addObject:section];
7058 [section addToCount];
7059 } else if ([package ignored])
7060 [ignored addToCount];
7063 [upgradable addToCount];
7068 CFRelease(formatter);
7071 Section *last = [sections_ lastObject];
7072 size_t count = [last count];
7073 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7074 [sections_ removeLastObject];
7077 if ([ignored count] != 0)
7078 [sections_ insertObject:ignored atIndex:0];
7080 [sections_ insertObject:upgradable atIndex:0];
7083 [self reloadButtons];
7086 - (void) resetViewAnimated:(BOOL)animated {
7087 [list_ resetViewAnimated:animated];
7090 - (NSString *) leftButtonTitle {
7091 return [(CYBook *)book_ updating] ? nil : UCLocalize("REFRESH");
7094 - (id) rightButtonTitle {
7095 return upgrades_ == 0 ? nil : [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
7098 - (NSString *) title {
7099 return UCLocalize("CHANGES");
7104 /* Search View {{{ */
7105 @protocol SearchViewDelegate
7106 - (void) showKeyboard:(BOOL)show;
7109 @interface SearchView : RVPage {
7111 UISearchField *field_;
7112 FilteredPackageTable *table_;
7117 - (id) initWithBook:(RVBook *)book database:(Database *)database;
7118 - (void) reloadData;
7122 @implementation SearchView
7125 [field_ setDelegate:nil];
7127 [accessory_ release];
7134 - (void) _showKeyboard:(BOOL)show {
7135 CGSize keysize = [UIKeyboard defaultSize];
7136 CGRect keydown = [book_ pageBounds];
7137 CGRect keyup = keydown;
7138 keyup.size.height -= keysize.height - ButtonBarHeight_;
7140 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
7142 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
7143 [animation setSignificantRectFields:8];
7146 [animation setStartFrame:keydown];
7147 [animation setEndFrame:keyup];
7149 [animation setStartFrame:keyup];
7150 [animation setEndFrame:keydown];
7153 UIAnimator *animator = [UIAnimator sharedAnimator];
7156 addAnimations:[NSArray arrayWithObjects:animation, nil]
7157 withDuration:(KeyboardTime_ - delay)
7162 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
7164 //[delegate_ showKeyboard:show];
7167 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
7168 [self _showKeyboard:YES];
7169 [table_ setObject:[field_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7173 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
7174 [self _showKeyboard:NO];
7175 [table_ setObject:[field_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7179 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
7181 NSString *text([field_ text]);
7182 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
7183 [table_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7189 - (void) textFieldClearButtonPressed:(UITextField *)field {
7193 - (void) keyboardInputShouldDelete:(id)input {
7197 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
7198 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
7202 [field_ resignFirstResponder];
7207 - (id) initWithBook:(RVBook *)book database:(Database *)database {
7208 if ((self = [super initWithBook:book]) != nil) {
7209 CGRect pageBounds = [book_ pageBounds];
7211 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
7212 CGColor dimmed(space_, 0, 0, 0, 0.5);
7213 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
7215 table_ = [[FilteredPackageTable alloc]
7219 filter:@selector(isUnfilteredAndSearchedForBy:)
7223 [table_ setShouldHideHeaderInShortLists:NO];
7224 [self addSubview:table_];
7226 CGRect cnfrect = {{7, 38}, {17, 18}};
7233 area.size.width = [self bounds].size.width - area.origin.x * 2;
7234 area.size.height = [UISearchField defaultHeight];
7236 field_ = [[UISearchField alloc] initWithFrame:area];
7238 UIFont *font = [UIFont systemFontOfSize:16];
7239 [field_ setFont:font];
7241 [field_ setPlaceholder:UCLocalize("SEARCH_EX")];
7242 [field_ setDelegate:self];
7244 [field_ setPaddingTop:5];
7246 UITextInputTraits *traits([field_ textInputTraits]);
7247 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7248 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7249 [traits setReturnKeyType:UIReturnKeySearch];
7251 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
7253 accessory_ = [[UIView alloc] initWithFrame:accrect];
7254 [accessory_ addSubview:field_];
7256 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7257 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7261 - (void) resetViewAnimated:(BOOL)animated {
7262 [table_ resetViewAnimated:animated];
7265 - (void) _reloadData {
7268 - (void) reloadData {
7269 _profile(SearchView$reloadData)
7270 [table_ reloadData];
7273 [table_ resetCursor];
7276 - (UIView *) accessoryView {
7280 - (NSString *) title {
7284 - (NSString *) backButtonTitle {
7285 return UCLocalize("SEARCH");
7288 - (void) setDelegate:(id)delegate {
7289 [table_ setDelegate:delegate];
7290 [super setDelegate:delegate];
7295 /* Settings View {{{ */
7296 @interface SettingsView : RVPage {
7297 _transient Database *database_;
7300 UIPreferencesTable *table_;
7301 _UISwitchSlider *subscribedSwitch_;
7302 _UISwitchSlider *ignoredSwitch_;
7303 UIPreferencesControlTableCell *subscribedCell_;
7304 UIPreferencesControlTableCell *ignoredCell_;
7307 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7311 @implementation SettingsView
7314 [table_ setDataSource:nil];
7317 if (package_ != nil)
7320 [subscribedSwitch_ release];
7321 [ignoredSwitch_ release];
7322 [subscribedCell_ release];
7323 [ignoredCell_ release];
7327 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7328 if (package_ == nil)
7334 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7335 if (package_ == nil)
7348 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7349 if (package_ == nil)
7362 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7363 if (package_ == nil)
7376 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7377 if (package_ == nil)
7380 _UISwitchSlider *slider([cell control]);
7381 BOOL value([slider value] != 0);
7382 NSMutableDictionary *metadata([package_ metadata]);
7385 if (NSNumber *number = [metadata objectForKey:key])
7386 before = [number boolValue];
7390 if (value != before) {
7391 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7393 [delegate_ updateData];
7397 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7398 [self onSomething:cell withKey:@"IsSubscribed"];
7401 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7402 [self onSomething:cell withKey:@"IsIgnored"];
7405 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7406 if (package_ == nil)
7410 case 0: switch (row) {
7412 return subscribedCell_;
7414 return ignoredCell_;
7418 case 1: switch (row) {
7420 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7421 [cell setShowSelection:NO];
7422 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7435 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7436 if ((self = [super initWithBook:book])) {
7437 database_ = database;
7438 name_ = [package retain];
7440 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7441 [self addSubview:table_];
7443 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7444 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
7446 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7447 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
7449 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7450 [subscribedCell_ setShowSelection:NO];
7451 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7452 [subscribedCell_ setControl:subscribedSwitch_];
7454 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7455 [ignoredCell_ setShowSelection:NO];
7456 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7457 [ignoredCell_ setControl:ignoredSwitch_];
7459 [table_ setDataSource:self];
7464 - (void) resetViewAnimated:(BOOL)animated {
7465 [table_ resetViewAnimated:animated];
7468 - (void) reloadData {
7469 if (package_ != nil)
7470 [package_ autorelease];
7471 package_ = [database_ packageWithName:name_];
7472 if (package_ != nil) {
7474 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7475 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7478 [table_ reloadData];
7481 - (NSString *) title {
7482 return UCLocalize("SETTINGS");
7488 /* Signature View {{{ */
7489 @interface SignatureView : CydiaBrowserView {
7490 _transient Database *database_;
7494 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7498 @implementation SignatureView
7505 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7507 [super webView:sender didClearWindowObject:window forFrame:frame];
7510 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7511 if ((self = [super initWithBook:book]) != nil) {
7512 database_ = database;
7513 package_ = [package retain];
7518 - (void) resetViewAnimated:(BOOL)animated {
7521 - (void) reloadData {
7522 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7528 @interface Cydia : UIApplication <
7529 ConfirmationViewDelegate,
7530 ProgressViewDelegate,
7539 UIToolbar *toolbar_;
7543 NSMutableArray *essential_;
7544 NSMutableArray *broken_;
7546 Database *database_;
7547 ProgressView *progress_;
7551 UIKeyboard *keyboard_;
7552 UIProgressHUD *hud_;
7554 SectionsView *sections_;
7555 ChangesView *changes_;
7556 ManageView *manage_;
7557 SearchView *search_;
7559 #if RecyclePackageViews
7560 NSMutableArray *details_;
7564 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7565 - (void) setPage:(RVPage *)page;
7569 static _finline void _setHomePage(Cydia *self) {
7570 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeView class]]];
7573 @implementation Cydia
7575 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7580 if ([broken_ count] != 0) {
7581 int count = [broken_ count];
7583 UIActionSheet *sheet = [[[UIActionSheet alloc]
7584 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7585 buttons:[NSArray arrayWithObjects:
7586 UCLocalize("FORCIBLY_CLEAR"),
7587 UCLocalize("TEMPORARY_IGNORE"),
7589 defaultButtonIndex:0
7594 [sheet setBodyText:UCLocalize("HALFINSTALLED_PACKAGE_EX")];
7595 [sheet popupAlertAnimated:YES];
7596 } else if (!Ignored_ && [essential_ count] != 0) {
7597 int count = [essential_ count];
7599 UIActionSheet *sheet = [[[UIActionSheet alloc]
7600 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7601 buttons:[NSArray arrayWithObjects:
7602 UCLocalize("UPGRADE_ESSENTIAL"),
7603 UCLocalize("COMPLETE_UPGRADE"),
7604 UCLocalize("TEMPORARY_IGNORE"),
7606 defaultButtonIndex:0
7611 [sheet setBodyText:UCLocalize("ESSENTIAL_UPGRADE_EX")];
7612 [sheet popupAlertAnimated:YES];
7616 - (void) _saveConfig {
7619 NSString *error(nil);
7620 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7622 NSError *error(nil);
7623 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7624 NSLog(@"failure to save metadata data: %@", error);
7627 NSLog(@"failure to serialize metadata: %@", error);
7635 - (void) _updateData {
7638 /* XXX: this is just stupid */
7639 if (tag_ != 2 && sections_ != nil)
7640 [sections_ reloadData];
7641 if (tag_ != 3 && changes_ != nil)
7642 [changes_ reloadData];
7643 if (tag_ != 5 && search_ != nil)
7644 [search_ reloadData];
7649 - (void) _reloadData {
7652 static bool loaded(false);
7653 UIProgressHUD *hud([self addProgressHUD]);
7654 [hud setText:(loaded ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7656 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7659 [self removeProgressHUD:hud];
7663 [essential_ removeAllObjects];
7664 [broken_ removeAllObjects];
7666 NSArray *packages([database_ packages]);
7667 for (Package *package in packages) {
7669 [broken_ addObject:package];
7670 if ([package upgradableAndEssential:NO]) {
7671 if ([package essential])
7672 [essential_ addObject:package];
7678 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7679 [toolbar_ setBadgeValue:badge forButton:3];
7680 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7681 [toolbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7682 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7683 [self setApplicationBadge:badge];
7685 [self setApplicationBadgeString:badge];
7687 [toolbar_ setBadgeValue:nil forButton:3];
7688 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7689 [toolbar_ setBadgeAnimated:NO forButton:3];
7690 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7691 [self removeApplicationBadge];
7692 else // XXX: maybe use setApplicationBadgeString also?
7693 [self setApplicationIconBadgeNumber:0];
7697 [toolbar_ setBadgeValue:nil forButton:4];
7701 if (loaded || ManualRefresh) loaded:
7706 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
7708 if (update != nil) {
7709 NSTimeInterval interval([update timeIntervalSinceNow]);
7710 if (interval <= 0 && interval > -(15*60))
7714 [book_ setUpdate:update];
7718 - (void) updateData {
7719 [database_ setVisible];
7728 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
7729 _assert(file != NULL);
7731 for (NSString *key in [Sources_ allKeys]) {
7732 NSDictionary *source([Sources_ objectForKey:key]);
7734 fprintf(file, "%s %s %s\n",
7735 [[source objectForKey:@"Type"] UTF8String],
7736 [[source objectForKey:@"URI"] UTF8String],
7737 [[source objectForKey:@"Distribution"] UTF8String]
7746 detachNewThreadSelector:@selector(update_)
7749 title:UCLocalize("UPDATING_SOURCES")
7753 - (void) reloadData {
7754 @synchronized (self) {
7755 if (confirm_ == nil)
7761 pkgProblemResolver *resolver = [database_ resolver];
7763 resolver->InstallProtect();
7764 if (!resolver->Resolve(true))
7768 - (void) popUpBook:(RVBook *)book {
7769 [underlay_ popSubview:book];
7772 - (CGRect) popUpBounds {
7773 return [underlay_ bounds];
7777 if (![database_ prepare])
7780 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7781 [confirm_ setDelegate:self];
7783 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7784 [page setDelegate:self];
7786 [confirm_ setPage:page];
7787 [self popUpBook:confirm_];
7793 @synchronized (self) {
7798 - (void) clearPackage:(Package *)package {
7799 @synchronized (self) {
7806 - (void) installPackage:(Package *)package {
7807 @synchronized (self) {
7814 - (void) removePackage:(Package *)package {
7815 @synchronized (self) {
7822 - (void) distUpgrade {
7823 @synchronized (self) {
7824 if (![database_ upgrade])
7831 [self slideUp:[[[UIActionSheet alloc]
7833 buttons:[NSArray arrayWithObjects:UCLocalize("CONTINUE_QUEUING"), UCLocalize("CANCEL_CLEAR"), nil]
7834 defaultButtonIndex:1
7841 @synchronized (self) {
7844 if (confirm_ != nil) {
7852 [overlay_ removeFromSuperview];
7856 detachNewThreadSelector:@selector(perform)
7859 title:UCLocalize("RUNNING")
7863 - (void) progressViewIsComplete:(ProgressView *)progress {
7864 if (confirm_ != nil) {
7865 [underlay_ addSubview:overlay_];
7866 [confirm_ popFromSuperviewAnimated:NO];
7872 - (void) setPage:(RVPage *)page {
7873 [page resetViewAnimated:NO];
7874 [page setDelegate:self];
7875 [book_ setPage:page];
7878 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7879 CydiaBrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7880 [browser loadURL:url];
7884 - (SectionsView *) sectionsView {
7885 if (sections_ == nil)
7886 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7890 - (ChangesView *) changesView {
7891 if (changes_ == nil)
7892 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7896 - (ManageView *) manageView {
7898 manage_ = (ManageView *) [[self
7899 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7900 withClass:[ManageView class]
7905 - (SearchView *) searchView {
7907 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7911 - (void) buttonBarItemTapped:(id)sender {
7912 unsigned tag = [sender tag];
7914 [book_ resetViewAnimated:YES];
7916 } else if (tag_ == 2)
7917 [[self sectionsView] resetView];
7920 case 1: _setHomePage(self); break;
7922 case 2: [self setPage:[self sectionsView]]; break;
7923 case 3: [self setPage:[self changesView]]; break;
7924 case 4: [self setPage:[self manageView]]; break;
7925 case 5: [self setPage:[self searchView]]; break;
7933 - (void) askForSettings {
7934 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
7936 CYActionSheet *role([[[CYActionSheet alloc]
7937 initWithTitle:UCLocalize("WHO_ARE_YOU")
7938 buttons:[NSArray arrayWithObjects:
7939 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
7940 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
7941 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
7943 defaultButtonIndex:-1
7946 [role setBodyText:UCLocalize("ROLE_EX")];
7948 int button([role yieldToPopupAlertAnimated:YES]);
7951 case 1: Role_ = @"User"; break;
7952 case 2: Role_ = @"Hacker"; break;
7953 case 3: Role_ = @"Developer"; break;
7958 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7962 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7969 - (void) setPackageView:(PackageView *)view {
7971 [view setPackage:nil];
7972 #if RecyclePackageViews
7973 if ([details_ count] < 3)
7974 [details_ addObject:view];
7979 - (PackageView *) _packageView {
7980 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7983 - (PackageView *) packageView {
7984 #if RecyclePackageViews
7986 size_t count([details_ count]);
7989 view = [self _packageView];
7991 [details_ addObject:[self _packageView]];
7993 view = [[[details_ lastObject] retain] autorelease];
7994 [details_ removeLastObject];
8001 return [self _packageView];
8005 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
8006 NSString *context([sheet context]);
8008 if ([context isEqualToString:@"missing"])
8010 else if ([context isEqualToString:@"cancel"]) {
8027 @synchronized (self) {
8032 [toolbar_ setBadgeValue:UCLocalize("Q_D") forButton:4];
8036 if (confirm_ != nil) {
8041 } else if ([context isEqualToString:@"fixhalf"]) {
8044 @synchronized (self) {
8045 for (Package *broken in broken_) {
8048 NSString *id = [broken id];
8049 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8050 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8051 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8052 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8061 [broken_ removeAllObjects];
8069 } else if ([context isEqualToString:@"upgrade"]) {
8072 @synchronized (self) {
8073 for (Package *essential in essential_)
8074 [essential install];
8096 - (void) system:(NSString *)command { _pooled
8097 system([command UTF8String]);
8100 - (void) applicationWillSuspend {
8102 [super applicationWillSuspend];
8105 - (void) applicationSuspend:(__GSEvent *)event {
8106 if (hud_ == nil && ![progress_ isRunning])
8107 [super applicationSuspend:event];
8110 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8112 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8115 - (void) _setSuspended:(BOOL)value {
8117 [super _setSuspended:value];
8120 - (UIProgressHUD *) addProgressHUD {
8121 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8122 [window_ setUserInteractionEnabled:NO];
8124 [progress_ addSubview:hud];
8128 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8130 [hud removeFromSuperview];
8131 [window_ setUserInteractionEnabled:YES];
8134 - (RVPage *) pageForPackage:(NSString *)name {
8135 if (Package *package = [database_ packageWithName:name]) {
8136 PackageView *view([self packageView]);
8137 [view setPackage:package];
8140 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8141 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8142 return [self _pageForURL:url withClass:[CydiaBrowserView class]];
8146 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8150 NSString *href([url absoluteString]);
8151 if ([href hasPrefix:@"apptapp://package/"])
8152 return [self pageForPackage:[href substringFromIndex:18]];
8154 NSString *scheme([[url scheme] lowercaseString]);
8155 if (![scheme isEqualToString:@"cydia"])
8157 NSString *path([url absoluteString]);
8158 if ([path length] < 8)
8160 path = [path substringFromIndex:8];
8161 if (![path hasPrefix:@"/"])
8162 path = [@"/" stringByAppendingString:path];
8164 if ([path isEqualToString:@"/add-source"])
8165 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8166 else if ([path isEqualToString:@"/storage"])
8167 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CydiaBrowserView class]];
8168 else if ([path isEqualToString:@"/sources"])
8169 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8170 else if ([path isEqualToString:@"/packages"])
8171 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8172 else if ([path hasPrefix:@"/url/"])
8173 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CydiaBrowserView class]];
8174 else if ([path hasPrefix:@"/launch/"])
8175 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8176 else if ([path hasPrefix:@"/package-settings/"])
8177 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8178 else if ([path hasPrefix:@"/package-signature/"])
8179 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8180 else if ([path hasPrefix:@"/package/"])
8181 return [self pageForPackage:[path substringFromIndex:9]];
8182 else if ([path hasPrefix:@"/files/"]) {
8183 NSString *name = [path substringFromIndex:7];
8185 if (Package *package = [database_ packageWithName:name]) {
8186 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8187 [files setPackage:package];
8195 - (void) applicationOpenURL:(NSURL *)url {
8196 [super applicationOpenURL:url];
8198 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8199 [self setPage:page];
8200 [toolbar_ showSelectionForButton:tag];
8205 - (void) applicationDidFinishLaunching:(id)unused {
8206 [BrowserView _initialize];
8208 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8210 Font12_ = [[UIFont systemFontOfSize:12] retain];
8211 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8212 Font14_ = [[UIFont systemFontOfSize:14] retain];
8213 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8214 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8218 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8219 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8221 window_ = [[UIWindow alloc] initWithContentRect:[UIHardware fullScreenApplicationContentRect]];
8222 [window_ orderFront:self];
8223 [window_ makeKey:self];
8224 [window_ setHidden:NO];
8225 //[window_ setAutorotates:YES];
8226 //[window_ setDelegate:self];
8228 database_ = [Database sharedInstance];
8230 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8231 [database_ setDelegate:progress_];
8232 [window_ setContentView:progress_];
8234 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8235 [progress_ setContentView:underlay_];
8237 [progress_ resetView];
8240 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8241 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8242 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8243 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8244 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8245 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8246 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8247 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8248 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8251 [self setIdleTimerDisabled:YES];
8253 hud_ = [self addProgressHUD];
8254 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8255 [self setStatusBarShowsProgress:YES];
8257 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8259 [self setStatusBarShowsProgress:NO];
8260 [self removeProgressHUD:hud_];
8263 if (ExecFork() == 0) {
8264 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8265 perror("launchctl stop");
8272 [self askForSettings];
8275 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
8277 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8278 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
8279 0, 0, screenrect.size.width, screenrect.size.height - 48
8280 ) database:database_];
8282 [book_ setDelegate:self];
8284 [overlay_ addSubview:book_];
8286 NSArray *buttonitems = [NSArray arrayWithObjects:
8287 [NSDictionary dictionaryWithObjectsAndKeys:
8288 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8289 @"home-up.png", kUIButtonBarButtonInfo,
8290 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
8291 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
8292 self, kUIButtonBarButtonTarget,
8293 @"Cydia", kUIButtonBarButtonTitle,
8294 @"0", kUIButtonBarButtonType,
8297 [NSDictionary dictionaryWithObjectsAndKeys:
8298 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8299 @"install-up.png", kUIButtonBarButtonInfo,
8300 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
8301 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
8302 self, kUIButtonBarButtonTarget,
8303 UCLocalize("SECTIONS"), kUIButtonBarButtonTitle,
8304 @"0", kUIButtonBarButtonType,
8307 [NSDictionary dictionaryWithObjectsAndKeys:
8308 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8309 @"changes-up.png", kUIButtonBarButtonInfo,
8310 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
8311 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
8312 self, kUIButtonBarButtonTarget,
8313 UCLocalize("CHANGES"), kUIButtonBarButtonTitle,
8314 @"0", kUIButtonBarButtonType,
8317 [NSDictionary dictionaryWithObjectsAndKeys:
8318 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8319 @"manage-up.png", kUIButtonBarButtonInfo,
8320 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
8321 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
8322 self, kUIButtonBarButtonTarget,
8323 UCLocalize("MANAGE"), kUIButtonBarButtonTitle,
8324 @"0", kUIButtonBarButtonType,
8327 [NSDictionary dictionaryWithObjectsAndKeys:
8328 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8329 @"search-up.png", kUIButtonBarButtonInfo,
8330 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
8331 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
8332 self, kUIButtonBarButtonTarget,
8333 UCLocalize("SEARCH"), kUIButtonBarButtonTitle,
8334 @"0", kUIButtonBarButtonType,
8338 toolbar_ = [[UIToolbar alloc]
8340 withFrame:CGRectMake(
8341 0, screenrect.size.height - ButtonBarHeight_,
8342 screenrect.size.width, ButtonBarHeight_
8344 withItemList:buttonitems
8347 [toolbar_ setDelegate:self];
8348 [toolbar_ setBarStyle:1];
8349 [toolbar_ setButtonBarTrackingMode:2];
8351 int buttons[5] = {1, 2, 3, 4, 5};
8352 [toolbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
8353 [toolbar_ showButtonGroup:0 withDuration:0];
8355 for (int i = 0; i != 5; ++i)
8356 [[toolbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
8357 i * (screenrect.size.width / 5) + (screenrect.size.width / 5 - ButtonBarWidth_) / 2, 1,
8358 ButtonBarWidth_, ButtonBarHeight_
8361 [toolbar_ showSelectionForButton:1];
8362 [overlay_ addSubview:toolbar_];
8364 [UIKeyboard initImplementationNow];
8365 /*CGSize keysize = [UIKeyboard defaultSize];
8366 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
8367 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
8368 [overlay_ addSubview:keyboard_];*/
8370 [underlay_ addSubview:overlay_];
8374 #if RecyclePackageViews
8375 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8376 [details_ addObject:[self _packageView]];
8377 [details_ addObject:[self _packageView]];
8385 - (void) showKeyboard:(BOOL)show {
8386 CGSize keysize([UIKeyboard defaultSize]);
8387 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8388 CGRect keyup(keydown);
8389 keyup.origin.y -= keysize.height;
8391 UIFrameAnimation *animation([[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease]);
8392 [animation setSignificantRectFields:2];
8395 [animation setStartFrame:keydown];
8396 [animation setEndFrame:keyup];
8397 [keyboard_ activate];
8399 [animation setStartFrame:keyup];
8400 [animation setEndFrame:keydown];
8401 [keyboard_ deactivate];
8404 [[UIAnimator sharedAnimator]
8405 addAnimations:[NSArray arrayWithObjects:animation, nil]
8406 withDuration:KeyboardTime_
8411 - (void) slideUp:(UIActionSheet *)alert {
8412 [alert presentSheetInView:overlay_];
8418 id Alloc_(id self, SEL selector) {
8419 id object = alloc_(self, selector);
8420 lprintf("[%s]A-%p\n", self->isa->name, object);
8425 id Dealloc_(id self, SEL selector) {
8426 id object = dealloc_(self, selector);
8427 lprintf("[%s]D-%p\n", self->isa->name, object);
8431 Class $WebDefaultUIKitDelegate;
8433 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8434 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8435 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8436 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8439 int main(int argc, char *argv[]) { _pooled
8442 if (Class $UIDevice = objc_getClass("UIDevice")) {
8443 UIDevice *device([$UIDevice currentDevice]);
8444 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8448 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8450 /* Library Hacks {{{ */
8451 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8453 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8454 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8455 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8456 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8457 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8460 /* Set Locale {{{ */
8461 Locale_ = CFLocaleCopyCurrent();
8462 Languages_ = [NSLocale preferredLanguages];
8463 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8464 //NSLog(@"%@", [Languages_ description]);
8467 if (Languages_ == nil || [Languages_ count] == 0)
8468 // XXX: consider just setting to C and then falling through?
8471 lang = [[Languages_ objectAtIndex:0] UTF8String];
8472 setenv("LANG", lang, true);
8475 //std::setlocale(LC_ALL, lang);
8476 NSLog(@"Setting Language: %s", lang);
8479 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8481 /* Parse Arguments {{{ */
8482 bool substrate(false);
8488 for (int argi(1); argi != argc; ++argi)
8489 if (strcmp(argv[argi], "--") == 0) {
8491 argv[argi] = argv[0];
8497 for (int argi(1); argi != arge; ++argi)
8498 if (strcmp(args[argi], "--substrate") == 0)
8501 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8505 App_ = [[NSBundle mainBundle] bundlePath];
8506 Home_ = NSHomeDirectory();
8512 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8513 alloc_ = alloc->method_imp;
8514 alloc->method_imp = (IMP) &Alloc_;*/
8516 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8517 dealloc_ = dealloc->method_imp;
8518 dealloc->method_imp = (IMP) &Dealloc_;*/
8520 /* System Information {{{ */
8524 size = sizeof(maxproc);
8525 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8526 perror("sysctlbyname(\"kern.maxproc\", ?)");
8527 else if (maxproc < 64) {
8529 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8530 perror("sysctlbyname(\"kern.maxproc\", #)");
8533 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8534 char *osversion = new char[size];
8535 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8536 perror("sysctlbyname(\"kern.osversion\", ?)");
8538 System_ = [NSString stringWithUTF8String:osversion];
8540 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8541 char *machine = new char[size];
8542 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8543 perror("sysctlbyname(\"hw.machine\", ?)");
8547 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8548 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8549 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8550 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8554 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8555 NSData *data((NSData *) ecid);
8556 size_t length([data length]);
8557 uint8_t bytes[length];
8558 [data getBytes:bytes];
8559 char string[length * 2 + 1];
8560 for (size_t i(0); i != length; ++i)
8561 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8562 ChipID_ = [NSString stringWithUTF8String:string];
8566 IOObjectRelease(service);
8570 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8572 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8573 Build_ = [system objectForKey:@"ProductBuildVersion"];
8574 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8575 Product_ = [info objectForKey:@"SafariProductVersion"];
8576 Safari_ = [info objectForKey:@"CFBundleVersion"];
8579 /* Load Database {{{ */
8581 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8583 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8586 if (Metadata_ == NULL)
8587 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8589 Settings_ = [Metadata_ objectForKey:@"Settings"];
8591 Packages_ = [Metadata_ objectForKey:@"Packages"];
8592 Sections_ = [Metadata_ objectForKey:@"Sections"];
8593 Sources_ = [Metadata_ objectForKey:@"Sources"];
8595 Token_ = [Metadata_ objectForKey:@"Token"];
8598 if (Settings_ != nil)
8599 Role_ = [Settings_ objectForKey:@"Role"];
8601 if (Packages_ == nil) {
8602 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8603 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8606 if (Sections_ == nil) {
8607 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8608 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8611 if (Sources_ == nil) {
8612 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8613 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8618 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8621 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8623 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
8624 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
8625 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8626 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8627 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8628 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8630 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
8632 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8633 unlink("/tmp/.cydia.fw");
8635 } else if (access("/User", F_OK) != 0 || version < 1) {
8638 system("/usr/libexec/cydia/firmware.sh");
8642 _assert([[NSFileManager defaultManager]
8643 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8644 withIntermediateDirectories:YES
8649 if (access("/tmp/cydia.chk", F_OK) == 0) {
8650 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8651 _assert(errno == ENOENT);
8652 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8653 _assert(errno == ENOENT);
8656 /* APT Initialization {{{ */
8657 _assert(pkgInitConfig(*_config));
8658 _assert(pkgInitSystem(*_config, _system));
8661 _config->Set("APT::Acquire::Translation", lang);
8662 _config->Set("Acquire::http::Timeout", 15);
8663 _config->Set("Acquire::http::MaxParallel", 3);
8665 /* Color Choices {{{ */
8666 space_ = CGColorSpaceCreateDeviceRGB();
8668 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8669 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8670 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8671 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8672 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8673 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8674 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8675 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8676 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8678 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8679 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8681 /* UIKit Configuration {{{ */
8682 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8683 if ($GSFontSetUseLegacyFontMetrics != NULL)
8684 $GSFontSetUseLegacyFontMetrics(YES);
8686 // XXX: I have a feeling this was important
8687 //UIKeyboardDisableAutomaticAppearance();
8690 Colon_ = UCLocalize("COLON_DELIMITED");
8691 Error_ = UCLocalize("ERROR");
8692 Warning_ = UCLocalize("WARNING");
8695 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8697 CGColorSpaceRelease(space_);