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 hasSupportingRole] && [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_ && (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 _profile(Package$isUnfilteredAndSelectedForBy)
2787 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2788 value &= [self unfiltered];
2791 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2792 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2799 - (bool) isInstalledAndVisible:(NSNumber *)number {
2800 return (![number boolValue] || [self visible]) && ![self uninstalled];
2803 - (bool) isVisibleInSection:(NSString *)name {
2804 NSString *section = [self section];
2809 section == nil && [name length] == 0 ||
2810 [name isEqualToString:section]
2814 - (bool) isVisibleInSource:(Source *)source {
2815 return [self source] == source && [self visible];
2820 /* Section Class {{{ */
2821 @interface Section : NSObject {
2826 NSString *localized_;
2829 - (NSComparisonResult) compareByLocalized:(Section *)section;
2830 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2831 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2832 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2833 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2834 - (NSString *) name;
2841 - (void) addToCount;
2843 - (void) setCount:(size_t)count;
2844 - (NSString *) localized;
2848 @implementation Section
2852 if (localized_ != nil)
2853 [localized_ release];
2857 - (NSComparisonResult) compareByLocalized:(Section *)section {
2858 NSString *lhs(localized_);
2859 NSString *rhs([section localized]);
2861 /*if ([lhs length] != 0 && [rhs length] != 0) {
2862 unichar lhc = [lhs characterAtIndex:0];
2863 unichar rhc = [rhs characterAtIndex:0];
2865 if (isalpha(lhc) && !isalpha(rhc))
2866 return NSOrderedAscending;
2867 else if (!isalpha(lhc) && isalpha(rhc))
2868 return NSOrderedDescending;
2871 return [lhs compare:rhs options:LaxCompareOptions_];
2874 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2875 if ((self = [self initWithName:name localize:NO]) != nil) {
2876 if (localized != nil)
2877 localized_ = [localized retain];
2881 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2882 return [self initWithName:name row:0 localize:localize];
2885 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2886 if ((self = [super init]) != nil) {
2887 name_ = [name retain];
2891 localized_ = [LocalizeSection(name_) retain];
2895 /* XXX: localize the index thingees */
2896 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2897 if ((self = [super init]) != nil) {
2898 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2904 - (NSString *) name {
2924 - (void) addToCount {
2928 - (void) setCount:(size_t)count {
2932 - (NSString *) localized {
2939 static NSString *Colon_;
2940 static NSString *Error_;
2941 static NSString *Warning_;
2943 /* Database Implementation {{{ */
2944 @implementation Database
2946 + (Database *) sharedInstance {
2947 static Database *instance;
2948 if (instance == nil)
2949 instance = [[Database alloc] init];
2959 NSRecycleZone(zone_);
2960 // XXX: malloc_destroy_zone(zone_);
2961 apr_pool_destroy(pool_);
2965 - (void) _readCydia:(NSNumber *)fd { _pooled
2966 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2967 std::istream is(&ib);
2970 static Pcre finish_r("^finish:([^:]*)$");
2972 while (std::getline(is, line)) {
2973 const char *data(line.c_str());
2974 size_t size = line.size();
2975 lprintf("C:%s\n", data);
2977 if (finish_r(data, size)) {
2978 NSString *finish = finish_r[1];
2979 int index = [Finishes_ indexOfObject:finish];
2980 if (index != INT_MAX && index > Finish_)
2988 - (void) _readStatus:(NSNumber *)fd { _pooled
2989 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2990 std::istream is(&ib);
2993 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2994 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2996 while (std::getline(is, line)) {
2997 const char *data(line.c_str());
2998 size_t size(line.size());
2999 lprintf("S:%s\n", data);
3001 if (conffile_r(data, size)) {
3002 [delegate_ setConfigurationData:conffile_r[1]];
3003 } else if (strncmp(data, "status: ", 8) == 0) {
3004 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3005 [delegate_ setProgressTitle:string];
3006 } else if (pmstatus_r(data, size)) {
3007 std::string type([pmstatus_r[1] UTF8String]);
3008 NSString *id = pmstatus_r[2];
3010 float percent([pmstatus_r[3] floatValue]);
3011 [delegate_ setProgressPercent:(percent / 100)];
3013 NSString *string = pmstatus_r[4];
3015 if (type == "pmerror")
3016 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3017 withObject:[NSArray arrayWithObjects:string, id, nil]
3020 else if (type == "pmstatus") {
3021 [delegate_ setProgressTitle:string];
3022 } else if (type == "pmconffile")
3023 [delegate_ setConfigurationData:string];
3025 lprintf("E:unknown pmstatus\n");
3027 lprintf("E:unknown status\n");
3033 - (void) _readOutput:(NSNumber *)fd { _pooled
3034 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3035 std::istream is(&ib);
3038 while (std::getline(is, line)) {
3039 lprintf("O:%s\n", line.c_str());
3040 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3050 - (Package *) packageWithName:(NSString *)name {
3051 @synchronized ([Database class]) {
3052 if (static_cast<pkgDepCache *>(cache_) == NULL)
3054 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3055 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3058 - (Database *) init {
3059 if ((self = [super init]) != nil) {
3066 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3067 apr_pool_create(&pool_, NULL);
3069 packages_ = [[NSMutableArray alloc] init];
3073 _assert(pipe(fds) != -1);
3076 _config->Set("APT::Keep-Fds::", cydiafd_);
3077 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3080 detachNewThreadSelector:@selector(_readCydia:)
3082 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3085 _assert(pipe(fds) != -1);
3089 detachNewThreadSelector:@selector(_readStatus:)
3091 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3094 _assert(pipe(fds) != -1);
3095 _assert(dup2(fds[0], 0) != -1);
3096 _assert(close(fds[0]) != -1);
3098 input_ = fdopen(fds[1], "a");
3100 _assert(pipe(fds) != -1);
3101 _assert(dup2(fds[1], 1) != -1);
3102 _assert(close(fds[1]) != -1);
3105 detachNewThreadSelector:@selector(_readOutput:)
3107 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3112 - (pkgCacheFile &) cache {
3116 - (pkgDepCache::Policy *) policy {
3120 - (pkgRecords *) records {
3124 - (pkgProblemResolver *) resolver {
3128 - (pkgAcquire &) fetcher {
3132 - (pkgSourceList &) list {
3136 - (NSArray *) packages {
3140 - (NSArray *) sources {
3141 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3142 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3143 [sources addObject:i->second];
3147 - (NSArray *) issues {
3148 if (cache_->BrokenCount() == 0)
3151 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3153 for (Package *package in packages_) {
3154 if (![package broken])
3156 pkgCache::PkgIterator pkg([package iterator]);
3158 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3159 [entry addObject:[package name]];
3160 [issues addObject:entry];
3162 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3166 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3167 pkgCache::DepIterator start;
3168 pkgCache::DepIterator end;
3169 dep.GlobOr(start, end); // ++dep
3171 if (!cache_->IsImportantDep(end))
3173 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3176 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3177 [entry addObject:failure];
3178 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3180 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3181 if (Package *package = [self packageWithName:name])
3182 name = [package name];
3183 [failure addObject:name];
3185 pkgCache::PkgIterator target(start.TargetPkg());
3186 if (target->ProvidesList != 0)
3187 [failure addObject:@"?"];
3189 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3191 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3192 else if (!cache_[target].CandidateVerIter(cache_).end())
3193 [failure addObject:@"-"];
3194 else if (target->ProvidesList == 0)
3195 [failure addObject:@"!"];
3197 [failure addObject:@"%"];
3201 if (start.TargetVer() != 0)
3202 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3213 - (bool) popErrorWithTitle:(NSString *)title {
3215 std::string message;
3217 while (!_error->empty()) {
3219 bool warning(!_error->PopMessage(error));
3223 size_t size(error.size());
3224 if (size == 0 || error[size - 1] != '\n')
3226 error.resize(size - 1);
3228 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3230 if (!message.empty())
3235 if (fatal && !message.empty())
3236 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3241 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3242 return [self popErrorWithTitle:title] || !success;
3245 - (void) reloadData { _pooled
3246 @synchronized ([Database class]) {
3247 @synchronized (self) {
3251 [packages_ removeAllObjects];
3277 apr_pool_clear(pool_);
3278 NSRecycleZone(zone_);
3280 int chk(creat("/tmp/cydia.chk", 0644));
3284 NSString *title(UCLocalize("DATABASE"));
3287 if (!cache_.Open(progress_, true)) { pop:
3289 bool warning(!_error->PopMessage(error));
3290 lprintf("cache_.Open():[%s]\n", error.c_str());
3292 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3293 [delegate_ repairWithSelector:@selector(configure)];
3294 else if (error == "The package lists or status file could not be parsed or opened.")
3295 [delegate_ repairWithSelector:@selector(update)];
3296 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3297 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3298 // else if (error == "The list of sources could not be read.")
3300 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3309 unlink("/tmp/cydia.chk");
3311 now_ = [[NSDate date] retain];
3313 policy_ = new pkgDepCache::Policy();
3314 records_ = new pkgRecords(cache_);
3315 resolver_ = new pkgProblemResolver(cache_);
3316 fetcher_ = new pkgAcquire(&status_);
3319 list_ = new pkgSourceList();
3320 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3323 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3324 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3328 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3331 if (cache_->BrokenCount() != 0) {
3332 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3335 if (cache_->BrokenCount() != 0) {
3336 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3340 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3346 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3347 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3348 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3349 // XXX: this could be more intelligent
3350 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3351 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3353 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3360 /*std::vector<Package *> packages;
3361 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3362 [packages_ release];
3367 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3368 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3369 //packages.push_back(package);
3370 [packages_ addObject:package];
3374 /*if (packages.empty())
3375 packages_ = [[NSArray alloc] init];
3377 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3380 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3381 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3382 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3390 /*if (!packages.empty())
3391 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3392 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3394 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3396 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3398 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3404 - (void) configure {
3405 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3406 system([dpkg UTF8String]);
3410 // XXX: I don't remember this condition
3415 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3417 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3419 if ([self popErrorWithTitle:title])
3423 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3426 public pkgArchiveCleaner
3429 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3434 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3441 fetcher_->Shutdown();
3443 pkgRecords records(cache_);
3445 lock_ = new FileFd();
3446 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3448 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3450 if ([self popErrorWithTitle:title])
3454 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3457 manager_ = (_system->CreatePM(cache_));
3458 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3465 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3467 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3469 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3471 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3472 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3475 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3480 bool failed = false;
3481 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3482 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3484 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3487 std::string uri = (*item)->DescURI();
3488 std::string error = (*item)->ErrorText;
3490 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3493 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3494 withObject:[NSArray arrayWithObjects:
3495 [NSString stringWithUTF8String:error.c_str()],
3507 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3509 if (_error->PendingError()) {
3514 if (result == pkgPackageManager::Failed) {
3519 if (result != pkgPackageManager::Completed) {
3524 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3526 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3528 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3529 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3532 if (![before isEqualToArray:after])
3537 NSString *title(UCLocalize("UPGRADE"));
3538 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3544 [self updateWithStatus:status_];
3547 - (void) setVisible {
3548 for (Package *package in packages_)
3549 [package setVisible];
3552 - (void) updateWithStatus:(Status &)status {
3553 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3554 NSString *title(UCLocalize("REFRESHING_DATA"));
3557 if (!list.ReadMainList())
3558 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3561 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3562 if ([self popErrorWithTitle:title])
3565 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3566 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */;
3568 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3572 - (void) setDelegate:(id)delegate {
3573 delegate_ = delegate;
3574 status_.setDelegate(delegate);
3575 progress_.setDelegate(delegate);
3578 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3579 SourceMap::const_iterator i(sources_.find(file->ID));
3580 return i == sources_.end() ? nil : i->second;
3586 /* Confirmation View {{{ */
3587 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3588 if (!iterator.end())
3589 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3590 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3592 pkgCache::PkgIterator package(dep.TargetPkg());
3595 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3602 /* Web Scripting {{{ */
3603 @interface CydiaObject : NSObject {
3607 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3610 @implementation CydiaObject
3613 [indirect_ release];
3617 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3618 if ((self = [super init]) != nil) {
3619 indirect_ = [indirect retain];
3623 + (NSArray *) _attributeKeys {
3624 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3627 - (NSArray *) attributeKeys {
3628 return [[self class] _attributeKeys];
3631 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3632 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3635 - (NSString *) device {
3636 return [[UIDevice currentDevice] uniqueIdentifier];
3639 #if 0 // XXX: implement!
3640 - (NSString *) mac {
3641 if (![indirect_ promptForSensitive:@"Mac Address"])
3645 - (NSString *) serial {
3646 if (![indirect_ promptForSensitive:@"Serial #"])
3650 - (NSString *) firewire {
3651 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3655 - (NSString *) imei {
3656 if (![indirect_ promptForSensitive:@"IMEI"])
3661 + (NSString *) webScriptNameForSelector:(SEL)selector {
3662 if (selector == @selector(close))
3664 else if (selector == @selector(getInstalledPackages))
3665 return @"getInstalledPackages";
3666 else if (selector == @selector(getPackageById:))
3667 return @"getPackageById";
3668 else if (selector == @selector(setAutoPopup:))
3669 return @"setAutoPopup";
3670 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3671 return @"setButtonImage";
3672 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3673 return @"setButtonTitle";
3674 else if (selector == @selector(setFinishHook:))
3675 return @"setFinishHook";
3676 else if (selector == @selector(setPopupHook:))
3677 return @"setPopupHook";
3678 else if (selector == @selector(setSpecial:))
3679 return @"setSpecial";
3680 else if (selector == @selector(setViewportWidth:))
3681 return @"setViewportWidth";
3682 else if (selector == @selector(supports:))
3684 else if (selector == @selector(stringWithFormat:arguments:))
3686 else if (selector == @selector(localizedStringForKey:value:table:))
3688 else if (selector == @selector(du:))
3690 else if (selector == @selector(statfs:))
3696 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3697 return [self webScriptNameForSelector:selector] == nil;
3700 - (BOOL) supports:(NSString *)feature {
3701 return [feature isEqualToString:@"window.open"];
3704 - (NSArray *) getInstalledPackages {
3705 NSArray *packages([[Database sharedInstance] packages]);
3706 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3707 for (Package *package in installed)
3708 if ([package installed] != nil)
3709 [installed addObject:package];
3713 - (Package *) getPackageById:(NSString *)id {
3714 Package *package([[Database sharedInstance] packageWithName:id]);
3719 - (NSArray *) statfs:(NSString *)path {
3722 if (path == nil || statfs([path UTF8String], &stat) == -1)
3725 return [NSArray arrayWithObjects:
3726 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3727 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3728 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3732 - (NSNumber *) du:(NSString *)path {
3733 NSNumber *value(nil);
3736 _assert(pipe(fds) != -1);
3738 pid_t pid(ExecFork());
3740 _assert(dup2(fds[1], 1) != -1);
3741 _assert(close(fds[0]) != -1);
3742 _assert(close(fds[1]) != -1);
3743 /* XXX: this should probably not use du */
3744 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3749 _assert(close(fds[1]) != -1);
3751 if (FILE *du = fdopen(fds[0], "r")) {
3753 while (fgets(line, sizeof(line), du) != NULL) {
3754 size_t length(strlen(line));
3755 while (length != 0 && line[length - 1] == '\n')
3756 line[--length] = '\0';
3757 if (char *tab = strchr(line, '\t')) {
3759 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3764 } else _assert(close(fds[0]));
3768 if (waitpid(pid, &status, 0) == -1)
3771 else _assert(false);
3780 - (void) setAutoPopup:(BOOL)popup {
3781 [indirect_ setAutoPopup:popup];
3784 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3785 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3788 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3789 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3792 - (void) setSpecial:(id)function {
3793 [indirect_ setSpecial:function];
3796 - (void) setFinishHook:(id)function {
3797 [indirect_ setFinishHook:function];
3800 - (void) setPopupHook:(id)function {
3801 [indirect_ setPopupHook:function];
3804 - (void) setViewportWidth:(float)width {
3805 [indirect_ setViewportWidth:width];
3808 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3809 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3810 unsigned count([arguments count]);
3812 for (unsigned i(0); i != count; ++i)
3813 values[i] = [arguments objectAtIndex:i];
3814 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3817 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3818 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3820 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3822 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3828 @interface CydiaBrowserView : BrowserView {
3829 CydiaObject *cydia_;
3834 @implementation CydiaBrowserView
3841 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3844 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3845 [super webView:sender didClearWindowObject:window forFrame:frame];
3847 WebDataSource *source([frame dataSource]);
3848 NSURLResponse *response([source response]);
3849 NSURL *url([response URL]);
3850 NSString *scheme([url scheme]);
3852 NSHTTPURLResponse *http;
3853 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3854 http = (NSHTTPURLResponse *) response;
3858 NSDictionary *headers([http allHeaderFields]);
3859 NSString *host([url host]);
3860 [self setHeaders:headers forHost:host];
3862 [window setValue:cydia_ forKey:@"cydia"];
3865 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3866 if (System_ != NULL)
3867 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3868 if (Machine_ != NULL)
3869 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3871 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3873 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3876 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3877 NSMutableURLRequest *copy = [request mutableCopy];
3878 [self _setMoreHeaders:copy];
3882 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
3883 if ((self = [super initWithBook:book forWidth:width ofClass:[CydiaBrowserView class]]) != nil) {
3884 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3886 WebView *webview([webview_ webView]);
3888 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3890 NSString *application = package == nil ? @"Cydia" : [NSString
3891 stringWithFormat:@"Cydia/%@",
3896 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3898 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3899 if (Product_ != nil)
3900 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3902 [webview setApplicationNameForUserAgent:application];
3908 @protocol ConfirmationViewDelegate
3914 @interface ConfirmationView : CydiaBrowserView {
3915 _transient Database *database_;
3916 UIActionSheet *essential_;
3923 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3927 @implementation ConfirmationView
3934 if (essential_ != nil)
3935 [essential_ release];
3941 [book_ popFromSuperviewAnimated:YES];
3944 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3945 NSString *context([sheet context]);
3947 if ([context isEqualToString:@"remove"]) {
3955 [delegate_ confirm];
3961 } else if ([context isEqualToString:@"unable"]) {
3965 [super alertSheet:sheet buttonClicked:button];
3968 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3969 [super webView:sender didClearWindowObject:window forFrame:frame];
3970 [window setValue:changes_ forKey:@"changes"];
3971 [window setValue:issues_ forKey:@"issues"];
3972 [window setValue:sizes_ forKey:@"sizes"];
3975 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3976 if ((self = [super initWithBook:book]) != nil) {
3977 database_ = database;
3979 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3980 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3981 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3982 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3983 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3987 pkgDepCache::Policy *policy([database_ policy]);
3989 pkgCacheFile &cache([database_ cache]);
3990 NSArray *packages = [database_ packages];
3991 for (Package *package in packages) {
3992 pkgCache::PkgIterator iterator = [package iterator];
3993 pkgDepCache::StateCache &state(cache[iterator]);
3995 NSString *name([package name]);
3997 if (state.NewInstall())
3998 [installing addObject:name];
3999 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4000 [reinstalling addObject:name];
4001 else if (state.Upgrade())
4002 [upgrading addObject:name];
4003 else if (state.Downgrade())
4004 [downgrading addObject:name];
4005 else if (state.Delete()) {
4006 if ([package essential])
4008 [removing addObject:name];
4011 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4012 substrate_ |= DepSubstrate(iterator.CurrentVer());
4017 else if (Advanced_) {
4018 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4020 essential_ = [[UIActionSheet alloc]
4021 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4022 buttons:[NSArray arrayWithObjects:
4023 [NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")],
4024 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4026 defaultButtonIndex:0
4031 [essential_ setDestructiveButtonIndex:1];
4032 [essential_ setBodyText:UCLocalize("REMOVING_ESSENTIALS_EX")];
4034 essential_ = [[UIActionSheet alloc]
4035 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4036 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4037 defaultButtonIndex:0
4042 [essential_ setBodyText:UCLocalize("UNABLE_TO_COMPLY_EX")];
4045 changes_ = [[NSArray alloc] initWithObjects:
4053 issues_ = [database_ issues];
4055 issues_ = [issues_ retain];
4057 sizes_ = [[NSArray alloc] initWithObjects:
4058 SizeString([database_ fetcher].FetchNeeded()),
4059 SizeString([database_ fetcher].PartialPresent()),
4060 SizeString([database_ cache]->UsrSize()),
4063 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4067 - (NSString *) backButtonTitle {
4068 return UCLocalize("CONFIRM");
4071 - (NSString *) leftButtonTitle {
4072 return [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")];
4075 - (id) rightButtonTitle {
4076 return issues_ != nil ? nil : [super rightButtonTitle];
4079 - (id) _rightButtonTitle {
4080 #if AlwaysReload || IgnoreInstall
4081 return [super _rightButtonTitle];
4083 return UCLocalize("CONFIRM");
4087 - (void) _leftButtonClicked {
4092 - (void) _rightButtonClicked {
4094 return [super _rightButtonClicked];
4096 if (essential_ != nil)
4097 [essential_ popupAlertAnimated:YES];
4101 [delegate_ confirm];
4109 /* Progress Data {{{ */
4110 @interface ProgressData : NSObject {
4116 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4123 @implementation ProgressData
4125 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4126 if ((self = [super init]) != nil) {
4127 selector_ = selector;
4147 /* Progress View {{{ */
4148 @interface ProgressView : UIView <
4149 ConfigurationDelegate,
4152 _transient Database *database_;
4154 UIView *background_;
4155 UITransitionView *transition_;
4157 UINavigationBar *navbar_;
4158 UIProgressBar *progress_;
4159 UITextView *output_;
4160 UITextLabel *status_;
4161 UIPushButton *close_;
4164 SHA1SumValue springlist_;
4165 SHA1SumValue notifyconf_;
4169 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
4170 - (void) setContentView:(UIView *)view;
4173 - (void) _retachThread;
4174 - (void) _detachNewThreadData:(ProgressData *)data;
4175 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4181 @protocol ProgressViewDelegate
4182 - (void) progressViewIsComplete:(ProgressView *)sender;
4185 @implementation ProgressView
4188 [transition_ setDelegate:nil];
4189 [navbar_ setDelegate:nil];
4192 if (background_ != nil)
4193 [background_ release];
4194 [transition_ release];
4197 [progress_ release];
4206 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
4207 if ((self = [super initWithFrame:frame]) != nil) {
4208 database_ = database;
4209 delegate_ = delegate;
4211 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
4212 [transition_ setDelegate:self];
4214 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
4216 background_ = [[UIView alloc] initWithFrame:[self bounds]];
4217 [background_ setBackgroundColor:[UIColor blackColor]];
4218 [self addSubview:background_];
4220 [self addSubview:transition_];
4222 CGSize navsize = [UINavigationBar defaultSize];
4223 CGRect navrect = {{0, 0}, navsize};
4225 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
4226 [overlay_ addSubview:navbar_];
4228 [navbar_ setBarStyle:1];
4229 [navbar_ setDelegate:self];
4231 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
4232 [navbar_ pushNavigationItem:navitem];
4234 CGRect bounds = [overlay_ bounds];
4235 CGSize prgsize = [UIProgressBar defaultSize];
4238 (bounds.size.width - prgsize.width) / 2,
4239 bounds.size.height - prgsize.height - 20
4242 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
4243 [progress_ setStyle:0];
4245 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
4247 bounds.size.height - prgsize.height - 50,
4248 bounds.size.width - 20,
4252 [status_ setColor:[UIColor whiteColor]];
4253 [status_ setBackgroundColor:[UIColor clearColor]];
4255 [status_ setCentersHorizontally:YES];
4256 //[status_ setFont:font];
4258 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
4260 navrect.size.height + 20,
4261 bounds.size.width - 20,
4262 bounds.size.height - navsize.height - 62 - navrect.size.height
4265 //[output_ setTextFont:@"Courier New"];
4266 [output_ setFont:[[output_ font] fontWithSize:12]];
4268 [output_ setTextColor:[UIColor whiteColor]];
4269 [output_ setBackgroundColor:[UIColor clearColor]];
4271 [output_ setMarginTop:0];
4272 [output_ setAllowsRubberBanding:YES];
4273 [output_ setEditable:NO];
4275 [overlay_ addSubview:output_];
4277 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
4279 bounds.size.height - prgsize.height - 50,
4280 bounds.size.width - 20,
4284 [close_ setAutosizesToFit:NO];
4285 [close_ setDrawsShadow:YES];
4286 [close_ setStretchBackground:YES];
4287 [close_ setEnabled:YES];
4289 UIFont *bold = [UIFont boldSystemFontOfSize:22];
4290 [close_ setTitleFont:bold];
4292 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4293 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4294 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4298 - (void) setContentView:(UIView *)view {
4299 view_ = [view retain];
4302 - (void) resetView {
4303 [transition_ transition:6 toView:view_];
4306 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4307 NSString *context([sheet context]);
4309 if ([context isEqualToString:@"conffile"]) {
4310 FILE *input = [database_ input];
4314 fprintf(input, "N\n");
4318 fprintf(input, "Y\n");
4328 - (void) closeButtonPushed {
4337 [delegate_ terminateWithSuccess];
4338 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4339 [delegate_ suspendWithAnimation:YES];
4341 [delegate_ suspend];*/
4345 system("launchctl stop com.apple.SpringBoard");
4349 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4358 - (void) _retachThread {
4359 UINavigationItem *item([navbar_ topItem]);
4360 [item setTitle:UCLocalize("COMPLETE")];
4362 [overlay_ addSubview:close_];
4363 [progress_ removeFromSuperview];
4364 [status_ removeFromSuperview];
4366 [database_ popErrorWithTitle:title_];
4367 [delegate_ progressViewIsComplete:self];
4371 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4374 MMap mmap(file, MMap::ReadOnly);
4376 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4377 if (!(notifyconf_ == sha1.Result()))
4384 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4387 MMap mmap(file, MMap::ReadOnly);
4389 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4390 if (!(springlist_ == sha1.Result()))
4396 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break;
4397 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4398 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4399 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4400 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4403 system("su -c /usr/bin/uicache mobile");
4405 [delegate_ setStatusBarShowsProgress:NO];
4408 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4409 [[data target] performSelector:[data selector] withObject:[data object]];
4412 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4415 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4421 title_ = [title retain];
4423 UINavigationItem *item([navbar_ topItem]);
4424 [item setTitle:title_];
4426 [status_ setText:nil];
4427 [output_ setText:@""];
4428 [progress_ setProgress:0];
4430 [close_ removeFromSuperview];
4431 [overlay_ addSubview:progress_];
4432 [overlay_ addSubview:status_];
4434 [delegate_ setStatusBarShowsProgress:YES];
4439 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4442 MMap mmap(file, MMap::ReadOnly);
4444 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4445 notifyconf_ = sha1.Result();
4451 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4454 MMap mmap(file, MMap::ReadOnly);
4456 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4457 springlist_ = sha1.Result();
4461 [transition_ transition:6 toView:overlay_];
4464 detachNewThreadSelector:@selector(_detachNewThreadData:)
4466 withObject:[[ProgressData alloc]
4467 initWithSelector:selector
4474 - (void) repairWithSelector:(SEL)selector {
4476 detachNewThreadSelector:selector
4479 title:UCLocalize("REPAIRING")
4483 - (void) setConfigurationData:(NSString *)data {
4485 performSelectorOnMainThread:@selector(_setConfigurationData:)
4491 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4492 CYActionSheet *sheet([[[CYActionSheet alloc]
4494 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4495 defaultButtonIndex:0
4498 [sheet setBodyText:error];
4499 [sheet yieldToPopupAlertAnimated:YES];
4503 - (void) setProgressTitle:(NSString *)title {
4505 performSelectorOnMainThread:@selector(_setProgressTitle:)
4511 - (void) setProgressPercent:(float)percent {
4513 performSelectorOnMainThread:@selector(_setProgressPercent:)
4514 withObject:[NSNumber numberWithFloat:percent]
4519 - (void) startProgress {
4522 - (void) addProgressOutput:(NSString *)output {
4524 performSelectorOnMainThread:@selector(_addProgressOutput:)
4530 - (bool) isCancelling:(size_t)received {
4534 - (void) _setConfigurationData:(NSString *)data {
4535 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4537 if (!conffile_r(data)) {
4538 lprintf("E:invalid conffile\n");
4542 NSString *ofile = conffile_r[1];
4543 //NSString *nfile = conffile_r[2];
4545 UIActionSheet *sheet = [[[UIActionSheet alloc]
4546 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4547 buttons:[NSArray arrayWithObjects:
4548 UCLocalize("KEEP_OLD_COPY"),
4549 UCLocalize("ACCEPT_NEW_COPY"),
4550 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4552 defaultButtonIndex:0
4557 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4558 [sheet popupAlertAnimated:YES];
4561 - (void) _setProgressTitle:(NSString *)title {
4562 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4563 for (size_t i(0), e([words count]); i != e; ++i) {
4564 NSString *word([words objectAtIndex:i]);
4565 if (Package *package = [database_ packageWithName:word])
4566 [words replaceObjectAtIndex:i withObject:[package name]];
4569 [status_ setText:[words componentsJoinedByString:@" "]];
4572 - (void) _setProgressPercent:(NSNumber *)percent {
4573 [progress_ setProgress:[percent floatValue]];
4576 - (void) _addProgressOutput:(NSString *)output {
4577 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4578 CGSize size = [output_ contentSize];
4579 CGRect rect = {{0, size.height}, {size.width, 0}};
4580 [output_ scrollRectToVisible:rect animated:YES];
4583 - (BOOL) isRunning {
4590 /* Package Cell {{{ */
4591 @interface ContentView : UIView {
4592 _transient id delegate_;
4597 @interface PackageCell : UITableViewCell {
4600 NSString *description_;
4606 ContentView *content_;
4612 - (PackageCell *) init;
4613 - (void) setPackage:(Package *)package;
4615 + (int) heightForPackage:(Package *)package;
4616 - (void) drawContentRect:(CGRect)rect;
4620 @implementation ContentView
4622 - (id) initWithFrame:(CGRect)frame {
4623 if ((self = [super initWithFrame:frame]) != nil) {
4627 - (void) setDelegate:(id)delegate {
4628 delegate_ = delegate;
4631 - (void) drawRect:(CGRect)rect {
4632 [super drawRect:rect];
4633 [delegate_ drawContentRect:rect];
4638 @implementation PackageCell
4640 - (void) clearPackage {
4651 if (description_ != nil) {
4652 [description_ release];
4656 if (source_ != nil) {
4661 if (badge_ != nil) {
4666 if (placard_ != nil) {
4676 [self clearPackage];
4683 return faded_ ? [self selectionPercent] : fade_;
4686 - (PackageCell *) init {
4687 CGRect frame(CGRectMake(0, 0, 320, 74));
4688 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4689 UIView *content([self contentView]);
4690 CGRect bounds([content bounds]);
4691 content_ = [[ContentView alloc] initWithFrame:bounds];
4692 [content_ setDelegate:self];
4693 [content_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
4694 [content_ setOpaque:YES];
4695 [content addSubview:content_];
4696 if ([self respondsToSelector:@selector(selectionPercent)])
4701 - (void) _setBackgroundColor {
4703 if (NSString *mode = [package_ mode]) {
4704 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4705 color = remove ? RemovingColor_ : InstallingColor_;
4707 color = [UIColor whiteColor];
4709 [content_ setBackgroundColor:color];
4710 [self setNeedsDisplay];
4713 - (void) setPackage:(Package *)package {
4714 [self clearPackage];
4717 Source *source = [package source];
4719 icon_ = [[package icon] retain];
4720 name_ = [[package name] retain];
4721 description_ = [IsWildcat_ ? [package shortDescription] : [package longDescription] retain];
4722 commercial_ = [package isCommercial];
4724 package_ = [package retain];
4726 NSString *label = nil;
4727 bool trusted = false;
4729 if (source != nil) {
4730 label = [source label];
4731 trusted = [source trusted];
4732 } else if ([[package id] isEqualToString:@"firmware"])
4733 label = UCLocalize("APPLE");
4735 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4737 NSString *from(label);
4739 NSString *section = [package simpleSection];
4740 if (section != nil && ![section isEqualToString:label]) {
4741 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4742 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4745 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4746 source_ = [from retain];
4748 if (NSString *purpose = [package primaryPurpose])
4749 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4750 badge_ = [badge_ retain];
4752 if ([package installed] != nil)
4753 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4754 placard_ = [placard_ retain];
4756 [self _setBackgroundColor];
4757 [content_ setNeedsDisplay];
4760 - (void) drawContentRect:(CGRect)rect {
4761 bool selected([self isSelected]);
4762 float width(rect.size.width);
4765 CGContextRef context(UIGraphicsGetCurrentContext());
4766 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4767 CGContextFillRect(context, rect);
4772 rect.size = [icon_ size];
4774 rect.size.width /= 2;
4775 rect.size.height /= 2;
4777 rect.origin.x = 25 - rect.size.width / 2;
4778 rect.origin.y = 25 - rect.size.height / 2;
4780 [icon_ drawInRect:rect];
4783 if (badge_ != nil) {
4784 CGSize size = [badge_ size];
4786 [badge_ drawAtPoint:CGPointMake(
4787 36 - size.width / 2,
4788 36 - size.height / 2
4796 UISetColor(commercial_ ? Purple_ : Black_);
4797 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ ellipsis:2];
4798 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ ellipsis:2];
4801 UISetColor(commercial_ ? Purplish_ : Gray_);
4802 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ ellipsis:2];
4804 if (placard_ != nil)
4805 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4808 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4809 //[self _setBackgroundColor];
4810 [super setSelected:selected animated:fade];
4811 [content_ setNeedsDisplay];
4814 + (int) heightForPackage:(Package *)package {
4820 /* Section Cell {{{ */
4821 @interface SectionCell : UISimpleTableCell {
4827 _UISwitchSlider *switch_;
4832 - (void) setSection:(Section *)section editing:(BOOL)editing;
4836 @implementation SectionCell
4838 - (void) clearSection {
4839 if (basic_ != nil) {
4844 if (section_ != nil) {
4854 if (count_ != nil) {
4861 [self clearSection];
4868 if ((self = [super init]) != nil) {
4869 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4870 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4871 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventTouchUpInside];
4875 - (void) onSwitch:(id)sender {
4876 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4877 if (metadata == nil) {
4878 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4879 [Sections_ setObject:metadata forKey:basic_];
4883 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4886 - (void) setSection:(Section *)section editing:(BOOL)editing {
4887 if (editing != editing_) {
4889 [switch_ removeFromSuperview];
4891 [self addSubview:switch_];
4895 [self clearSection];
4897 if (section == nil) {
4898 name_ = [UCLocalize("ALL_PACKAGES") retain];
4901 basic_ = [section name];
4903 basic_ = [basic_ retain];
4905 section_ = [section localized];
4906 if (section_ != nil)
4907 section_ = [section_ retain];
4909 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4910 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4913 [switch_ setValue:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4917 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4918 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4926 float width(rect.size.width + 23);
4930 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ ellipsis:2];
4932 CGSize size = [count_ sizeWithFont:Font14_];
4936 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4938 [super drawContentInRect:rect selected:selected];
4944 /* File Table {{{ */
4945 @interface FileTable : RVPage {
4946 _transient Database *database_;
4949 NSMutableArray *files_;
4953 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4954 - (void) setPackage:(Package *)package;
4958 @implementation FileTable
4961 if (package_ != nil)
4970 - (int) numberOfRowsInTable:(UITable *)table {
4971 return files_ == nil ? 0 : [files_ count];
4974 - (float) table:(UITable *)table heightForRow:(int)row {
4978 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4979 if (reusing == nil) {
4980 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4981 UIFont *font = [UIFont systemFontOfSize:16];
4982 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4984 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4988 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4992 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4993 if ((self = [super initWithBook:book]) != nil) {
4994 database_ = database;
4996 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4998 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4999 [self addSubview:list_];
5001 UITableColumn *column = [[[UITableColumn alloc]
5002 initWithTitle:UCLocalize("NAME")
5004 width:[self frame].size.width
5007 [list_ setDataSource:self];
5008 [list_ setSeparatorStyle:1];
5009 [list_ addTableColumn:column];
5010 [list_ setDelegate:self];
5011 [list_ setReusesTableCells:YES];
5015 - (void) setPackage:(Package *)package {
5016 if (package_ != nil) {
5017 [package_ autorelease];
5026 [files_ removeAllObjects];
5028 if (package != nil) {
5029 package_ = [package retain];
5030 name_ = [[package id] retain];
5032 if (NSArray *files = [package files])
5033 [files_ addObjectsFromArray:files];
5035 if ([files_ count] != 0) {
5036 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5037 [files_ removeObjectAtIndex:0];
5038 [files_ sortUsingSelector:@selector(compareByPath:)];
5040 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5041 [stack addObject:@"/"];
5043 for (int i(0), e([files_ count]); i != e; ++i) {
5044 NSString *file = [files_ objectAtIndex:i];
5045 while (![file hasPrefix:[stack lastObject]])
5046 [stack removeLastObject];
5047 NSString *directory = [stack lastObject];
5048 [stack addObject:[file stringByAppendingString:@"/"]];
5049 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5050 ([stack count] - 2) * 3, "",
5051 [file substringFromIndex:[directory length]]
5060 - (void) resetViewAnimated:(BOOL)animated {
5061 [list_ resetViewAnimated:animated];
5064 - (void) reloadData {
5065 [self setPackage:[database_ packageWithName:name_]];
5066 [self reloadButtons];
5069 - (NSString *) title {
5070 return UCLocalize("INSTALLED_FILES");
5073 - (NSString *) backButtonTitle {
5074 return UCLocalize("FILES");
5079 /* Package View {{{ */
5080 @interface PackageView : CydiaBrowserView {
5081 _transient Database *database_;
5085 NSMutableArray *buttons_;
5088 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5089 - (void) setPackage:(Package *)package;
5093 @implementation PackageView
5096 if (package_ != nil)
5105 if ([self retainCount] == 1)
5106 [delegate_ setPackageView:self];
5110 /* XXX: this is not safe at all... localization of /fail/ */
5111 - (void) _clickButtonWithName:(NSString *)name {
5112 if ([name isEqualToString:UCLocalize("CLEAR")])
5113 [delegate_ clearPackage:package_];
5114 else if ([name isEqualToString:UCLocalize("INSTALL")])
5115 [delegate_ installPackage:package_];
5116 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5117 [delegate_ installPackage:package_];
5118 else if ([name isEqualToString:UCLocalize("REMOVE")])
5119 [delegate_ removePackage:package_];
5120 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5121 [delegate_ installPackage:package_];
5122 else _assert(false);
5125 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5126 NSString *context([sheet context]);
5128 if ([context isEqualToString:@"modify"]) {
5129 int count = [buttons_ count];
5130 _assert(count != 0);
5131 _assert(button <= count + 1);
5133 if (count != button - 1)
5134 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
5138 [super alertSheet:sheet buttonClicked:button];
5141 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5142 return [super webView:sender didFinishLoadForFrame:frame];
5145 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5146 [super webView:sender didClearWindowObject:window forFrame:frame];
5147 [window setValue:package_ forKey:@"package"];
5150 - (bool) _allowJavaScriptPanel {
5155 - (void) __rightButtonClicked {
5156 int count([buttons_ count]);
5161 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5163 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
5164 [buttons addObjectsFromArray:buttons_];
5165 [buttons addObject:UCLocalize("CANCEL")];
5167 [delegate_ slideUp:[[[UIActionSheet alloc]
5170 defaultButtonIndex:([buttons count] - 1)
5177 - (void) _rightButtonClicked {
5179 [super _rightButtonClicked];
5181 [self __rightButtonClicked];
5185 - (id) _rightButtonTitle {
5186 int count = [buttons_ count];
5187 return count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0];
5190 - (NSString *) backButtonTitle {
5194 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5195 if ((self = [super initWithBook:book]) != nil) {
5196 database_ = database;
5197 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5198 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5202 - (void) setPackage:(Package *)package {
5203 if (package_ != nil) {
5204 [package_ autorelease];
5213 [buttons_ removeAllObjects];
5215 if (package != nil) {
5218 package_ = [package retain];
5219 name_ = [[package id] retain];
5220 commercial_ = [package isCommercial];
5222 if ([package_ mode] != nil)
5223 [buttons_ addObject:UCLocalize("CLEAR")];
5224 if ([package_ source] == nil);
5225 else if ([package_ upgradableAndEssential:NO])
5226 [buttons_ addObject:UCLocalize("UPGRADE")];
5227 else if ([package_ uninstalled])
5228 [buttons_ addObject:UCLocalize("INSTALL")];
5230 [buttons_ addObject:UCLocalize("REINSTALL")];
5231 if (![package_ uninstalled])
5232 [buttons_ addObject:UCLocalize("REMOVE")];
5234 if (special_ != NULL) {
5235 CGRect frame([webview_ frame]);
5236 frame.size.width = 320;
5237 frame.size.height = 0;
5238 [webview_ setFrame:frame];
5240 if ([scroller_ respondsToSelector:@selector(scrollPointVisibleAtTopLeft:)])
5241 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5243 [scroller_ scrollRectToVisible:CGRectZero animated:NO];
5246 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5248 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5250 [self setFinishHook:nil];
5251 [self setPopupHook:nil];
5254 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5255 [super callFunction:special_];
5259 [self reloadButtons];
5262 - (bool) isLoading {
5263 return commercial_ ? [super isLoading] : false;
5266 - (void) reloadData {
5267 [self setPackage:[database_ packageWithName:name_]];
5272 /* Package Table {{{ */
5273 @interface PackageTable : RVPage {
5274 _transient Database *database_;
5276 NSMutableArray *packages_;
5277 NSMutableArray *sections_;
5279 NSMutableArray *index_;
5280 NSMutableDictionary *indices_;
5283 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5285 - (void) setDelegate:(id)delegate;
5287 - (void) reloadData;
5288 - (void) resetCursor;
5290 - (UITableView *) list;
5292 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5296 @implementation PackageTable
5299 [list_ setDataSource:nil];
5302 [packages_ release];
5303 [sections_ release];
5310 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5311 NSInteger count([sections_ count]);
5312 return count == 0 ? 1 : count;
5315 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5316 if ([sections_ count] == 0)
5318 return [[sections_ objectAtIndex:section] name];
5321 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5322 if ([sections_ count] == 0)
5324 return [[sections_ objectAtIndex:section] count];
5327 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5328 Section *section([sections_ objectAtIndex:[path section]]);
5329 NSInteger row([path row]);
5330 Package *package([packages_ objectAtIndex:([section row] + row)]);
5334 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5335 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
5337 cell = [[[PackageCell alloc] init] autorelease];
5338 [cell setPackage:[self packageAtIndexPath:path]];
5342 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5344 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5347 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5348 Package *package([self packageAtIndexPath:path]);
5349 package = [database_ packageWithName:[package id]];
5350 PackageView *view([delegate_ packageView]);
5351 [view setPackage:package];
5352 [view setDelegate:delegate_];
5353 [book_ pushPage:view];
5357 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5358 return [packages_ count] > 20 ? index_ : nil;
5361 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5365 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5366 if ((self = [super initWithBook:book]) != nil) {
5367 database_ = database;
5368 title_ = [title retain];
5370 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5371 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5373 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5374 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5376 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5377 [list_ setDataSource:self];
5378 [list_ setDelegate:self];
5380 [self addSubview:list_];
5382 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5383 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5387 - (void) setDelegate:(id)delegate {
5388 delegate_ = delegate;
5391 - (bool) hasPackage:(Package *)package {
5395 - (void) reloadData {
5396 NSArray *packages = [database_ packages];
5398 [packages_ removeAllObjects];
5399 [sections_ removeAllObjects];
5401 _profile(PackageTable$reloadData$Filter)
5402 for (Package *package in packages)
5403 if ([self hasPackage:package])
5404 [packages_ addObject:package];
5407 [index_ removeAllObjects];
5408 [indices_ removeAllObjects];
5410 Section *section = nil;
5412 _profile(PackageTable$reloadData$Section)
5413 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5417 _profile(PackageTable$reloadData$Section$Package)
5418 package = [packages_ objectAtIndex:offset];
5419 index = [package index];
5422 if (section == nil || [section index] != index) {
5423 _profile(PackageTable$reloadData$Section$Allocate)
5424 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5427 [index_ addObject:[section name]];
5428 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5430 _profile(PackageTable$reloadData$Section$Add)
5431 [sections_ addObject:section];
5435 [section addToCount];
5439 _profile(PackageTable$reloadData$List)
5444 - (NSString *) title {
5448 - (void) resetViewAnimated:(BOOL)animated {
5449 [list_ resetViewAnimated:animated];
5452 - (void) resetCursor {
5453 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5456 - (UITableView *) list {
5460 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5461 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5466 /* Filtered Package Table {{{ */
5467 @interface FilteredPackageTable : PackageTable {
5473 - (void) setObject:(id)object;
5474 - (void) setObject:(id)object forFilter:(SEL)filter;
5476 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5480 @implementation FilteredPackageTable
5488 - (void) setFilter:(SEL)filter {
5491 /* XXX: this is an unsafe optimization of doomy hell */
5492 Method method(class_getInstanceMethod([Package class], filter));
5493 _assert(method != NULL);
5494 imp_ = method_getImplementation(method);
5495 _assert(imp_ != NULL);
5498 - (void) setObject:(id)object {
5504 object_ = [object retain];
5507 - (void) setObject:(id)object forFilter:(SEL)filter {
5508 [self setFilter:filter];
5509 [self setObject:object];
5513 - (bool) hasPackage:(Package *)package {
5514 _profile(FilteredPackageTable$hasPackage)
5515 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5519 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5520 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5521 [self setFilter:filter];
5522 object_ = object == nil ? nil : [object retain];
5530 /* Add Source View {{{ */
5531 @interface AddSourceView : RVPage {
5532 _transient Database *database_;
5535 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5539 @implementation AddSourceView
5541 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5542 if ((self = [super initWithBook:book]) != nil) {
5543 database_ = database;
5549 /* Source Cell {{{ */
5550 @interface SourceCell : UITableCell {
5553 NSString *description_;
5559 - (SourceCell *) initWithSource:(Source *)source;
5563 @implementation SourceCell
5568 [description_ release];
5573 - (SourceCell *) initWithSource:(Source *)source {
5574 if ((self = [super init]) != nil) {
5576 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5578 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5579 icon_ = [icon_ retain];
5581 origin_ = [[source name] retain];
5582 label_ = [[source uri] retain];
5583 description_ = [[source description] retain];
5587 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5588 float width(rect.size.width);
5591 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5598 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ ellipsis:2];
5602 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ ellipsis:2];
5606 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ ellipsis:2];
5608 [super drawContentInRect:rect selected:selected];
5613 /* Source Table {{{ */
5614 @interface SourceTable : RVPage {
5615 _transient Database *database_;
5616 UISectionList *list_;
5617 NSMutableArray *sources_;
5618 UIActionSheet *alert_;
5622 UIProgressHUD *hud_;
5625 //NSURLConnection *installer_;
5626 NSURLConnection *trivial_;
5627 NSURLConnection *trivial_bz2_;
5628 NSURLConnection *trivial_gz_;
5629 //NSURLConnection *automatic_;
5634 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5638 @implementation SourceTable
5640 - (void) _deallocConnection:(NSURLConnection *)connection {
5641 if (connection != nil) {
5642 [connection cancel];
5643 //[connection setDelegate:nil];
5644 [connection release];
5649 [[list_ table] setDelegate:nil];
5650 [list_ setDataSource:nil];
5659 //[self _deallocConnection:installer_];
5660 [self _deallocConnection:trivial_];
5661 [self _deallocConnection:trivial_gz_];
5662 [self _deallocConnection:trivial_bz2_];
5663 //[self _deallocConnection:automatic_];
5670 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5671 return offset_ == 0 ? 1 : 2;
5674 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5675 switch (section + (offset_ == 0 ? 1 : 0)) {
5676 case 0: return UCLocalize("ENTERED_BY_USER");
5677 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5683 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5684 switch (section + (offset_ == 0 ? 1 : 0)) {
5686 case 1: return offset_;
5692 - (int) numberOfRowsInTable:(UITable *)table {
5693 return [sources_ count];
5696 - (float) table:(UITable *)table heightForRow:(int)row {
5697 Source *source = [sources_ objectAtIndex:row];
5698 return [source description] == nil ? 56 : 73;
5701 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5702 Source *source = [sources_ objectAtIndex:row];
5703 // XXX: weird warning, stupid selectors ;P
5704 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5707 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5711 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5715 - (void) tableRowSelected:(NSNotification*)notification {
5716 UITable *table([list_ table]);
5717 int row([table selectedRow]);
5721 Source *source = [sources_ objectAtIndex:row];
5723 PackageTable *packages = [[[FilteredPackageTable alloc]
5726 title:[source label]
5727 filter:@selector(isVisibleInSource:)
5731 [packages setDelegate:delegate_];
5733 [book_ pushPage:packages];
5736 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5737 Source *source = [sources_ objectAtIndex:row];
5738 return [source record] != nil;
5741 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5742 [[list_ table] setDeleteConfirmationRow:row];
5745 - (void) table:(UITable *)table deleteRow:(int)row {
5746 Source *source = [sources_ objectAtIndex:row];
5747 [Sources_ removeObjectForKey:[source key]];
5748 [delegate_ syncData];
5752 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5755 @"./", @"Distribution",
5756 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5758 [delegate_ syncData];
5761 - (NSString *) getWarning {
5762 NSString *href(href_);
5763 NSRange colon([href rangeOfString:@"://"]);
5764 if (colon.location != NSNotFound)
5765 href = [href substringFromIndex:(colon.location + 3)];
5766 href = [href stringByAddingPercentEscapes];
5767 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5768 href = [href stringByCachingURLWithCurrentCDN];
5770 NSURL *url([NSURL URLWithString:href]);
5772 NSStringEncoding encoding;
5773 NSError *error(nil);
5775 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5776 return [warning length] == 0 ? nil : warning;
5780 - (void) _endConnection:(NSURLConnection *)connection {
5781 NSURLConnection **field = NULL;
5782 if (connection == trivial_)
5784 else if (connection == trivial_bz2_)
5785 field = &trivial_bz2_;
5786 else if (connection == trivial_gz_)
5787 field = &trivial_gz_;
5788 _assert(field != NULL);
5789 [connection release];
5794 trivial_bz2_ == nil &&
5800 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5803 UIActionSheet *sheet = [[[UIActionSheet alloc]
5804 initWithTitle:UCLocalize("SOURCE_WARNING")
5805 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_ANYWAY"), UCLocalize("CANCEL"), nil]
5806 defaultButtonIndex:0
5811 [sheet setNumberOfRows:1];
5813 [sheet setBodyText:warning];
5814 [sheet popupAlertAnimated:YES];
5817 } else if (error_ != nil) {
5818 UIActionSheet *sheet = [[[UIActionSheet alloc]
5819 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5820 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5821 defaultButtonIndex:0
5826 [sheet setBodyText:[error_ localizedDescription]];
5827 [sheet popupAlertAnimated:YES];
5829 UIActionSheet *sheet = [[[UIActionSheet alloc]
5830 initWithTitle:UCLocalize("NOT_REPOSITORY")
5831 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5832 defaultButtonIndex:0
5837 [sheet setBodyText:UCLocalize("NOT_REPOSITORY_EX")];
5838 [sheet popupAlertAnimated:YES];
5841 [delegate_ setStatusBarShowsProgress:NO];
5842 [delegate_ removeProgressHUD:hud_];
5852 if (error_ != nil) {
5859 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5860 switch ([response statusCode]) {
5866 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5867 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5869 error_ = [error retain];
5870 [self _endConnection:connection];
5873 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5874 [self _endConnection:connection];
5877 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5878 NSMutableURLRequest *request = [NSMutableURLRequest
5879 requestWithURL:[NSURL URLWithString:href]
5880 cachePolicy:NSURLRequestUseProtocolCachePolicy
5881 timeoutInterval:20.0
5884 [request setHTTPMethod:method];
5886 if (Machine_ != NULL)
5887 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5889 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
5891 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5893 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5896 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5897 NSString *context([sheet context]);
5899 if ([context isEqualToString:@"source"]) {
5902 NSString *href = [[sheet textField] text];
5904 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5906 if (![href hasSuffix:@"/"])
5907 href_ = [href stringByAppendingString:@"/"];
5910 href_ = [href_ retain];
5912 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
5913 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5914 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5915 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5919 hud_ = [[delegate_ addProgressHUD] retain];
5920 [hud_ setText:UCLocalize("VERIFYING_URL")];
5930 } else if ([context isEqualToString:@"trivial"])
5932 else if ([context isEqualToString:@"urlerror"])
5934 else if ([context isEqualToString:@"warning"]) {
5953 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5954 if ((self = [super initWithBook:book]) != nil) {
5955 database_ = database;
5956 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5958 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5959 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5960 [list_ setShouldHideHeaderInShortLists:NO];
5962 [self addSubview:list_];
5963 [list_ setDataSource:self];
5965 UITableColumn *column = [[UITableColumn alloc]
5966 initWithTitle:UCLocalize("NAME")
5968 width:[self frame].size.width
5971 UITable *table = [list_ table];
5972 [table setSeparatorStyle:1];
5973 [table addTableColumn:column];
5974 [table setDelegate:self];
5978 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5979 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5983 - (void) reloadData {
5985 if (!list.ReadMainList())
5988 [sources_ removeAllObjects];
5989 [sources_ addObjectsFromArray:[database_ sources]];
5991 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5994 int count([sources_ count]);
5995 for (offset_ = 0; offset_ != count; ++offset_) {
5996 Source *source = [sources_ objectAtIndex:offset_];
5997 if ([source record] == nil)
6004 - (void) resetViewAnimated:(BOOL)animated {
6005 [list_ resetViewAnimated:animated];
6008 - (void) _leftButtonClicked {
6009 /*[book_ pushPage:[[[AddSourceView alloc]
6014 UIActionSheet *sheet = [[[UIActionSheet alloc]
6015 initWithTitle:UCLocalize("ENTER_APT_URL")
6016 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_SOURCE"), UCLocalize("CANCEL"), nil]
6017 defaultButtonIndex:0
6022 [sheet setNumberOfRows:1];
6024 [sheet addTextFieldWithValue:@"http://" label:@""];
6026 UITextInputTraits *traits = [[sheet textField] textInputTraits];
6027 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6028 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6029 [traits setKeyboardType:UIKeyboardTypeURL];
6030 // XXX: UIReturnKeyDone
6031 [traits setReturnKeyType:UIReturnKeyNext];
6033 [sheet popupAlertAnimated:YES];
6036 - (void) _rightButtonClicked {
6037 UITable *table = [list_ table];
6038 BOOL editing = [table isRowDeletionEnabled];
6039 [table enableRowDeletion:!editing animated:YES];
6040 [book_ reloadButtonsForPage:self];
6043 - (NSString *) title {
6044 return UCLocalize("SOURCES");
6047 - (NSString *) leftButtonTitle {
6048 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("ADD") : nil;
6051 - (id) rightButtonTitle {
6052 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("DONE") : UCLocalize("EDIT");
6055 - (UINavigationButtonStyle) rightButtonStyle {
6056 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6062 /* Installed View {{{ */
6063 @interface InstalledView : RVPage {
6064 _transient Database *database_;
6065 FilteredPackageTable *packages_;
6069 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6073 @implementation InstalledView
6076 [packages_ release];
6080 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6081 if ((self = [super initWithBook:book]) != nil) {
6082 database_ = database;
6084 packages_ = [[FilteredPackageTable alloc]
6088 filter:@selector(isInstalledAndVisible:)
6089 with:[NSNumber numberWithBool:YES]
6092 [self addSubview:packages_];
6094 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6095 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6099 - (void) resetViewAnimated:(BOOL)animated {
6100 [packages_ resetViewAnimated:animated];
6103 - (void) reloadData {
6104 [packages_ reloadData];
6107 - (void) _rightButtonClicked {
6108 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6109 [packages_ reloadData];
6111 [book_ reloadButtonsForPage:self];
6114 - (NSString *) title {
6115 return UCLocalize("INSTALLED");
6118 - (NSString *) backButtonTitle {
6119 return UCLocalize("PACKAGES");
6122 - (id) rightButtonTitle {
6123 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE");
6126 - (UINavigationButtonStyle) rightButtonStyle {
6127 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6130 - (void) setDelegate:(id)delegate {
6131 [super setDelegate:delegate];
6132 [packages_ setDelegate:delegate];
6139 @interface HomeView : CydiaBrowserView {
6144 @implementation HomeView
6146 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
6147 if (NSString *token = [headers objectForKey:@"X-Cydia-Token"]) {
6150 Token_ = [token retain];
6154 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6155 NSString *context([sheet context]);
6157 if ([context isEqualToString:@"about"])
6160 [super alertSheet:sheet buttonClicked:button];
6163 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6164 [super _setMoreHeaders:request];
6166 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6167 if (UniqueID_ != nil)
6168 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6171 - (void) _leftButtonClicked {
6172 UIActionSheet *sheet = [[[UIActionSheet alloc]
6173 initWithTitle:UCLocalize("ABOUT_CYDIA")
6174 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
6175 defaultButtonIndex:0
6181 @"Copyright (C) 2008-2009\n"
6182 "Jay Freeman (saurik)\n"
6183 "saurik@saurik.com\n"
6184 "http://www.saurik.com/\n"
6187 "http://www.theokorigroup.com/\n"
6189 "College of Creative Studies,\n"
6190 "University of California,\n"
6192 "http://www.ccs.ucsb.edu/"
6195 [sheet popupAlertAnimated:YES];
6198 - (NSString *) leftButtonTitle {
6199 return UCLocalize("ABOUT");
6204 /* Manage View {{{ */
6205 @interface ManageView : CydiaBrowserView {
6210 @implementation ManageView
6212 - (NSString *) title {
6213 return UCLocalize("MANAGE");
6216 - (void) _leftButtonClicked {
6217 [delegate_ askForSettings];
6218 [delegate_ updateData];
6221 - (NSString *) leftButtonTitle {
6222 return UCLocalize("SETTINGS");
6226 - (id) _rightButtonTitle {
6227 return Queuing_ ? UCLocalize("QUEUE") : nil;
6230 - (UINavigationButtonStyle) rightButtonStyle {
6231 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6234 - (void) _rightButtonClicked {
6239 - (bool) isLoading {
6246 /* Cydia Book {{{ */
6247 @interface CYBook : RVBook <
6250 _transient Database *database_;
6251 UINavigationBar *overlay_;
6252 UINavigationBar *underlay_;
6253 UIProgressIndicator *indicator_;
6254 UITextLabel *prompt_;
6255 UIProgressBar *progress_;
6256 UINavigationButton *cancel_;
6261 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
6264 - (void) setUpdate:(NSDate *)date;
6268 @implementation CYBook
6272 [indicator_ release];
6274 [progress_ release];
6279 - (NSString *) getTitleForPage:(RVPage *)page {
6280 return [super getTitleForPage:page];
6292 [UIView beginAnimations:nil context:NULL];
6294 CGRect ovrframe = [overlay_ frame];
6295 ovrframe.origin.y = 0;
6296 [overlay_ setFrame:ovrframe];
6298 CGRect barframe = [navbar_ frame];
6299 barframe.origin.y += ovrframe.size.height;
6300 [navbar_ setFrame:barframe];
6302 CGRect trnframe = [transition_ frame];
6303 trnframe.origin.y += ovrframe.size.height;
6304 trnframe.size.height -= ovrframe.size.height;
6305 [transition_ setFrame:trnframe];
6307 [UIView endAnimations];
6315 [UIView beginAnimations:nil context:NULL];
6317 CGRect ovrframe = [overlay_ frame];
6318 ovrframe.origin.y = -ovrframe.size.height;
6319 [overlay_ setFrame:ovrframe];
6321 CGRect barframe = [navbar_ frame];
6322 barframe.origin.y -= ovrframe.size.height;
6323 [navbar_ setFrame:barframe];
6325 CGRect trnframe = [transition_ frame];
6326 trnframe.origin.y -= ovrframe.size.height;
6327 trnframe.size.height += ovrframe.size.height;
6328 [transition_ setFrame:trnframe];
6330 [UIView commitAnimations];
6333 - (void) setUpdate:(NSDate *)date {
6340 [indicator_ startAnimation];
6341 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6342 [progress_ setProgress:0];
6345 [overlay_ addSubview:cancel_];
6348 detachNewThreadSelector:@selector(_update)
6354 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6355 NSString *context([sheet context]);
6357 if ([context isEqualToString:@"refresh"])
6364 [indicator_ stopAnimation];
6368 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6371 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6372 if ((self = [super initWithFrame:frame]) != nil) {
6373 database_ = database;
6375 CGRect ovrrect([navbar_ bounds]);
6376 ovrrect.size.height = [UINavigationBar defaultSize].height;
6377 ovrrect.origin.y = -ovrrect.size.height;
6379 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6380 [self addSubview:overlay_];
6382 ovrrect.origin.y = frame.size.height;
6383 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6384 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6385 [self addSubview:underlay_];
6387 [overlay_ setBarStyle:1];
6388 [underlay_ setBarStyle:1];
6390 int barstyle([overlay_ _barStyle:NO]);
6391 bool ugly(barstyle == 0);
6393 UIProgressIndicatorStyle style = ugly ?
6394 UIProgressIndicatorStyleMediumBrown :
6395 UIProgressIndicatorStyleMediumWhite;
6397 CGSize indsize([UIProgressIndicator defaultSizeForStyle:style]);
6398 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6399 CGRect indrect = {{indoffset, indoffset}, indsize};
6401 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6402 [indicator_ setStyle:style];
6403 [overlay_ addSubview:indicator_];
6405 CGSize prmsize = {215, indsize.height + 4};
6408 indoffset * 2 + indsize.width,
6409 unsigned(ovrrect.size.height - prmsize.height) / 2 - 1
6412 UIFont *font([UIFont systemFontOfSize:15]);
6414 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6416 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6417 [prompt_ setBackgroundColor:[UIColor clearColor]];
6418 [prompt_ setFont:font];
6420 [overlay_ addSubview:prompt_];
6422 CGSize prgsize = {75, 100};
6425 ovrrect.size.width - prgsize.width - 10,
6426 (ovrrect.size.height - prgsize.height) / 2
6429 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6430 [progress_ setStyle:0];
6431 [overlay_ addSubview:progress_];
6433 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6434 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6436 CGRect frame = [cancel_ frame];
6437 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6438 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6439 [cancel_ setFrame:frame];
6441 [cancel_ setBarStyle:barstyle];
6445 - (void) _onCancel {
6447 [cancel_ removeFromSuperview];
6450 - (void) _update { _pooled
6452 status.setDelegate(self);
6453 [database_ updateWithStatus:status];
6456 performSelectorOnMainThread:@selector(_update_)
6462 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6463 [prompt_ setText:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6467 UIActionSheet *sheet = [[[UIActionSheet alloc]
6468 initWithTitle:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), UCLocalize("REFRESH")]
6469 buttons:[NSArray arrayWithObjects:
6472 defaultButtonIndex:0
6477 [sheet setBodyText:error];
6478 [sheet popupAlertAnimated:YES];
6480 [self reloadButtons];
6483 - (void) setProgressTitle:(NSString *)title {
6485 performSelectorOnMainThread:@selector(_setProgressTitle:)
6491 - (void) setProgressPercent:(float)percent {
6493 performSelectorOnMainThread:@selector(_setProgressPercent:)
6494 withObject:[NSNumber numberWithFloat:percent]
6499 - (void) startProgress {
6502 - (void) addProgressOutput:(NSString *)output {
6504 performSelectorOnMainThread:@selector(_addProgressOutput:)
6510 - (bool) isCancelling:(size_t)received {
6514 - (void) _setProgressTitle:(NSString *)title {
6515 [prompt_ setText:title];
6518 - (void) _setProgressPercent:(NSNumber *)percent {
6519 [progress_ setProgress:[percent floatValue]];
6522 - (void) _addProgressOutput:(NSString *)output {
6527 /* Cydia:// Protocol {{{ */
6528 @interface CydiaURLProtocol : NSURLProtocol {
6533 @implementation CydiaURLProtocol
6535 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6536 NSURL *url([request URL]);
6539 NSString *scheme([[url scheme] lowercaseString]);
6540 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6545 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6549 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6550 id<NSURLProtocolClient> client([self client]);
6552 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6554 NSData *data(UIImagePNGRepresentation(icon));
6556 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6557 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6558 [client URLProtocol:self didLoadData:data];
6559 [client URLProtocolDidFinishLoading:self];
6563 - (void) startLoading {
6564 id<NSURLProtocolClient> client([self client]);
6565 NSURLRequest *request([self request]);
6567 NSURL *url([request URL]);
6568 NSString *href([url absoluteString]);
6570 NSString *path([href substringFromIndex:8]);
6571 NSRange slash([path rangeOfString:@"/"]);
6574 if (slash.location == NSNotFound) {
6578 command = [path substringToIndex:slash.location];
6579 path = [path substringFromIndex:(slash.location + 1)];
6582 Database *database([Database sharedInstance]);
6584 if ([command isEqualToString:@"package-icon"]) {
6587 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6588 Package *package([database packageWithName:path]);
6591 UIImage *icon([package icon]);
6592 [self _returnPNGWithImage:icon forRequest:request];
6593 } else if ([command isEqualToString:@"source-icon"]) {
6596 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6597 NSString *source(Simplify(path));
6598 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6600 icon = [UIImage applicationImageNamed:@"unknown.png"];
6601 [self _returnPNGWithImage:icon forRequest:request];
6602 } else if ([command isEqualToString:@"uikit-image"]) {
6605 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6606 UIImage *icon(_UIImageWithName(path));
6607 [self _returnPNGWithImage:icon forRequest:request];
6608 } else if ([command isEqualToString:@"section-icon"]) {
6611 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6612 NSString *section(Simplify(path));
6613 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6615 icon = [UIImage applicationImageNamed:@"unknown.png"];
6616 [self _returnPNGWithImage:icon forRequest:request];
6618 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6622 - (void) stopLoading {
6628 /* Sections View {{{ */
6629 @interface SectionsView : RVPage {
6630 _transient Database *database_;
6631 NSMutableArray *sections_;
6632 NSMutableArray *filtered_;
6633 UITransitionView *transition_;
6639 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6640 - (void) reloadData;
6645 @implementation SectionsView
6648 [list_ setDataSource:nil];
6649 [list_ setDelegate:nil];
6651 [sections_ release];
6652 [filtered_ release];
6653 [transition_ release];
6655 [accessory_ release];
6659 - (int) numberOfRowsInTable:(UITable *)table {
6660 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6663 - (float) table:(UITable *)table heightForRow:(int)row {
6667 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6669 reusing = [[[SectionCell alloc] init] autorelease];
6670 [(SectionCell *)reusing setSection:(editing_ ?
6671 [sections_ objectAtIndex:row] :
6672 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6673 ) editing:editing_];
6677 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6681 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6685 - (void) tableRowSelected:(NSNotification *)notification {
6686 int row = [[notification object] selectedRow];
6697 title = UCLocalize("ALL_PACKAGES");
6699 section = [filtered_ objectAtIndex:(row - 1)];
6700 name = [section name];
6703 name = [NSString stringWithString:name];
6704 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6707 title = UCLocalize("NO_SECTION");
6711 PackageTable *table = [[[FilteredPackageTable alloc]
6715 filter:@selector(isVisibleInSection:)
6719 [table setDelegate:delegate_];
6721 [book_ pushPage:table];
6724 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6725 if ((self = [super initWithBook:book]) != nil) {
6726 database_ = database;
6728 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6729 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6731 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6732 [self addSubview:transition_];
6734 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6735 [transition_ transition:0 toView:list_];
6737 UITableColumn *column = [[[UITableColumn alloc]
6738 initWithTitle:UCLocalize("NAME")
6740 width:[self frame].size.width
6743 [list_ setDataSource:self];
6744 [list_ setSeparatorStyle:1];
6745 [list_ addTableColumn:column];
6746 [list_ setDelegate:self];
6747 [list_ setReusesTableCells:YES];
6751 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6752 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6756 - (void) reloadData {
6757 NSArray *packages = [database_ packages];
6759 [sections_ removeAllObjects];
6760 [filtered_ removeAllObjects];
6763 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6764 SectionMap sections;
6765 sections.resize(64);
6767 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6771 for (Package *package in packages) {
6772 NSString *name([package section]);
6773 NSString *key(name == nil ? @"" : name);
6778 _profile(SectionsView$reloadData$Section)
6779 section = §ions[key];
6780 if (*section == nil) {
6781 _profile(SectionsView$reloadData$Section$Allocate)
6782 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6787 [*section addToCount];
6789 _profile(SectionsView$reloadData$Filter)
6790 if (![package valid] || ![package visible])
6794 [*section addToRow];
6798 _profile(SectionsView$reloadData$Section)
6799 section = [sections objectForKey:key];
6800 if (section == nil) {
6801 _profile(SectionsView$reloadData$Section$Allocate)
6802 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6803 [sections setObject:section forKey:key];
6808 [section addToCount];
6810 _profile(SectionsView$reloadData$Filter)
6811 if (![package valid] || ![package visible])
6821 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6822 [sections_ addObject:i->second];
6824 [sections_ addObjectsFromArray:[sections allValues]];
6827 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6829 for (Section *section in sections_) {
6830 size_t count([section row]);
6834 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6835 [section setCount:count];
6836 [filtered_ addObject:section];
6843 - (void) resetView {
6845 [self _rightButtonClicked];
6848 - (void) resetViewAnimated:(BOOL)animated {
6849 [list_ resetViewAnimated:animated];
6852 - (void) _rightButtonClicked {
6853 if ((editing_ = !editing_))
6856 [delegate_ updateData];
6857 [book_ reloadTitleForPage:self];
6858 [book_ reloadButtonsForPage:self];
6861 - (NSString *) title {
6862 return editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS");
6865 - (NSString *) backButtonTitle {
6866 return UCLocalize("SECTIONS");
6869 - (id) rightButtonTitle {
6870 return [sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT");
6873 - (UINavigationButtonStyle) rightButtonStyle {
6874 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6877 - (UIView *) accessoryView {
6883 /* Changes View {{{ */
6884 @interface ChangesView : RVPage {
6885 _transient Database *database_;
6886 NSMutableArray *packages_;
6887 NSMutableArray *sections_;
6892 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6893 - (void) reloadData;
6897 @implementation ChangesView
6900 [list_ setDelegate:nil];
6901 [list_ setDataSource:nil];
6903 [packages_ release];
6904 [sections_ release];
6909 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6910 NSInteger count([sections_ count]);
6911 return count == 0 ? 1 : count;
6914 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6915 if ([sections_ count] == 0)
6917 return [[sections_ objectAtIndex:section] name];
6920 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6921 if ([sections_ count] == 0)
6923 return [[sections_ objectAtIndex:section] count];
6926 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6927 Section *section([sections_ objectAtIndex:[path section]]);
6928 NSInteger row([path row]);
6929 return [packages_ objectAtIndex:([section row] + row)];
6932 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6933 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
6935 cell = [[[PackageCell alloc] init] autorelease];
6936 [cell setPackage:[self packageAtIndexPath:path]];
6940 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6942 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6945 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6946 Package *package([self packageAtIndexPath:path]);
6947 PackageView *view([delegate_ packageView]);
6948 [view setDelegate:delegate_];
6949 [view setPackage:package];
6950 [book_ pushPage:view];
6954 - (void) _leftButtonClicked {
6955 [(CYBook *)book_ update];
6956 [self reloadButtons];
6959 - (void) _rightButtonClicked {
6960 [delegate_ distUpgrade];
6963 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6964 if ((self = [super initWithBook:book]) != nil) {
6965 database_ = database;
6967 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6968 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6970 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
6971 [self addSubview:list_];
6973 //XXX:[list_ setShouldHideHeaderInShortLists:NO];
6974 [list_ setDataSource:self];
6975 [list_ setDelegate:self];
6976 //[list_ setSectionListStyle:1];
6980 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6981 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6985 - (void) reloadData {
6986 NSArray *packages = [database_ packages];
6988 [packages_ removeAllObjects];
6989 [sections_ removeAllObjects];
6992 for (Package *package in packages)
6994 [package uninstalled] && [package valid] && [package visible] ||
6995 [package upgradableAndEssential:YES]
6997 [packages_ addObject:package];
7000 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7003 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7004 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7005 Section *section = nil;
7009 bool unseens = false;
7011 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7013 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7014 Package *package = [packages_ objectAtIndex:offset];
7016 BOOL uae = [package upgradableAndEssential:YES];
7022 _profile(ChangesView$reloadData$Remember)
7023 seen = [package seen];
7026 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7031 name = UCLocalize("UNKNOWN");
7033 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7037 _profile(ChangesView$reloadData$Allocate)
7038 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7039 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7040 [sections_ addObject:section];
7044 [section addToCount];
7045 } else if ([package ignored])
7046 [ignored addToCount];
7049 [upgradable addToCount];
7054 CFRelease(formatter);
7057 Section *last = [sections_ lastObject];
7058 size_t count = [last count];
7059 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7060 [sections_ removeLastObject];
7063 if ([ignored count] != 0)
7064 [sections_ insertObject:ignored atIndex:0];
7066 [sections_ insertObject:upgradable atIndex:0];
7069 [self reloadButtons];
7072 - (void) resetViewAnimated:(BOOL)animated {
7073 [list_ resetViewAnimated:animated];
7076 - (NSString *) leftButtonTitle {
7077 return [(CYBook *)book_ updating] ? nil : UCLocalize("REFRESH");
7080 - (id) rightButtonTitle {
7081 return upgrades_ == 0 ? nil : [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
7084 - (NSString *) title {
7085 return UCLocalize("CHANGES");
7090 /* Search View {{{ */
7091 @protocol SearchViewDelegate
7092 - (void) showKeyboard:(BOOL)show;
7095 @interface SearchView : RVPage {
7097 UISearchField *field_;
7098 FilteredPackageTable *table_;
7103 - (id) initWithBook:(RVBook *)book database:(Database *)database;
7104 - (void) reloadData;
7108 @implementation SearchView
7111 [field_ setDelegate:nil];
7113 [accessory_ release];
7120 - (void) _showKeyboard:(BOOL)show {
7121 CGSize keysize = [UIKeyboard defaultSize];
7122 CGRect keydown = [book_ pageBounds];
7123 CGRect keyup = keydown;
7124 keyup.size.height -= keysize.height - ButtonBarHeight_;
7126 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
7128 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
7129 [animation setSignificantRectFields:8];
7132 [animation setStartFrame:keydown];
7133 [animation setEndFrame:keyup];
7135 [animation setStartFrame:keyup];
7136 [animation setEndFrame:keydown];
7139 UIAnimator *animator = [UIAnimator sharedAnimator];
7142 addAnimations:[NSArray arrayWithObjects:animation, nil]
7143 withDuration:(KeyboardTime_ - delay)
7148 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
7150 //[delegate_ showKeyboard:show];
7153 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
7154 [self _showKeyboard:YES];
7155 [table_ setObject:[field_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7159 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
7160 [self _showKeyboard:NO];
7161 [table_ setObject:[field_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7165 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
7167 NSString *text([field_ text]);
7168 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
7169 [table_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7175 - (void) textFieldClearButtonPressed:(UITextField *)field {
7179 - (void) keyboardInputShouldDelete:(id)input {
7183 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
7184 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
7188 [field_ resignFirstResponder];
7193 - (id) initWithBook:(RVBook *)book database:(Database *)database {
7194 if ((self = [super initWithBook:book]) != nil) {
7195 CGRect pageBounds = [book_ pageBounds];
7197 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
7198 CGColor dimmed(space_, 0, 0, 0, 0.5);
7199 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
7201 table_ = [[FilteredPackageTable alloc]
7205 filter:@selector(isUnfilteredAndSearchedForBy:)
7209 [table_ setShouldHideHeaderInShortLists:NO];
7210 [self addSubview:table_];
7212 CGRect cnfrect = {{7, 38}, {17, 18}};
7219 area.size.width = [self bounds].size.width - area.origin.x * 2;
7220 area.size.height = [UISearchField defaultHeight];
7222 field_ = [[UISearchField alloc] initWithFrame:area];
7224 UIFont *font = [UIFont systemFontOfSize:16];
7225 [field_ setFont:font];
7227 [field_ setPlaceholder:UCLocalize("SEARCH_EX")];
7228 [field_ setDelegate:self];
7230 [field_ setPaddingTop:5];
7232 UITextInputTraits *traits([field_ textInputTraits]);
7233 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7234 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7235 [traits setReturnKeyType:UIReturnKeySearch];
7237 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
7239 accessory_ = [[UIView alloc] initWithFrame:accrect];
7240 [accessory_ addSubview:field_];
7242 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7243 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7247 - (void) resetViewAnimated:(BOOL)animated {
7248 [table_ resetViewAnimated:animated];
7251 - (void) _reloadData {
7254 - (void) reloadData {
7255 _profile(SearchView$reloadData)
7256 [table_ reloadData];
7259 [table_ resetCursor];
7262 - (UIView *) accessoryView {
7266 - (NSString *) title {
7270 - (NSString *) backButtonTitle {
7271 return UCLocalize("SEARCH");
7274 - (void) setDelegate:(id)delegate {
7275 [table_ setDelegate:delegate];
7276 [super setDelegate:delegate];
7281 /* Settings View {{{ */
7282 @interface SettingsView : RVPage {
7283 _transient Database *database_;
7286 UIPreferencesTable *table_;
7287 _UISwitchSlider *subscribedSwitch_;
7288 _UISwitchSlider *ignoredSwitch_;
7289 UIPreferencesControlTableCell *subscribedCell_;
7290 UIPreferencesControlTableCell *ignoredCell_;
7293 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7297 @implementation SettingsView
7300 [table_ setDataSource:nil];
7303 if (package_ != nil)
7306 [subscribedSwitch_ release];
7307 [ignoredSwitch_ release];
7308 [subscribedCell_ release];
7309 [ignoredCell_ release];
7313 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7314 if (package_ == nil)
7320 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7321 if (package_ == nil)
7334 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7335 if (package_ == nil)
7348 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7349 if (package_ == nil)
7362 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7363 if (package_ == nil)
7366 _UISwitchSlider *slider([cell control]);
7367 BOOL value([slider value] != 0);
7368 NSMutableDictionary *metadata([package_ metadata]);
7371 if (NSNumber *number = [metadata objectForKey:key])
7372 before = [number boolValue];
7376 if (value != before) {
7377 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7379 [delegate_ updateData];
7383 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7384 [self onSomething:cell withKey:@"IsSubscribed"];
7387 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7388 [self onSomething:cell withKey:@"IsIgnored"];
7391 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7392 if (package_ == nil)
7396 case 0: switch (row) {
7398 return subscribedCell_;
7400 return ignoredCell_;
7404 case 1: switch (row) {
7406 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7407 [cell setShowSelection:NO];
7408 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7421 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7422 if ((self = [super initWithBook:book])) {
7423 database_ = database;
7424 name_ = [package retain];
7426 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7427 [self addSubview:table_];
7429 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7430 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
7432 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7433 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
7435 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7436 [subscribedCell_ setShowSelection:NO];
7437 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7438 [subscribedCell_ setControl:subscribedSwitch_];
7440 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7441 [ignoredCell_ setShowSelection:NO];
7442 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7443 [ignoredCell_ setControl:ignoredSwitch_];
7445 [table_ setDataSource:self];
7450 - (void) resetViewAnimated:(BOOL)animated {
7451 [table_ resetViewAnimated:animated];
7454 - (void) reloadData {
7455 if (package_ != nil)
7456 [package_ autorelease];
7457 package_ = [database_ packageWithName:name_];
7458 if (package_ != nil) {
7460 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7461 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7464 [table_ reloadData];
7467 - (NSString *) title {
7468 return UCLocalize("SETTINGS");
7474 /* Signature View {{{ */
7475 @interface SignatureView : CydiaBrowserView {
7476 _transient Database *database_;
7480 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7484 @implementation SignatureView
7491 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7493 [super webView:sender didClearWindowObject:window forFrame:frame];
7496 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7497 if ((self = [super initWithBook:book]) != nil) {
7498 database_ = database;
7499 package_ = [package retain];
7504 - (void) resetViewAnimated:(BOOL)animated {
7507 - (void) reloadData {
7508 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7514 @interface Cydia : UIApplication <
7515 ConfirmationViewDelegate,
7516 ProgressViewDelegate,
7525 UIToolbar *toolbar_;
7529 NSMutableArray *essential_;
7530 NSMutableArray *broken_;
7532 Database *database_;
7533 ProgressView *progress_;
7537 UIKeyboard *keyboard_;
7538 UIProgressHUD *hud_;
7540 SectionsView *sections_;
7541 ChangesView *changes_;
7542 ManageView *manage_;
7543 SearchView *search_;
7545 #if RecyclePackageViews
7546 NSMutableArray *details_;
7550 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7551 - (void) setPage:(RVPage *)page;
7555 static _finline void _setHomePage(Cydia *self) {
7556 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeView class]]];
7559 @implementation Cydia
7561 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7566 if ([broken_ count] != 0) {
7567 int count = [broken_ count];
7569 UIActionSheet *sheet = [[[UIActionSheet alloc]
7570 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7571 buttons:[NSArray arrayWithObjects:
7572 UCLocalize("FORCIBLY_CLEAR"),
7573 UCLocalize("TEMPORARY_IGNORE"),
7575 defaultButtonIndex:0
7580 [sheet setBodyText:UCLocalize("HALFINSTALLED_PACKAGE_EX")];
7581 [sheet popupAlertAnimated:YES];
7582 } else if (!Ignored_ && [essential_ count] != 0) {
7583 int count = [essential_ count];
7585 UIActionSheet *sheet = [[[UIActionSheet alloc]
7586 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7587 buttons:[NSArray arrayWithObjects:
7588 UCLocalize("UPGRADE_ESSENTIAL"),
7589 UCLocalize("COMPLETE_UPGRADE"),
7590 UCLocalize("TEMPORARY_IGNORE"),
7592 defaultButtonIndex:0
7597 [sheet setBodyText:UCLocalize("ESSENTIAL_UPGRADE_EX")];
7598 [sheet popupAlertAnimated:YES];
7602 - (void) _saveConfig {
7605 NSString *error(nil);
7606 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7608 NSError *error(nil);
7609 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7610 NSLog(@"failure to save metadata data: %@", error);
7613 NSLog(@"failure to serialize metadata: %@", error);
7621 - (void) _updateData {
7624 /* XXX: this is just stupid */
7625 if (tag_ != 2 && sections_ != nil)
7626 [sections_ reloadData];
7627 if (tag_ != 3 && changes_ != nil)
7628 [changes_ reloadData];
7629 if (tag_ != 5 && search_ != nil)
7630 [search_ reloadData];
7635 - (void) _reloadData {
7638 static bool loaded(false);
7639 UIProgressHUD *hud([self addProgressHUD]);
7640 [hud setText:(loaded ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7642 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7645 [self removeProgressHUD:hud];
7649 [essential_ removeAllObjects];
7650 [broken_ removeAllObjects];
7652 NSArray *packages([database_ packages]);
7653 for (Package *package in packages) {
7655 [broken_ addObject:package];
7656 if ([package upgradableAndEssential:NO]) {
7657 if ([package essential])
7658 [essential_ addObject:package];
7664 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7665 [toolbar_ setBadgeValue:badge forButton:3];
7666 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7667 [toolbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7668 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7669 [self setApplicationBadge:badge];
7671 [self setApplicationBadgeString:badge];
7673 [toolbar_ setBadgeValue:nil forButton:3];
7674 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7675 [toolbar_ setBadgeAnimated:NO forButton:3];
7676 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7677 [self removeApplicationBadge];
7678 else // XXX: maybe use setApplicationBadgeString also?
7679 [self setApplicationIconBadgeNumber:0];
7683 [toolbar_ setBadgeValue:nil forButton:4];
7687 if (loaded || ManualRefresh) loaded:
7692 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
7694 if (update != nil) {
7695 NSTimeInterval interval([update timeIntervalSinceNow]);
7696 if (interval <= 0 && interval > -(15*60))
7700 [book_ setUpdate:update];
7704 - (void) updateData {
7705 [database_ setVisible];
7714 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
7715 _assert(file != NULL);
7717 for (NSString *key in [Sources_ allKeys]) {
7718 NSDictionary *source([Sources_ objectForKey:key]);
7720 fprintf(file, "%s %s %s\n",
7721 [[source objectForKey:@"Type"] UTF8String],
7722 [[source objectForKey:@"URI"] UTF8String],
7723 [[source objectForKey:@"Distribution"] UTF8String]
7732 detachNewThreadSelector:@selector(update_)
7735 title:UCLocalize("UPDATING_SOURCES")
7739 - (void) reloadData {
7740 @synchronized (self) {
7741 if (confirm_ == nil)
7747 pkgProblemResolver *resolver = [database_ resolver];
7749 resolver->InstallProtect();
7750 if (!resolver->Resolve(true))
7754 - (void) popUpBook:(RVBook *)book {
7755 [underlay_ popSubview:book];
7758 - (CGRect) popUpBounds {
7759 return [underlay_ bounds];
7763 if (![database_ prepare])
7766 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7767 [confirm_ setDelegate:self];
7769 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7770 [page setDelegate:self];
7772 [confirm_ setPage:page];
7773 [self popUpBook:confirm_];
7779 @synchronized (self) {
7784 - (void) clearPackage:(Package *)package {
7785 @synchronized (self) {
7792 - (void) installPackage:(Package *)package {
7793 @synchronized (self) {
7800 - (void) removePackage:(Package *)package {
7801 @synchronized (self) {
7808 - (void) distUpgrade {
7809 @synchronized (self) {
7810 if (![database_ upgrade])
7817 [self slideUp:[[[UIActionSheet alloc]
7819 buttons:[NSArray arrayWithObjects:UCLocalize("CONTINUE_QUEUING"), UCLocalize("CANCEL_CLEAR"), nil]
7820 defaultButtonIndex:1
7827 @synchronized (self) {
7830 if (confirm_ != nil) {
7838 [overlay_ removeFromSuperview];
7842 detachNewThreadSelector:@selector(perform)
7845 title:UCLocalize("RUNNING")
7849 - (void) progressViewIsComplete:(ProgressView *)progress {
7850 if (confirm_ != nil) {
7851 [underlay_ addSubview:overlay_];
7852 [confirm_ popFromSuperviewAnimated:NO];
7858 - (void) setPage:(RVPage *)page {
7859 [page resetViewAnimated:NO];
7860 [page setDelegate:self];
7861 [book_ setPage:page];
7864 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7865 CydiaBrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7866 [browser loadURL:url];
7870 - (SectionsView *) sectionsView {
7871 if (sections_ == nil)
7872 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7876 - (ChangesView *) changesView {
7877 if (changes_ == nil)
7878 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7882 - (ManageView *) manageView {
7884 manage_ = (ManageView *) [[self
7885 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7886 withClass:[ManageView class]
7891 - (SearchView *) searchView {
7893 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7897 - (void) buttonBarItemTapped:(id)sender {
7898 unsigned tag = [sender tag];
7900 [book_ resetViewAnimated:YES];
7902 } else if (tag_ == 2)
7903 [[self sectionsView] resetView];
7906 case 1: _setHomePage(self); break;
7908 case 2: [self setPage:[self sectionsView]]; break;
7909 case 3: [self setPage:[self changesView]]; break;
7910 case 4: [self setPage:[self manageView]]; break;
7911 case 5: [self setPage:[self searchView]]; break;
7919 - (void) askForSettings {
7920 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
7922 CYActionSheet *role([[[CYActionSheet alloc]
7923 initWithTitle:UCLocalize("WHO_ARE_YOU")
7924 buttons:[NSArray arrayWithObjects:
7925 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
7926 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
7927 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
7929 defaultButtonIndex:-1
7932 [role setBodyText:UCLocalize("ROLE_EX")];
7934 int button([role yieldToPopupAlertAnimated:YES]);
7937 case 1: Role_ = @"User"; break;
7938 case 2: Role_ = @"Hacker"; break;
7939 case 3: Role_ = @"Developer"; break;
7944 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7948 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7955 - (void) setPackageView:(PackageView *)view {
7957 [view setPackage:nil];
7958 #if RecyclePackageViews
7959 if ([details_ count] < 3)
7960 [details_ addObject:view];
7965 - (PackageView *) _packageView {
7966 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7969 - (PackageView *) packageView {
7970 #if RecyclePackageViews
7972 size_t count([details_ count]);
7975 view = [self _packageView];
7977 [details_ addObject:[self _packageView]];
7979 view = [[[details_ lastObject] retain] autorelease];
7980 [details_ removeLastObject];
7987 return [self _packageView];
7991 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7992 NSString *context([sheet context]);
7994 if ([context isEqualToString:@"missing"])
7996 else if ([context isEqualToString:@"cancel"]) {
8013 @synchronized (self) {
8018 [toolbar_ setBadgeValue:UCLocalize("Q_D") forButton:4];
8022 if (confirm_ != nil) {
8027 } else if ([context isEqualToString:@"fixhalf"]) {
8030 @synchronized (self) {
8031 for (Package *broken in broken_) {
8034 NSString *id = [broken id];
8035 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8036 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8037 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8038 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8047 [broken_ removeAllObjects];
8055 } else if ([context isEqualToString:@"upgrade"]) {
8058 @synchronized (self) {
8059 for (Package *essential in essential_)
8060 [essential install];
8082 - (void) system:(NSString *)command { _pooled
8083 system([command UTF8String]);
8086 - (void) applicationWillSuspend {
8088 [super applicationWillSuspend];
8091 - (void) applicationSuspend:(__GSEvent *)event {
8092 if (hud_ == nil && ![progress_ isRunning])
8093 [super applicationSuspend:event];
8096 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8098 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8101 - (void) _setSuspended:(BOOL)value {
8103 [super _setSuspended:value];
8106 - (UIProgressHUD *) addProgressHUD {
8107 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8108 [window_ setUserInteractionEnabled:NO];
8110 [progress_ addSubview:hud];
8114 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8116 [hud removeFromSuperview];
8117 [window_ setUserInteractionEnabled:YES];
8120 - (RVPage *) pageForPackage:(NSString *)name {
8121 if (Package *package = [database_ packageWithName:name]) {
8122 PackageView *view([self packageView]);
8123 [view setPackage:package];
8126 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8127 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8128 return [self _pageForURL:url withClass:[CydiaBrowserView class]];
8132 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8136 NSString *href([url absoluteString]);
8137 if ([href hasPrefix:@"apptapp://package/"])
8138 return [self pageForPackage:[href substringFromIndex:18]];
8140 NSString *scheme([[url scheme] lowercaseString]);
8141 if (![scheme isEqualToString:@"cydia"])
8143 NSString *path([url absoluteString]);
8144 if ([path length] < 8)
8146 path = [path substringFromIndex:8];
8147 if (![path hasPrefix:@"/"])
8148 path = [@"/" stringByAppendingString:path];
8150 if ([path isEqualToString:@"/add-source"])
8151 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8152 else if ([path isEqualToString:@"/storage"])
8153 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CydiaBrowserView class]];
8154 else if ([path isEqualToString:@"/sources"])
8155 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8156 else if ([path isEqualToString:@"/packages"])
8157 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8158 else if ([path hasPrefix:@"/url/"])
8159 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CydiaBrowserView class]];
8160 else if ([path hasPrefix:@"/launch/"])
8161 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8162 else if ([path hasPrefix:@"/package-settings/"])
8163 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8164 else if ([path hasPrefix:@"/package-signature/"])
8165 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8166 else if ([path hasPrefix:@"/package/"])
8167 return [self pageForPackage:[path substringFromIndex:9]];
8168 else if ([path hasPrefix:@"/files/"]) {
8169 NSString *name = [path substringFromIndex:7];
8171 if (Package *package = [database_ packageWithName:name]) {
8172 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8173 [files setPackage:package];
8181 - (void) applicationOpenURL:(NSURL *)url {
8182 [super applicationOpenURL:url];
8184 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8185 [self setPage:page];
8186 [toolbar_ showSelectionForButton:tag];
8191 - (void) applicationDidFinishLaunching:(id)unused {
8192 [BrowserView _initialize];
8194 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8196 Font12_ = [[UIFont systemFontOfSize:12] retain];
8197 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8198 Font14_ = [[UIFont systemFontOfSize:14] retain];
8199 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8200 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8204 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8205 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8207 window_ = [[UIWindow alloc] initWithContentRect:[UIHardware fullScreenApplicationContentRect]];
8208 [window_ orderFront:self];
8209 [window_ makeKey:self];
8210 [window_ setHidden:NO];
8211 //[window_ setAutorotates:YES];
8212 //[window_ setDelegate:self];
8214 database_ = [Database sharedInstance];
8216 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8217 [database_ setDelegate:progress_];
8218 [window_ setContentView:progress_];
8220 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8221 [progress_ setContentView:underlay_];
8223 [progress_ resetView];
8226 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8227 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8228 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8229 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8230 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8231 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8232 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8233 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8234 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8237 [self setIdleTimerDisabled:YES];
8239 hud_ = [self addProgressHUD];
8240 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8241 [self setStatusBarShowsProgress:YES];
8243 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8245 [self setStatusBarShowsProgress:NO];
8246 [self removeProgressHUD:hud_];
8249 if (ExecFork() == 0) {
8250 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8251 perror("launchctl stop");
8258 [self askForSettings];
8261 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
8263 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8264 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
8265 0, 0, screenrect.size.width, screenrect.size.height - 48
8266 ) database:database_];
8268 [book_ setDelegate:self];
8270 [overlay_ addSubview:book_];
8272 NSArray *buttonitems = [NSArray arrayWithObjects:
8273 [NSDictionary dictionaryWithObjectsAndKeys:
8274 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8275 @"home-up.png", kUIButtonBarButtonInfo,
8276 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
8277 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
8278 self, kUIButtonBarButtonTarget,
8279 @"Cydia", kUIButtonBarButtonTitle,
8280 @"0", kUIButtonBarButtonType,
8283 [NSDictionary dictionaryWithObjectsAndKeys:
8284 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8285 @"install-up.png", kUIButtonBarButtonInfo,
8286 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
8287 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
8288 self, kUIButtonBarButtonTarget,
8289 UCLocalize("SECTIONS"), kUIButtonBarButtonTitle,
8290 @"0", kUIButtonBarButtonType,
8293 [NSDictionary dictionaryWithObjectsAndKeys:
8294 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8295 @"changes-up.png", kUIButtonBarButtonInfo,
8296 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
8297 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
8298 self, kUIButtonBarButtonTarget,
8299 UCLocalize("CHANGES"), kUIButtonBarButtonTitle,
8300 @"0", kUIButtonBarButtonType,
8303 [NSDictionary dictionaryWithObjectsAndKeys:
8304 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8305 @"manage-up.png", kUIButtonBarButtonInfo,
8306 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
8307 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
8308 self, kUIButtonBarButtonTarget,
8309 UCLocalize("MANAGE"), kUIButtonBarButtonTitle,
8310 @"0", kUIButtonBarButtonType,
8313 [NSDictionary dictionaryWithObjectsAndKeys:
8314 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8315 @"search-up.png", kUIButtonBarButtonInfo,
8316 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
8317 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
8318 self, kUIButtonBarButtonTarget,
8319 UCLocalize("SEARCH"), kUIButtonBarButtonTitle,
8320 @"0", kUIButtonBarButtonType,
8324 toolbar_ = [[UIToolbar alloc]
8326 withFrame:CGRectMake(
8327 0, screenrect.size.height - ButtonBarHeight_,
8328 screenrect.size.width, ButtonBarHeight_
8330 withItemList:buttonitems
8333 [toolbar_ setDelegate:self];
8334 [toolbar_ setBarStyle:1];
8335 [toolbar_ setButtonBarTrackingMode:2];
8337 int buttons[5] = {1, 2, 3, 4, 5};
8338 [toolbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
8339 [toolbar_ showButtonGroup:0 withDuration:0];
8341 for (int i = 0; i != 5; ++i)
8342 [[toolbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
8343 i * (screenrect.size.width / 5) + (screenrect.size.width / 5 - ButtonBarWidth_) / 2, 1,
8344 ButtonBarWidth_, ButtonBarHeight_
8347 [toolbar_ showSelectionForButton:1];
8348 [overlay_ addSubview:toolbar_];
8350 [UIKeyboard initImplementationNow];
8351 /*CGSize keysize = [UIKeyboard defaultSize];
8352 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
8353 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
8354 [overlay_ addSubview:keyboard_];*/
8356 [underlay_ addSubview:overlay_];
8360 #if RecyclePackageViews
8361 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8362 [details_ addObject:[self _packageView]];
8363 [details_ addObject:[self _packageView]];
8371 - (void) showKeyboard:(BOOL)show {
8372 CGSize keysize([UIKeyboard defaultSize]);
8373 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8374 CGRect keyup(keydown);
8375 keyup.origin.y -= keysize.height;
8377 UIFrameAnimation *animation([[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease]);
8378 [animation setSignificantRectFields:2];
8381 [animation setStartFrame:keydown];
8382 [animation setEndFrame:keyup];
8383 [keyboard_ activate];
8385 [animation setStartFrame:keyup];
8386 [animation setEndFrame:keydown];
8387 [keyboard_ deactivate];
8390 [[UIAnimator sharedAnimator]
8391 addAnimations:[NSArray arrayWithObjects:animation, nil]
8392 withDuration:KeyboardTime_
8397 - (void) slideUp:(UIActionSheet *)alert {
8398 [alert presentSheetInView:overlay_];
8404 id Alloc_(id self, SEL selector) {
8405 id object = alloc_(self, selector);
8406 lprintf("[%s]A-%p\n", self->isa->name, object);
8411 id Dealloc_(id self, SEL selector) {
8412 id object = dealloc_(self, selector);
8413 lprintf("[%s]D-%p\n", self->isa->name, object);
8417 Class $WebDefaultUIKitDelegate;
8419 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8420 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8421 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8422 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8425 int main(int argc, char *argv[]) { _pooled
8428 if (Class $UIDevice = objc_getClass("UIDevice")) {
8429 UIDevice *device([$UIDevice currentDevice]);
8430 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8434 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8436 /* Library Hacks {{{ */
8437 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8439 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8440 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8441 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8442 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8443 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8446 /* Set Locale {{{ */
8447 Locale_ = CFLocaleCopyCurrent();
8448 Languages_ = [NSLocale preferredLanguages];
8449 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8450 //NSLog(@"%@", [Languages_ description]);
8453 if (Languages_ == nil || [Languages_ count] == 0)
8454 // XXX: consider just setting to C and then falling through?
8457 lang = [[Languages_ objectAtIndex:0] UTF8String];
8458 setenv("LANG", lang, true);
8461 //std::setlocale(LC_ALL, lang);
8462 NSLog(@"Setting Language: %s", lang);
8465 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8467 /* Parse Arguments {{{ */
8468 bool substrate(false);
8474 for (int argi(1); argi != argc; ++argi)
8475 if (strcmp(argv[argi], "--") == 0) {
8477 argv[argi] = argv[0];
8483 for (int argi(1); argi != arge; ++argi)
8484 if (strcmp(args[argi], "--substrate") == 0)
8487 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8491 App_ = [[NSBundle mainBundle] bundlePath];
8492 Home_ = NSHomeDirectory();
8498 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8499 alloc_ = alloc->method_imp;
8500 alloc->method_imp = (IMP) &Alloc_;*/
8502 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8503 dealloc_ = dealloc->method_imp;
8504 dealloc->method_imp = (IMP) &Dealloc_;*/
8506 /* System Information {{{ */
8510 size = sizeof(maxproc);
8511 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8512 perror("sysctlbyname(\"kern.maxproc\", ?)");
8513 else if (maxproc < 64) {
8515 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8516 perror("sysctlbyname(\"kern.maxproc\", #)");
8519 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8520 char *osversion = new char[size];
8521 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8522 perror("sysctlbyname(\"kern.osversion\", ?)");
8524 System_ = [NSString stringWithUTF8String:osversion];
8526 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8527 char *machine = new char[size];
8528 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8529 perror("sysctlbyname(\"hw.machine\", ?)");
8533 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8534 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8535 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8536 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8540 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8541 NSData *data((NSData *) ecid);
8542 size_t length([data length]);
8543 uint8_t bytes[length];
8544 [data getBytes:bytes];
8545 char string[length * 2 + 1];
8546 for (size_t i(0); i != length; ++i)
8547 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8548 ChipID_ = [NSString stringWithUTF8String:string];
8552 IOObjectRelease(service);
8556 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8558 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8559 Build_ = [system objectForKey:@"ProductBuildVersion"];
8560 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8561 Product_ = [info objectForKey:@"SafariProductVersion"];
8562 Safari_ = [info objectForKey:@"CFBundleVersion"];
8565 /* Load Database {{{ */
8567 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8569 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8572 if (Metadata_ == NULL)
8573 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8575 Settings_ = [Metadata_ objectForKey:@"Settings"];
8577 Packages_ = [Metadata_ objectForKey:@"Packages"];
8578 Sections_ = [Metadata_ objectForKey:@"Sections"];
8579 Sources_ = [Metadata_ objectForKey:@"Sources"];
8582 if (Settings_ != nil)
8583 Role_ = [Settings_ objectForKey:@"Role"];
8585 if (Packages_ == nil) {
8586 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8587 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8590 if (Sections_ == nil) {
8591 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8592 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8595 if (Sources_ == nil) {
8596 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8597 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8602 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8605 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8607 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
8608 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
8609 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8610 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8611 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8612 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8614 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
8616 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8617 unlink("/tmp/.cydia.fw");
8619 } else if (access("/User", F_OK) != 0 || version < 1) {
8622 system("/usr/libexec/cydia/firmware.sh");
8626 _assert([[NSFileManager defaultManager]
8627 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8628 withIntermediateDirectories:YES
8633 if (access("/tmp/cydia.chk", F_OK) == 0) {
8634 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8635 _assert(errno == ENOENT);
8636 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8637 _assert(errno == ENOENT);
8640 /* APT Initialization {{{ */
8641 _assert(pkgInitConfig(*_config));
8642 _assert(pkgInitSystem(*_config, _system));
8645 _config->Set("APT::Acquire::Translation", lang);
8646 _config->Set("Acquire::http::Timeout", 15);
8647 _config->Set("Acquire::http::MaxParallel", 3);
8649 /* Color Choices {{{ */
8650 space_ = CGColorSpaceCreateDeviceRGB();
8652 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8653 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8654 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8655 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8656 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8657 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8658 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8659 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8660 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8662 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8663 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8665 /* UIKit Configuration {{{ */
8666 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8667 if ($GSFontSetUseLegacyFontMetrics != NULL)
8668 $GSFontSetUseLegacyFontMetrics(YES);
8670 // XXX: I have a feeling this was important
8671 //UIKeyboardDisableAutomaticAppearance();
8674 Colon_ = UCLocalize("COLON_DELIMITED");
8675 Error_ = UCLocalize("ERROR");
8676 Warning_ = UCLocalize("WARNING");
8679 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8681 CGColorSpaceRelease(space_);