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 (1 && !ForRelease)
382 #define LogBrowser (0 && !ForRelease)
383 #define TrackResize (0 && !ForRelease)
384 #define ManualRefresh (1 && !ForRelease)
385 #define ShowInternals (0 && !ForRelease)
386 #define IgnoreInstall (0 && !ForRelease)
387 #define RecycleWebViews 0
388 #define RecyclePackageViews (1 && ForRelease)
389 #define AlwaysReload (1 && !ForRelease)
393 #define _trace(args...)
398 #define _profile(name) {
401 #define PrintTimes() do {} while (false)
405 typedef uint32_t (*SKRadixFunction)(id, void *);
407 @interface NSMutableArray (Radix)
408 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
409 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
417 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
418 struct RadixItem_ *lhs(swap), *rhs(swap + count);
420 static const size_t width = 32;
421 static const size_t bits = 11;
422 static const size_t slots = 1 << bits;
423 static const size_t passes = (width + (bits - 1)) / bits;
425 size_t *hist(new size_t[slots]);
427 for (size_t pass(0); pass != passes; ++pass) {
428 memset(hist, 0, sizeof(size_t) * slots);
430 for (size_t i(0); i != count; ++i) {
431 uint32_t key(lhs[i].key);
433 key &= _not(uint32_t) >> width - bits;
438 for (size_t i(0); i != slots; ++i) {
439 size_t local(offset);
444 for (size_t i(0); i != count; ++i) {
445 uint32_t key(lhs[i].key);
447 key &= _not(uint32_t) >> width - bits;
448 rhs[hist[key]++] = lhs[i];
451 RadixItem_ *tmp(lhs);
458 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
459 for (size_t i(0); i != count; ++i)
460 [values addObject:[self objectAtIndex:lhs[i].index]];
461 [self setArray:values];
466 @implementation NSMutableArray (Radix)
468 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
469 size_t count([self count]);
474 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
475 [invocation setSelector:selector];
476 [invocation setArgument:&object atIndex:2];
478 /* XXX: this is an unsafe optimization of doomy hell */
479 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
480 _assert(method != NULL);
481 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
482 _assert(imp != NULL);
485 struct RadixItem_ *swap(new RadixItem_[count * 2]);
487 for (size_t i(0); i != count; ++i) {
488 RadixItem_ &item(swap[i]);
491 id object([self objectAtIndex:i]);
494 [invocation setTarget:object];
496 [invocation getReturnValue:&item.key];
498 item.key = imp(object, selector, object);
502 RadixSort_(self, count, swap);
505 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
506 size_t count([self count]);
507 struct RadixItem_ *swap(new RadixItem_[count * 2]);
509 for (size_t i(0); i != count; ++i) {
510 RadixItem_ &item(swap[i]);
513 id object([self objectAtIndex:i]);
514 item.key = function(object, argument);
517 RadixSort_(self, count, swap);
522 /* Insertion Sort {{{ */
524 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
525 const char *ptr = (const char *)list;
527 CFIndex half = count / 2;
528 const char *probe = ptr + elementSize * half;
529 CFComparisonResult cr = comparator(element, probe, context);
530 if (0 == cr) return (probe - (const char *)list) / elementSize;
531 ptr = (cr < 0) ? ptr : probe + elementSize;
532 count = (cr < 0) ? half : (half + (count & 1) - 1);
534 return (ptr - (const char *)list) / elementSize;
537 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
538 const char *ptr = (const char *)list;
540 CFIndex half = count / 2;
541 const char *probe = ptr + elementSize * half;
542 CFComparisonResult cr = comparator(element, probe, context);
543 if (0 == cr) return (probe - (const char *)list) / elementSize;
544 ptr = (cr < 0) ? ptr : probe + elementSize;
545 count = (cr < 0) ? half : (half + (count & 1) - 1);
547 return (ptr - (const char *)list) / elementSize;
550 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
551 if (range.length == 0)
553 const void **values(new const void *[range.length]);
554 CFArrayGetValues(array, range, values);
556 #if HistogramInsertionSort
557 uint32_t total(0), *offsets(new uint32_t[range.length]);
560 for (CFIndex index(1); index != range.length; ++index) {
561 const void *value(values[index]);
562 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
563 CFIndex correct(index);
564 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
567 if (correct != index) {
568 size_t offset(index - correct);
569 #if HistogramInsertionSort
573 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
575 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
576 values[correct] = value;
580 CFArrayReplaceValues(array, range, values, range.length);
583 #if HistogramInsertionSort
584 for (CFIndex index(0); index != range.length; ++index)
585 if (offsets[index] != 0)
586 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
587 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
594 /* Apple Bug Fixes {{{ */
595 @implementation UIWebDocumentView (Cydia)
597 - (void) _setScrollerOffset:(CGPoint)offset {
598 UIScroller *scroller([self _scroller]);
600 CGSize size([scroller contentSize]);
601 CGSize bounds([scroller bounds].size);
604 max.x = size.width - bounds.width;
605 max.y = size.height - bounds.height;
613 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
614 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
616 [scroller setOffset:offset];
622 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
623 size_t length([self length] - state->state);
626 else if (length > count)
628 for (size_t i(0); i != length; ++i)
629 objects[i] = [self item:state->state++];
630 state->itemsPtr = objects;
631 state->mutationsPtr = (unsigned long *) self;
635 @interface NSString (UIKit)
636 - (NSString *) stringByAddingPercentEscapes;
639 /* Cydia NSString Additions {{{ */
640 @interface NSString (Cydia)
641 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
642 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
643 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
644 - (NSComparisonResult) compareByPath:(NSString *)other;
645 - (NSString *) stringByCachingURLWithCurrentCDN;
646 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
649 @implementation NSString (Cydia)
651 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
652 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
655 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
656 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
657 memcpy(data, bytes, length);
658 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
661 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
662 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
665 - (NSComparisonResult) compareByPath:(NSString *)other {
666 NSString *prefix = [self commonPrefixWithString:other options:0];
667 size_t length = [prefix length];
669 NSRange lrange = NSMakeRange(length, [self length] - length);
670 NSRange rrange = NSMakeRange(length, [other length] - length);
672 lrange = [self rangeOfString:@"/" options:0 range:lrange];
673 rrange = [other rangeOfString:@"/" options:0 range:rrange];
675 NSComparisonResult value;
677 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
678 value = NSOrderedSame;
679 else if (lrange.location == NSNotFound)
680 value = NSOrderedAscending;
681 else if (rrange.location == NSNotFound)
682 value = NSOrderedDescending;
684 value = NSOrderedSame;
686 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
687 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
688 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
689 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
691 NSComparisonResult result = [lpath compare:rpath];
692 return result == NSOrderedSame ? value : result;
695 - (NSString *) stringByCachingURLWithCurrentCDN {
697 stringByReplacingOccurrencesOfString:@"://"
698 withString:@"://ne.edgecastcdn.net/8003A4/"
700 /* XXX: this is somewhat inaccurate */
701 range:NSMakeRange(0, 10)
705 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
706 return [(id)CFURLCreateStringByAddingPercentEscapes(
711 kCFStringEncodingUTF8
718 /* C++ NSString Wrapper Cache {{{ */
725 _finline void clear_() {
726 if (cache_ != NULL) {
733 _finline bool empty() const {
737 _finline size_t size() const {
741 _finline char *data() const {
745 _finline void clear() {
750 _finline CYString() :
757 _finline ~CYString() {
761 void operator =(const CYString &rhs) {
765 if (rhs.cache_ == nil)
768 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
771 void set(apr_pool_t *pool, const char *data, size_t size) {
777 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
778 memcpy(temp, data, size);
785 _finline void set(apr_pool_t *pool, const char *data) {
786 set(pool, data, data == NULL ? 0 : strlen(data));
789 _finline void set(apr_pool_t *pool, const std::string &rhs) {
790 set(pool, rhs.data(), rhs.size());
793 bool operator ==(const CYString &rhs) const {
794 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
797 operator CFStringRef() {
798 if (cache_ == NULL) {
801 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
805 _finline operator id() {
806 return (NSString *) static_cast<CFStringRef>(*this);
810 /* C++ NSString Algorithm Adapters {{{ */
812 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
815 struct NSStringMapHash :
816 std::unary_function<NSString *, size_t>
818 _finline size_t operator ()(NSString *value) const {
819 return CFStringHashNSString((CFStringRef) value);
823 struct NSStringMapLess :
824 std::binary_function<NSString *, NSString *, bool>
826 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
827 return [lhs compare:rhs] == NSOrderedAscending;
831 struct NSStringMapEqual :
832 std::binary_function<NSString *, NSString *, bool>
834 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
835 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
836 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
837 //[lhs isEqualToString:rhs];
842 /* Perl-Compatible RegEx {{{ */
852 Pcre(const char *regex) :
857 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
860 lprintf("%d:%s\n", offset, error);
864 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
865 matches_ = new int[(capture_ + 1) * 3];
873 NSString *operator [](size_t match) {
874 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
877 bool operator ()(NSString *data) {
878 // XXX: length is for characters, not for bytes
879 return operator ()([data UTF8String], [data length]);
882 bool operator ()(const char *data, size_t size) {
884 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
888 /* Mime Addresses {{{ */
889 @interface Address : NSObject {
895 - (NSString *) address;
897 - (void) setAddress:(NSString *)address;
899 + (Address *) addressWithString:(NSString *)string;
900 - (Address *) initWithString:(NSString *)string;
903 @implementation Address
912 - (NSString *) name {
916 - (NSString *) address {
920 - (void) setAddress:(NSString *)address {
922 [address_ autorelease];
926 address_ = [address retain];
929 + (Address *) addressWithString:(NSString *)string {
930 return [[[Address alloc] initWithString:string] autorelease];
933 + (NSArray *) _attributeKeys {
934 return [NSArray arrayWithObjects:@"address", @"name", nil];
937 - (NSArray *) attributeKeys {
938 return [[self class] _attributeKeys];
941 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
942 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
945 - (Address *) initWithString:(NSString *)string {
946 if ((self = [super init]) != nil) {
947 const char *data = [string UTF8String];
948 size_t size = [string length];
950 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
952 if (address_r(data, size)) {
953 name_ = [address_r[1] retain];
954 address_ = [address_r[2] retain];
956 name_ = [string retain];
964 /* CoreGraphics Primitives {{{ */
975 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
978 Set(space, red, green, blue, alpha);
983 CGColorRelease(color_);
990 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
992 float color[] = {red, green, blue, alpha};
993 color_ = CGColorCreate(space, color);
996 operator CGColorRef() {
1002 /* Random Global Variables {{{ */
1003 static const int PulseInterval_ = 50000;
1004 static const int ButtonBarHeight_ = 48;
1005 static const float KeyboardTime_ = 0.3f;
1008 static NSArray *Finishes_;
1010 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1011 #define NotifyConfig_ "/etc/notify.conf"
1013 static bool Queuing_;
1015 static CGColor Blue_;
1016 static CGColor Blueish_;
1017 static CGColor Black_;
1018 static CGColor Off_;
1019 static CGColor White_;
1020 static CGColor Gray_;
1021 static CGColor Green_;
1022 static CGColor Purple_;
1023 static CGColor Purplish_;
1025 static UIColor *InstallingColor_;
1026 static UIColor *RemovingColor_;
1028 static NSString *App_;
1029 static NSString *Home_;
1031 static BOOL Advanced_;
1032 static BOOL Ignored_;
1034 static UIFont *Font12_;
1035 static UIFont *Font12Bold_;
1036 static UIFont *Font14_;
1037 static UIFont *Font18Bold_;
1038 static UIFont *Font22Bold_;
1040 static const char *Machine_ = NULL;
1041 static const NSString *System_ = NULL;
1042 static const NSString *SerialNumber_ = nil;
1043 static const NSString *ChipID_ = nil;
1044 static const NSString *UniqueID_ = nil;
1045 static const NSString *Build_ = nil;
1046 static const NSString *Product_ = nil;
1047 static const NSString *Safari_ = nil;
1049 static CFLocaleRef Locale_;
1050 static NSArray *Languages_;
1051 static CGColorSpaceRef space_;
1053 static bool reload_;
1055 static NSDictionary *SectionMap_;
1056 static NSMutableDictionary *Metadata_;
1057 static _transient NSMutableDictionary *Settings_;
1058 static _transient NSString *Role_;
1059 static _transient NSMutableDictionary *Packages_;
1060 static _transient NSMutableDictionary *Sections_;
1061 static _transient NSMutableDictionary *Sources_;
1062 static bool Changed_;
1063 static NSDate *now_;
1066 static NSMutableArray *Documents_;
1070 /* Display Helpers {{{ */
1071 inline float Interpolate(float begin, float end, float fraction) {
1072 return (end - begin) * fraction + begin;
1075 /* XXX: localize this! */
1076 NSString *SizeString(double size) {
1077 bool negative = size < 0;
1082 while (size > 1024) {
1087 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1089 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1092 static _finline CFStringRef CFCString(const char *value) {
1093 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1096 const char *StripVersion_(const char *version) {
1097 const char *colon(strchr(version, ':'));
1099 version = colon + 1;
1103 CFStringRef StripVersion(const char *version) {
1104 const char *colon(strchr(version, ':'));
1106 version = colon + 1;
1107 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1109 return CFCString(version);
1112 NSString *LocalizeSection(NSString *section) {
1113 static Pcre title_r("^(.*?) \\((.*)\\)$");
1114 if (title_r(section)) {
1115 NSString *parent(title_r[1]);
1116 NSString *child(title_r[2]);
1118 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1119 LocalizeSection(parent),
1120 LocalizeSection(child)
1124 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1127 NSString *Simplify(NSString *title) {
1128 const char *data = [title UTF8String];
1129 size_t size = [title length];
1131 static Pcre square_r("^\\[(.*)\\]$");
1132 if (square_r(data, size))
1133 return Simplify(square_r[1]);
1135 static Pcre paren_r("^\\((.*)\\)$");
1136 if (paren_r(data, size))
1137 return Simplify(paren_r[1]);
1139 static Pcre title_r("^(.*?) \\((.*)\\)$");
1140 if (title_r(data, size))
1141 return Simplify(title_r[1]);
1147 NSString *GetLastUpdate() {
1148 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1151 return UCLocalize("NEVER_OR_UNKNOWN");
1153 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1154 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1156 CFRelease(formatter);
1158 return [(NSString *) formatted autorelease];
1161 bool isSectionVisible(NSString *section) {
1162 NSDictionary *metadata([Sections_ objectForKey:section]);
1163 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1164 return hidden == nil || ![hidden boolValue];
1167 /* Delegate Prototypes {{{ */
1171 @interface NSObject (ProgressDelegate)
1174 @protocol ProgressDelegate
1175 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1176 - (void) setProgressTitle:(NSString *)title;
1177 - (void) setProgressPercent:(float)percent;
1178 - (void) startProgress;
1179 - (void) addProgressOutput:(NSString *)output;
1180 - (bool) isCancelling:(size_t)received;
1183 @protocol ConfigurationDelegate
1184 - (void) repairWithSelector:(SEL)selector;
1185 - (void) setConfigurationData:(NSString *)data;
1190 @protocol CydiaDelegate
1191 - (void) setPackageView:(PackageView *)view;
1192 - (void) clearPackage:(Package *)package;
1193 - (void) installPackage:(Package *)package;
1194 - (void) removePackage:(Package *)package;
1195 - (void) slideUp:(UIActionSheet *)alert;
1196 - (void) distUpgrade;
1197 - (void) updateData;
1199 - (void) askForSettings;
1200 - (UIProgressHUD *) addProgressHUD;
1201 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1202 - (RVPage *) pageForPackage:(NSString *)name;
1203 - (PackageView *) packageView;
1207 /* Status Delegation {{{ */
1209 public pkgAcquireStatus
1212 _transient NSObject<ProgressDelegate> *delegate_;
1220 void setDelegate(id delegate) {
1221 delegate_ = delegate;
1224 NSObject<ProgressDelegate> *getDelegate() const {
1228 virtual bool MediaChange(std::string media, std::string drive) {
1232 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1235 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1236 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1237 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1240 virtual void Done(pkgAcquire::ItemDesc &item) {
1243 virtual void Fail(pkgAcquire::ItemDesc &item) {
1245 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1246 item.Owner->Status == pkgAcquire::Item::StatDone
1250 std::string &error(item.Owner->ErrorText);
1254 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1255 NSArray *fields([description componentsSeparatedByString:@" "]);
1256 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1258 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1259 withObject:[NSArray arrayWithObjects:
1260 [NSString stringWithUTF8String:error.c_str()],
1267 virtual bool Pulse(pkgAcquire *Owner) {
1268 bool value = pkgAcquireStatus::Pulse(Owner);
1271 double(CurrentBytes + CurrentItems) /
1272 double(TotalBytes + TotalItems)
1275 [delegate_ setProgressPercent:percent];
1276 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1279 virtual void Start() {
1280 [delegate_ startProgress];
1283 virtual void Stop() {
1287 /* Progress Delegation {{{ */
1292 _transient id<ProgressDelegate> delegate_;
1296 virtual void Update() {
1297 /*if (abs(Percent - percent_) > 2)
1298 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1302 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1303 [delegate_ setProgressPercent:(Percent / 100)];*/
1313 void setDelegate(id delegate) {
1314 delegate_ = delegate;
1317 id getDelegate() const {
1321 virtual void Done() {
1323 //[delegate_ setProgressPercent:1];
1328 /* Database Interface {{{ */
1329 typedef std::map< unsigned long, _H<Source> > SourceMap;
1331 @interface Database : NSObject {
1337 pkgCacheFile cache_;
1338 pkgDepCache::Policy *policy_;
1339 pkgRecords *records_;
1340 pkgProblemResolver *resolver_;
1341 pkgAcquire *fetcher_;
1343 SPtr<pkgPackageManager> manager_;
1344 pkgSourceList *list_;
1347 NSMutableArray *packages_;
1349 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1358 + (Database *) sharedInstance;
1361 - (void) _readCydia:(NSNumber *)fd;
1362 - (void) _readStatus:(NSNumber *)fd;
1363 - (void) _readOutput:(NSNumber *)fd;
1367 - (Package *) packageWithName:(NSString *)name;
1369 - (pkgCacheFile &) cache;
1370 - (pkgDepCache::Policy *) policy;
1371 - (pkgRecords *) records;
1372 - (pkgProblemResolver *) resolver;
1373 - (pkgAcquire &) fetcher;
1374 - (pkgSourceList &) list;
1375 - (NSArray *) packages;
1376 - (NSArray *) sources;
1377 - (void) reloadData;
1385 - (void) setVisible;
1387 - (void) updateWithStatus:(Status &)status;
1389 - (void) setDelegate:(id)delegate;
1390 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1393 /* Delegate Helpers {{{ */
1394 @implementation NSObject(ProgressDelegate)
1396 - (void) _setProgressErrorPackage:(NSArray *)args {
1397 [self performSelector:@selector(setProgressError:forPackage:)
1398 withObject:[args objectAtIndex:0]
1399 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1403 - (void) _setProgressErrorTitle:(NSArray *)args {
1404 [self performSelector:@selector(setProgressError:withTitle:)
1405 withObject:[args objectAtIndex:0]
1406 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1410 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1411 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1412 withObject:[NSArray arrayWithObjects:error, title, nil]
1417 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1418 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1419 // XXX: holy typecast batman!
1420 [(id<ProgressDelegate>)self setProgressError:error withTitle:(package == nil ? id : [package name])];
1426 /* Source Class {{{ */
1427 @interface Source : NSObject {
1428 CYString depiction_;
1429 CYString description_;
1435 CYString distribution_;
1440 NSString *authority_;
1442 CYString defaultIcon_;
1444 NSDictionary *record_;
1448 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1450 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1452 - (NSString *) depictionForPackage:(NSString *)package;
1453 - (NSString *) supportForPackage:(NSString *)package;
1455 - (NSDictionary *) record;
1459 - (NSString *) distribution;
1460 - (NSString *) type;
1462 - (NSString *) host;
1464 - (NSString *) name;
1465 - (NSString *) description;
1466 - (NSString *) label;
1467 - (NSString *) origin;
1468 - (NSString *) version;
1470 - (NSString *) defaultIcon;
1474 @implementation Source
1478 distribution_.clear();
1481 description_.clear();
1487 defaultIcon_.clear();
1489 if (record_ != nil) {
1499 if (authority_ != nil) {
1500 [authority_ release];
1510 + (NSArray *) _attributeKeys {
1511 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1514 - (NSArray *) attributeKeys {
1515 return [[self class] _attributeKeys];
1518 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1519 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1522 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1525 trusted_ = index->IsTrusted();
1527 uri_.set(pool, index->GetURI());
1528 distribution_.set(pool, index->GetDist());
1529 type_.set(pool, index->GetType());
1531 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1532 if (dindex != NULL) {
1534 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1537 pkgTagFile tags(&fd);
1539 pkgTagSection section;
1546 {"default-icon", &defaultIcon_},
1547 {"depiction", &depiction_},
1548 {"description", &description_},
1550 {"origin", &origin_},
1551 {"support", &support_},
1552 {"version", &version_},
1555 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1556 const char *start, *end;
1558 if (section.Find(names[i].name_, start, end)) {
1559 CYString &value(*names[i].value_);
1560 value.set(pool, start, end - start);
1566 record_ = [Sources_ objectForKey:[self key]];
1568 record_ = [record_ retain];
1570 NSURL *url([NSURL URLWithString:uri_]);
1574 host_ = [[host_ lowercaseString] retain];
1579 authority_ = [url path];
1581 if (authority_ != nil)
1582 authority_ = [authority_ retain];
1585 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1586 if ((self = [super init]) != nil) {
1587 [self setMetaIndex:index inPool:pool];
1591 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1592 NSDictionary *lhr = [self record];
1593 NSDictionary *rhr = [source record];
1596 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1598 NSString *lhs = [self name];
1599 NSString *rhs = [source name];
1601 if ([lhs length] != 0 && [rhs length] != 0) {
1602 unichar lhc = [lhs characterAtIndex:0];
1603 unichar rhc = [rhs characterAtIndex:0];
1605 if (isalpha(lhc) && !isalpha(rhc))
1606 return NSOrderedAscending;
1607 else if (!isalpha(lhc) && isalpha(rhc))
1608 return NSOrderedDescending;
1611 return [lhs compare:rhs options:LaxCompareOptions_];
1614 - (NSString *) depictionForPackage:(NSString *)package {
1615 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1618 - (NSString *) supportForPackage:(NSString *)package {
1619 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1622 - (NSDictionary *) record {
1630 - (NSString *) uri {
1634 - (NSString *) distribution {
1635 return distribution_;
1638 - (NSString *) type {
1642 - (NSString *) key {
1643 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1646 - (NSString *) host {
1650 - (NSString *) name {
1651 return origin_.empty() ? authority_ : origin_;
1654 - (NSString *) description {
1655 return description_;
1658 - (NSString *) label {
1659 return label_.empty() ? authority_ : label_;
1662 - (NSString *) origin {
1666 - (NSString *) version {
1670 - (NSString *) defaultIcon {
1671 return defaultIcon_;
1676 /* Relationship Class {{{ */
1677 @interface Relationship : NSObject {
1682 - (NSString *) type;
1684 - (NSString *) name;
1688 @implementation Relationship
1696 - (NSString *) type {
1704 - (NSString *) name {
1711 /* Package Class {{{ */
1712 @interface Package : NSObject {
1716 pkgCache::VerIterator version_;
1717 pkgCache::PkgIterator iterator_;
1718 _transient Database *database_;
1719 pkgCache::VerFileIterator file_;
1726 NSString *section$_;
1732 CYString installed_;
1738 CYString depiction_;
1749 NSMutableArray *tags_;
1752 NSArray *relationships_;
1754 NSMutableDictionary *metadata_;
1755 _transient NSDate *firstSeen_;
1756 _transient NSDate *lastSeen_;
1760 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1761 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1763 - (pkgCache::PkgIterator) iterator;
1766 - (NSString *) section;
1767 - (NSString *) simpleSection;
1769 - (NSString *) longSection;
1770 - (NSString *) shortSection;
1774 - (Address *) maintainer;
1776 - (NSString *) longDescription;
1777 - (NSString *) shortDescription;
1780 - (NSMutableDictionary *) metadata;
1782 - (BOOL) subscribed;
1785 - (NSString *) latest;
1786 - (NSString *) installed;
1787 - (BOOL) uninstalled;
1790 - (BOOL) upgradableAndEssential:(BOOL)essential;
1793 - (BOOL) unfiltered;
1797 - (BOOL) halfConfigured;
1798 - (BOOL) halfInstalled;
1800 - (NSString *) mode;
1802 - (void) setVisible;
1805 - (NSString *) name;
1807 - (NSString *) homepage;
1808 - (NSString *) depiction;
1809 - (Address *) author;
1811 - (NSString *) support;
1813 - (NSArray *) files;
1814 - (NSArray *) relationships;
1815 - (NSArray *) warnings;
1816 - (NSArray *) applications;
1818 - (Source *) source;
1819 - (NSString *) role;
1821 - (BOOL) matches:(NSString *)text;
1823 - (bool) hasSupportingRole;
1824 - (BOOL) hasTag:(NSString *)tag;
1825 - (NSString *) primaryPurpose;
1826 - (NSArray *) purposes;
1827 - (bool) isCommercial;
1829 - (CYString &) cyname;
1831 - (uint32_t) compareBySection:(NSArray *)sections;
1833 - (uint32_t) compareForChanges;
1838 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1839 - (bool) isInstalledAndVisible:(NSNumber *)number;
1840 - (bool) isVisibleInSection:(NSString *)section;
1841 - (bool) isVisibleInSource:(Source *)source;
1845 uint32_t PackageChangesRadix(Package *self, void *) {
1850 uint32_t timestamp : 30;
1851 uint32_t ignored : 1;
1852 uint32_t upgradable : 1;
1856 bool upgradable([self upgradableAndEssential:YES]);
1857 value.bits.upgradable = upgradable ? 1 : 0;
1860 value.bits.timestamp = 0;
1861 value.bits.ignored = [self ignored] ? 0 : 1;
1862 value.bits.upgradable = 1;
1864 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1865 value.bits.ignored = 0;
1866 value.bits.upgradable = 0;
1869 return _not(uint32_t) - value.key;
1872 _finline static void Stifle(uint8_t &value) {
1875 uint32_t PackagePrefixRadix(Package *self, void *context) {
1876 size_t offset(reinterpret_cast<size_t>(context));
1877 CYString &name([self cyname]);
1879 size_t size(name.size());
1882 char *text(name.data());
1885 if (!isdigit(text[0]))
1889 while (size != digits && isdigit(text[digits]))
1899 if (offset == 0 && zeros != 0) {
1900 memset(data, '0', zeros);
1901 memcpy(data + zeros, text, 4 - zeros);
1903 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1904 if (size <= offset - zeros)
1907 text += offset - zeros;
1908 size -= offset - zeros;
1911 memcpy(data, text, 4);
1913 memcpy(data, text, size);
1914 memset(data + size, 0, 4 - size);
1917 for (size_t i(0); i != 4; ++i)
1918 if (isalpha(data[i]))
1923 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1925 /* XXX: ntohl may be more honest */
1926 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1929 CYString &(*PackageName)(Package *self, SEL sel);
1931 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1932 _profile(PackageNameCompare)
1933 CYString &lhi(PackageName(lhs, @selector(cyname)));
1934 CYString &rhi(PackageName(rhs, @selector(cyname)));
1935 CFStringRef lhn(lhi), rhn(rhi);
1938 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1939 else if (rhn == NULL)
1940 return NSOrderedDescending;
1942 _profile(PackageNameCompare$NumbersLast)
1943 if (!lhi.empty() && !rhi.empty()) {
1944 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1945 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1946 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1947 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1948 return lha ? NSOrderedAscending : NSOrderedDescending;
1952 CFIndex length = CFStringGetLength(lhn);
1954 _profile(PackageNameCompare$Compare)
1955 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1960 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1961 return PackageNameCompare(*lhs, *rhs, context);
1964 struct PackageNameOrdering :
1965 std::binary_function<Package *, Package *, bool>
1967 _finline bool operator ()(Package *lhs, Package *rhs) const {
1968 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1972 @implementation Package
1974 - (NSString *) description {
1975 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1981 if (section$_ != nil)
1982 [section$_ release];
1987 if (sponsor$_ != nil)
1988 [sponsor$_ release];
1989 if (author$_ != nil)
1996 if (relationships_ != nil)
1997 [relationships_ release];
1998 if (metadata_ != nil)
1999 [metadata_ release];
2004 + (NSString *) webScriptNameForSelector:(SEL)selector {
2005 if (selector == @selector(hasTag:))
2011 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2012 return [self webScriptNameForSelector:selector] == nil;
2015 + (NSArray *) _attributeKeys {
2016 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];
2019 - (NSArray *) attributeKeys {
2020 return [[self class] _attributeKeys];
2023 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2024 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2034 _profile(Package$parse)
2035 pkgRecords::Parser *parser;
2037 _profile(Package$parse$Lookup)
2038 parser = &[database_ records]->Lookup(file_);
2043 _profile(Package$parse$Find)
2049 {"depiction", &depiction_},
2050 {"homepage", &homepage_},
2051 {"website", &website},
2053 {"support", &support_},
2054 {"sponsor", &sponsor_},
2055 {"author", &author_},
2058 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2059 const char *start, *end;
2061 if (parser->Find(names[i].name_, start, end)) {
2062 CYString &value(*names[i].value_);
2063 _profile(Package$parse$Value)
2064 value.set(pool_, start, end - start);
2070 _profile(Package$parse$Tagline)
2071 const char *start, *end;
2072 if (parser->ShortDesc(start, end)) {
2073 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2076 while (stop != start && stop[-1] == '\r')
2078 tagline_.set(pool_, start, stop - start);
2082 _profile(Package$parse$Retain)
2083 if (homepage_.empty())
2084 homepage_ = website;
2085 if (homepage_ == depiction_)
2091 - (void) setVisible {
2092 visible_ = required_ && [self hasSupportingRole] && [self unfiltered];
2095 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2096 if ((self = [super init]) != nil) {
2097 _profile(Package$initWithVersion)
2098 @synchronized (database) {
2099 era_ = [database era];
2103 iterator_ = version.ParentPkg();
2104 database_ = database;
2106 _profile(Package$initWithVersion$Latest)
2107 latest_ = (NSString *) StripVersion(version_.VerStr());
2110 pkgCache::VerIterator current;
2111 _profile(Package$initWithVersion$Versions)
2112 current = iterator_.CurrentVer();
2114 installed_.set(pool_, StripVersion_(current.VerStr()));
2116 if (!version_.end())
2117 file_ = version_.FileList();
2119 pkgCache &cache([database_ cache]);
2120 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2124 _profile(Package$initWithVersion$Name)
2125 id_.set(pool_, iterator_.Name());
2126 name_.set(pool, iterator_.Display());
2130 _profile(Package$initWithVersion$Source)
2131 source_ = [database_ getSource:file_.File()];
2140 _profile(Package$initWithVersion$Tags)
2141 pkgCache::TagIterator tag(iterator_.TagList());
2143 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2145 const char *name(tag.Name());
2146 [tags_ addObject:(NSString *)CFCString(name)];
2147 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2148 role_ = (NSString *) CFCString(name + 6);
2149 if (required_ && strncmp(name, "require::", 9) == 0 && (
2154 } while (!tag.end());
2158 bool changed(false);
2159 NSString *key([id_ lowercaseString]);
2161 _profile(Package$initWithVersion$Metadata)
2162 metadata_ = [Packages_ objectForKey:key];
2164 if (metadata_ == nil) {
2167 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2168 firstSeen_, @"FirstSeen",
2169 latest_, @"LastVersion",
2174 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2175 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2177 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2178 subscribed_ = [subscribed boolValue];
2180 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2182 if (firstSeen_ == nil) {
2183 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2184 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2188 if (version == nil) {
2189 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2192 if (![version isEqualToString:latest_]) {
2193 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2195 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2200 metadata_ = [metadata_ retain];
2203 [Packages_ setObject:metadata_ forKey:key];
2208 _profile(Package$initWithVersion$Section)
2209 section_.set(pool_, iterator_.Section());
2212 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2214 } _end } return self;
2217 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2218 @synchronized ([Database class]) {
2219 pkgCache::VerIterator version;
2221 _profile(Package$packageWithIterator$GetCandidateVer)
2222 version = [database policy]->GetCandidateVer(iterator);
2228 return [[[Package alloc]
2229 initWithVersion:version
2236 - (pkgCache::PkgIterator) iterator {
2240 - (NSString *) section {
2241 if (section$_ == nil) {
2242 if (section_.empty())
2245 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2246 NSString *name(section_);
2249 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2250 if (NSString *rename = [value objectForKey:@"Rename"]) {
2255 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2259 - (NSString *) simpleSection {
2260 if (NSString *section = [self section])
2261 return Simplify(section);
2266 - (NSString *) longSection {
2267 return LocalizeSection([self section]);
2270 - (NSString *) shortSection {
2271 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2274 - (NSString *) uri {
2277 pkgIndexFile *index;
2278 pkgCache::PkgFileIterator file(file_.File());
2279 if (![database_ list].FindIndex(file, index))
2281 return [NSString stringWithUTF8String:iterator_->Path];
2282 //return [NSString stringWithUTF8String:file.Site()];
2283 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2287 - (Address *) maintainer {
2290 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2291 const std::string &maintainer(parser->Maintainer());
2292 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2296 return version_.end() ? 0 : version_->InstalledSize;
2299 - (NSString *) longDescription {
2302 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2303 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2305 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2306 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2307 if ([lines count] < 2)
2310 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2311 for (size_t i(1), e([lines count]); i != e; ++i) {
2312 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2313 [trimmed addObject:trim];
2316 return [trimmed componentsJoinedByString:@"\n"];
2319 - (NSString *) shortDescription {
2324 _profile(Package$index)
2325 CFStringRef name((CFStringRef) [self name]);
2326 if (CFStringGetLength(name) == 0)
2328 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2329 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2331 return toupper(character);
2335 - (NSMutableDictionary *) metadata {
2340 if (subscribed_ && lastSeen_ != nil)
2345 - (BOOL) subscribed {
2350 NSDictionary *metadata([self metadata]);
2351 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2352 return [ignored boolValue];
2357 - (NSString *) latest {
2361 - (NSString *) installed {
2365 - (BOOL) uninstalled {
2366 return installed_.empty();
2370 return !version_.end();
2373 - (BOOL) upgradableAndEssential:(BOOL)essential {
2374 _profile(Package$upgradableAndEssential)
2375 pkgCache::VerIterator current(iterator_.CurrentVer());
2377 return essential && essential_ && visible_;
2379 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2383 - (BOOL) essential {
2388 return [database_ cache][iterator_].InstBroken();
2391 - (BOOL) unfiltered {
2392 NSString *section([self section]);
2393 return section == nil || isSectionVisible(section);
2401 unsigned char current(iterator_->CurrentState);
2402 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2405 - (BOOL) halfConfigured {
2406 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2409 - (BOOL) halfInstalled {
2410 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2414 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2415 return state.Mode != pkgDepCache::ModeKeep;
2418 - (NSString *) mode {
2419 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2421 switch (state.Mode) {
2422 case pkgDepCache::ModeDelete:
2423 if ((state.iFlags & pkgDepCache::Purge) != 0)
2427 case pkgDepCache::ModeKeep:
2428 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2429 return @"REINSTALL";
2430 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2434 case pkgDepCache::ModeInstall:
2435 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2436 return @"REINSTALL";
2437 else*/ switch (state.Status) {
2439 return @"DOWNGRADE";
2445 return @"NEW_INSTALL";
2456 - (NSString *) name {
2457 return name_.empty() ? id_ : name_;
2460 - (UIImage *) icon {
2461 NSString *section = [self simpleSection];
2465 if ([icon_ hasPrefix:@"file:///"])
2466 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2467 if (icon == nil) if (section != nil)
2468 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2469 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2470 if ([dicon hasPrefix:@"file:///"])
2471 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2473 icon = [UIImage applicationImageNamed:@"unknown.png"];
2477 - (NSString *) homepage {
2481 - (NSString *) depiction {
2482 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2485 - (Address *) sponsor {
2486 if (sponsor$_ == nil) {
2487 if (sponsor_.empty())
2489 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2493 - (Address *) author {
2494 if (author$_ == nil) {
2495 if (author_.empty())
2497 author$_ = [[Address addressWithString:author_] retain];
2501 - (NSString *) support {
2502 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2505 - (NSArray *) files {
2506 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2507 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2510 fin.open([path UTF8String]);
2515 while (std::getline(fin, line))
2516 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2521 - (NSArray *) relationships {
2522 return relationships_;
2525 - (NSArray *) warnings {
2526 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2527 const char *name(iterator_.Name());
2529 size_t length(strlen(name));
2530 if (length < 2) invalid:
2531 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2532 else for (size_t i(0); i != length; ++i)
2534 /* XXX: technically this is not allowed */
2535 (name[i] < 'A' || name[i] > 'Z') &&
2536 (name[i] < 'a' || name[i] > 'z') &&
2537 (name[i] < '0' || name[i] > '9') &&
2538 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2541 if (strcmp(name, "cydia") != 0) {
2544 bool _private = false;
2547 bool repository = [[self section] isEqualToString:@"Repositories"];
2549 if (NSArray *files = [self files])
2550 for (NSString *file in files)
2551 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2553 else if (!user && [file isEqualToString:@"/User"])
2555 else if (!_private && [file isEqualToString:@"/private"])
2557 else if (!stash && [file isEqualToString:@"/var/stash"])
2560 /* XXX: this is not sensitive enough. only some folders are valid. */
2561 if (cydia && !repository)
2562 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2564 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2566 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2568 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2571 return [warnings count] == 0 ? nil : warnings;
2574 - (NSArray *) applications {
2575 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2577 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2579 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2580 if (NSArray *files = [self files])
2581 for (NSString *file in files)
2582 if (application_r(file)) {
2583 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2584 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2585 if ([id isEqualToString:me])
2588 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2590 display = application_r[1];
2592 NSString *bundle([file stringByDeletingLastPathComponent]);
2593 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2594 if (icon == nil || [icon length] == 0)
2596 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2598 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2599 [applications addObject:application];
2601 [application addObject:id];
2602 [application addObject:display];
2603 [application addObject:url];
2606 return [applications count] == 0 ? nil : applications;
2609 - (Source *) source {
2611 @synchronized (database_) {
2612 if ([database_ era] != era_ || file_.end())
2615 source_ = [database_ getSource:file_.File()];
2627 - (NSString *) role {
2631 - (BOOL) matches:(NSString *)text {
2637 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2638 if (range.location != NSNotFound)
2641 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2642 if (range.location != NSNotFound)
2645 /* range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2646 if (range.location != NSNotFound)
2652 - (bool) hasSupportingRole {
2655 if ([role_ isEqualToString:@"enduser"])
2657 if ([Role_ isEqualToString:@"User"])
2659 if ([role_ isEqualToString:@"hacker"])
2661 if ([Role_ isEqualToString:@"Hacker"])
2663 if ([role_ isEqualToString:@"developer"])
2665 if ([Role_ isEqualToString:@"Developer"])
2670 - (BOOL) hasTag:(NSString *)tag {
2671 return tags_ == nil ? NO : [tags_ containsObject:tag];
2674 - (NSString *) primaryPurpose {
2675 for (NSString *tag in tags_)
2676 if ([tag hasPrefix:@"purpose::"])
2677 return [tag substringFromIndex:9];
2681 - (NSArray *) purposes {
2682 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2683 for (NSString *tag in tags_)
2684 if ([tag hasPrefix:@"purpose::"])
2685 [purposes addObject:[tag substringFromIndex:9]];
2686 return [purposes count] == 0 ? nil : purposes;
2689 - (bool) isCommercial {
2690 return [self hasTag:@"cydia::commercial"];
2693 - (CYString &) cyname {
2694 return name_.empty() ? id_ : name_;
2697 - (uint32_t) compareBySection:(NSArray *)sections {
2698 NSString *section([self section]);
2699 for (size_t i(0), e([sections count]); i != e; ++i) {
2700 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2704 return _not(uint32_t);
2707 - (uint32_t) compareForChanges {
2712 uint32_t timestamp : 30;
2713 uint32_t ignored : 1;
2714 uint32_t upgradable : 1;
2718 bool upgradable([self upgradableAndEssential:YES]);
2719 value.bits.upgradable = upgradable ? 1 : 0;
2722 value.bits.timestamp = 0;
2723 value.bits.ignored = [self ignored] ? 0 : 1;
2724 value.bits.upgradable = 1;
2726 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2727 value.bits.ignored = 0;
2728 value.bits.upgradable = 0;
2731 return _not(uint32_t) - value.key;
2735 pkgProblemResolver *resolver = [database_ resolver];
2736 resolver->Clear(iterator_);
2737 resolver->Protect(iterator_);
2741 pkgProblemResolver *resolver = [database_ resolver];
2742 resolver->Clear(iterator_);
2743 resolver->Protect(iterator_);
2744 pkgCacheFile &cache([database_ cache]);
2745 cache->MarkInstall(iterator_, false);
2746 pkgDepCache::StateCache &state((*cache)[iterator_]);
2747 if (!state.Install())
2748 cache->SetReInstall(iterator_, true);
2752 pkgProblemResolver *resolver = [database_ resolver];
2753 resolver->Clear(iterator_);
2754 resolver->Protect(iterator_);
2755 resolver->Remove(iterator_);
2756 [database_ cache]->MarkDelete(iterator_, true);
2759 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2760 _profile(Package$isUnfilteredAndSearchedForBy)
2763 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2764 value &= [self unfiltered];
2767 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2768 value &= [self matches:search];
2775 - (bool) isInstalledAndVisible:(NSNumber *)number {
2776 return (![number boolValue] || [self visible]) && ![self uninstalled];
2779 - (bool) isVisibleInSection:(NSString *)name {
2780 NSString *section = [self section];
2785 section == nil && [name length] == 0 ||
2786 [name isEqualToString:section]
2790 - (bool) isVisibleInSource:(Source *)source {
2791 return [self source] == source && [self visible];
2796 /* Section Class {{{ */
2797 @interface Section : NSObject {
2802 NSString *localized_;
2805 - (NSComparisonResult) compareByLocalized:(Section *)section;
2806 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2807 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2808 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2809 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2810 - (NSString *) name;
2817 - (void) addToCount;
2819 - (void) setCount:(size_t)count;
2820 - (NSString *) localized;
2824 @implementation Section
2828 if (localized_ != nil)
2829 [localized_ release];
2833 - (NSComparisonResult) compareByLocalized:(Section *)section {
2834 NSString *lhs(localized_);
2835 NSString *rhs([section localized]);
2837 /*if ([lhs length] != 0 && [rhs length] != 0) {
2838 unichar lhc = [lhs characterAtIndex:0];
2839 unichar rhc = [rhs characterAtIndex:0];
2841 if (isalpha(lhc) && !isalpha(rhc))
2842 return NSOrderedAscending;
2843 else if (!isalpha(lhc) && isalpha(rhc))
2844 return NSOrderedDescending;
2847 return [lhs compare:rhs options:LaxCompareOptions_];
2850 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2851 if ((self = [self initWithName:name localize:NO]) != nil) {
2852 if (localized != nil)
2853 localized_ = [localized retain];
2857 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2858 return [self initWithName:name row:0 localize:localize];
2861 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2862 if ((self = [super init]) != nil) {
2863 name_ = [name retain];
2867 localized_ = [LocalizeSection(name_) retain];
2871 /* XXX: localize the index thingees */
2872 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2873 if ((self = [super init]) != nil) {
2874 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2880 - (NSString *) name {
2900 - (void) addToCount {
2904 - (void) setCount:(size_t)count {
2908 - (NSString *) localized {
2915 static NSString *Colon_;
2916 static NSString *Error_;
2917 static NSString *Warning_;
2919 /* Database Implementation {{{ */
2920 @implementation Database
2922 + (Database *) sharedInstance {
2923 static Database *instance;
2924 if (instance == nil)
2925 instance = [[Database alloc] init];
2935 NSRecycleZone(zone_);
2936 // XXX: malloc_destroy_zone(zone_);
2937 apr_pool_destroy(pool_);
2941 - (void) _readCydia:(NSNumber *)fd { _pooled
2942 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2943 std::istream is(&ib);
2946 static Pcre finish_r("^finish:([^:]*)$");
2948 while (std::getline(is, line)) {
2949 const char *data(line.c_str());
2950 size_t size = line.size();
2951 lprintf("C:%s\n", data);
2953 if (finish_r(data, size)) {
2954 NSString *finish = finish_r[1];
2955 int index = [Finishes_ indexOfObject:finish];
2956 if (index != INT_MAX && index > Finish_)
2964 - (void) _readStatus:(NSNumber *)fd { _pooled
2965 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2966 std::istream is(&ib);
2969 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2970 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2972 while (std::getline(is, line)) {
2973 const char *data(line.c_str());
2974 size_t size(line.size());
2975 lprintf("S:%s\n", data);
2977 if (conffile_r(data, size)) {
2978 [delegate_ setConfigurationData:conffile_r[1]];
2979 } else if (strncmp(data, "status: ", 8) == 0) {
2980 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2981 [delegate_ setProgressTitle:string];
2982 } else if (pmstatus_r(data, size)) {
2983 std::string type([pmstatus_r[1] UTF8String]);
2984 NSString *id = pmstatus_r[2];
2986 float percent([pmstatus_r[3] floatValue]);
2987 [delegate_ setProgressPercent:(percent / 100)];
2989 NSString *string = pmstatus_r[4];
2991 if (type == "pmerror")
2992 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
2993 withObject:[NSArray arrayWithObjects:string, id, nil]
2996 else if (type == "pmstatus") {
2997 [delegate_ setProgressTitle:string];
2998 } else if (type == "pmconffile")
2999 [delegate_ setConfigurationData:string];
3001 lprintf("E:unknown pmstatus\n");
3003 lprintf("E:unknown status\n");
3009 - (void) _readOutput:(NSNumber *)fd { _pooled
3010 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3011 std::istream is(&ib);
3014 while (std::getline(is, line)) {
3015 lprintf("O:%s\n", line.c_str());
3016 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3026 - (Package *) packageWithName:(NSString *)name {
3027 @synchronized ([Database class]) {
3028 if (static_cast<pkgDepCache *>(cache_) == NULL)
3030 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3031 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3034 - (Database *) init {
3035 if ((self = [super init]) != nil) {
3042 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3043 apr_pool_create(&pool_, NULL);
3045 packages_ = [[NSMutableArray alloc] init];
3049 _assert(pipe(fds) != -1);
3052 _config->Set("APT::Keep-Fds::", cydiafd_);
3053 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3056 detachNewThreadSelector:@selector(_readCydia:)
3058 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3061 _assert(pipe(fds) != -1);
3065 detachNewThreadSelector:@selector(_readStatus:)
3067 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3070 _assert(pipe(fds) != -1);
3071 _assert(dup2(fds[0], 0) != -1);
3072 _assert(close(fds[0]) != -1);
3074 input_ = fdopen(fds[1], "a");
3076 _assert(pipe(fds) != -1);
3077 _assert(dup2(fds[1], 1) != -1);
3078 _assert(close(fds[1]) != -1);
3081 detachNewThreadSelector:@selector(_readOutput:)
3083 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3088 - (pkgCacheFile &) cache {
3092 - (pkgDepCache::Policy *) policy {
3096 - (pkgRecords *) records {
3100 - (pkgProblemResolver *) resolver {
3104 - (pkgAcquire &) fetcher {
3108 - (pkgSourceList &) list {
3112 - (NSArray *) packages {
3116 - (NSArray *) sources {
3117 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3118 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3119 [sources addObject:i->second];
3123 - (NSArray *) issues {
3124 if (cache_->BrokenCount() == 0)
3127 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3129 for (Package *package in packages_) {
3130 if (![package broken])
3132 pkgCache::PkgIterator pkg([package iterator]);
3134 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3135 [entry addObject:[package name]];
3136 [issues addObject:entry];
3138 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3142 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3143 pkgCache::DepIterator start;
3144 pkgCache::DepIterator end;
3145 dep.GlobOr(start, end); // ++dep
3147 if (!cache_->IsImportantDep(end))
3149 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3152 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3153 [entry addObject:failure];
3154 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3156 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3157 if (Package *package = [self packageWithName:name])
3158 name = [package name];
3159 [failure addObject:name];
3161 pkgCache::PkgIterator target(start.TargetPkg());
3162 if (target->ProvidesList != 0)
3163 [failure addObject:@"?"];
3165 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3167 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3168 else if (!cache_[target].CandidateVerIter(cache_).end())
3169 [failure addObject:@"-"];
3170 else if (target->ProvidesList == 0)
3171 [failure addObject:@"!"];
3173 [failure addObject:@"%"];
3177 if (start.TargetVer() != 0)
3178 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3189 - (bool) popErrorWithTitle:(NSString *)title {
3191 std::string message;
3193 while (!_error->empty()) {
3195 bool warning(!_error->PopMessage(error));
3199 size_t size(error.size());
3200 if (size == 0 || error[size - 1] != '\n')
3202 error.resize(size - 1);
3204 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3206 if (!message.empty())
3211 if (fatal && !message.empty())
3212 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3217 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3218 return [self popErrorWithTitle:title] || !success;
3221 - (void) reloadData { _pooled
3222 @synchronized ([Database class]) {
3223 @synchronized (self) {
3227 [packages_ removeAllObjects];
3253 apr_pool_clear(pool_);
3254 NSRecycleZone(zone_);
3256 int chk(creat("/tmp/cydia.chk", 0644));
3260 NSString *title(UCLocalize("DATABASE"));
3263 if (!cache_.Open(progress_, true)) { pop:
3265 bool warning(!_error->PopMessage(error));
3266 lprintf("cache_.Open():[%s]\n", error.c_str());
3268 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3269 [delegate_ repairWithSelector:@selector(configure)];
3270 else if (error == "The package lists or status file could not be parsed or opened.")
3271 [delegate_ repairWithSelector:@selector(update)];
3272 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3273 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3274 // else if (error == "The list of sources could not be read.")
3276 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3285 unlink("/tmp/cydia.chk");
3287 now_ = [[NSDate date] retain];
3289 policy_ = new pkgDepCache::Policy();
3290 records_ = new pkgRecords(cache_);
3291 resolver_ = new pkgProblemResolver(cache_);
3292 fetcher_ = new pkgAcquire(&status_);
3295 list_ = new pkgSourceList();
3296 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3299 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3300 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3304 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3307 if (cache_->BrokenCount() != 0) {
3308 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3311 if (cache_->BrokenCount() != 0) {
3312 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3316 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3322 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3323 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3324 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3325 // XXX: this could be more intelligent
3326 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3327 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3329 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3336 /*std::vector<Package *> packages;
3337 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3338 [packages_ release];
3343 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3344 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3345 //packages.push_back(package);
3346 [packages_ addObject:package];
3350 /*if (packages.empty())
3351 packages_ = [[NSArray alloc] init];
3353 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3356 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3357 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3358 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3366 /*if (!packages.empty())
3367 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3368 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3370 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3372 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3374 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3380 - (void) configure {
3381 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3382 system([dpkg UTF8String]);
3386 // XXX: I don't remember this condition
3391 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3393 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3395 if ([self popErrorWithTitle:title])
3399 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3402 public pkgArchiveCleaner
3405 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3410 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3417 fetcher_->Shutdown();
3419 pkgRecords records(cache_);
3421 lock_ = new FileFd();
3422 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3424 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3426 if ([self popErrorWithTitle:title])
3430 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3433 manager_ = (_system->CreatePM(cache_));
3434 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3441 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3443 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3445 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3447 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3448 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3451 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3456 bool failed = false;
3457 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3458 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3460 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3463 std::string uri = (*item)->DescURI();
3464 std::string error = (*item)->ErrorText;
3466 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3469 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3470 withObject:[NSArray arrayWithObjects:
3471 [NSString stringWithUTF8String:error.c_str()],
3483 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3485 if (_error->PendingError()) {
3490 if (result == pkgPackageManager::Failed) {
3495 if (result != pkgPackageManager::Completed) {
3500 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3502 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3504 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3505 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3508 if (![before isEqualToArray:after])
3513 NSString *title(UCLocalize("UPGRADE"));
3514 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3520 [self updateWithStatus:status_];
3523 - (void) setVisible {
3524 for (Package *package in packages_)
3525 [package setVisible];
3528 - (void) updateWithStatus:(Status &)status {
3529 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3530 NSString *title(UCLocalize("REFRESHING_DATA"));
3533 if (!list.ReadMainList())
3534 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3537 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3538 if ([self popErrorWithTitle:title])
3541 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3542 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */;
3544 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3548 - (void) setDelegate:(id)delegate {
3549 delegate_ = delegate;
3550 status_.setDelegate(delegate);
3551 progress_.setDelegate(delegate);
3554 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3555 SourceMap::const_iterator i(sources_.find(file->ID));
3556 return i == sources_.end() ? nil : i->second;
3562 /* Confirmation View {{{ */
3563 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3564 if (!iterator.end())
3565 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3566 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3568 pkgCache::PkgIterator package(dep.TargetPkg());
3571 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3578 /* Web Scripting {{{ */
3579 @interface CydiaObject : NSObject {
3583 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3586 @implementation CydiaObject
3589 [indirect_ release];
3593 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3594 if ((self = [super init]) != nil) {
3595 indirect_ = [indirect retain];
3599 + (NSArray *) _attributeKeys {
3600 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3603 - (NSArray *) attributeKeys {
3604 return [[self class] _attributeKeys];
3607 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3608 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3611 - (NSString *) device {
3612 return [[UIDevice currentDevice] uniqueIdentifier];
3615 #if 0 // XXX: implement!
3616 - (NSString *) mac {
3617 if (![indirect_ promptForSensitive:@"Mac Address"])
3621 - (NSString *) serial {
3622 if (![indirect_ promptForSensitive:@"Serial #"])
3626 - (NSString *) firewire {
3627 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3631 - (NSString *) imei {
3632 if (![indirect_ promptForSensitive:@"IMEI"])
3637 + (NSString *) webScriptNameForSelector:(SEL)selector {
3638 if (selector == @selector(close))
3640 else if (selector == @selector(getInstalledPackages))
3641 return @"getInstalledPackages";
3642 else if (selector == @selector(getPackageById:))
3643 return @"getPackageById";
3644 else if (selector == @selector(setAutoPopup:))
3645 return @"setAutoPopup";
3646 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3647 return @"setButtonImage";
3648 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3649 return @"setButtonTitle";
3650 else if (selector == @selector(setFinishHook:))
3651 return @"setFinishHook";
3652 else if (selector == @selector(setPopupHook:))
3653 return @"setPopupHook";
3654 else if (selector == @selector(setSpecial:))
3655 return @"setSpecial";
3656 else if (selector == @selector(setViewportWidth:))
3657 return @"setViewportWidth";
3658 else if (selector == @selector(supports:))
3660 else if (selector == @selector(stringWithFormat:arguments:))
3662 else if (selector == @selector(localizedStringForKey:value:table:))
3664 else if (selector == @selector(du:))
3666 else if (selector == @selector(statfs:))
3672 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3673 return [self webScriptNameForSelector:selector] == nil;
3676 - (BOOL) supports:(NSString *)feature {
3677 return [feature isEqualToString:@"window.open"];
3680 - (NSArray *) getInstalledPackages {
3681 NSArray *packages([[Database sharedInstance] packages]);
3682 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3683 for (Package *package in installed)
3684 if ([package installed] != nil)
3685 [installed addObject:package];
3689 - (Package *) getPackageById:(NSString *)id {
3690 Package *package([[Database sharedInstance] packageWithName:id]);
3695 - (NSArray *) statfs:(NSString *)path {
3698 if (path == nil || statfs([path UTF8String], &stat) == -1)
3701 return [NSArray arrayWithObjects:
3702 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3703 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3704 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3708 - (NSNumber *) du:(NSString *)path {
3709 NSNumber *value(nil);
3712 _assert(pipe(fds) != -1);
3714 pid_t pid(ExecFork());
3716 _assert(dup2(fds[1], 1) != -1);
3717 _assert(close(fds[0]) != -1);
3718 _assert(close(fds[1]) != -1);
3719 /* XXX: this should probably not use du */
3720 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3725 _assert(close(fds[1]) != -1);
3727 if (FILE *du = fdopen(fds[0], "r")) {
3729 while (fgets(line, sizeof(line), du) != NULL) {
3730 size_t length(strlen(line));
3731 while (length != 0 && line[length - 1] == '\n')
3732 line[--length] = '\0';
3733 if (char *tab = strchr(line, '\t')) {
3735 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3740 } else _assert(close(fds[0]));
3744 if (waitpid(pid, &status, 0) == -1)
3747 else _assert(false);
3756 - (void) setAutoPopup:(BOOL)popup {
3757 [indirect_ setAutoPopup:popup];
3760 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3761 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3764 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3765 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3768 - (void) setSpecial:(id)function {
3769 [indirect_ setSpecial:function];
3772 - (void) setFinishHook:(id)function {
3773 [indirect_ setFinishHook:function];
3776 - (void) setPopupHook:(id)function {
3777 [indirect_ setPopupHook:function];
3780 - (void) setViewportWidth:(float)width {
3781 [indirect_ setViewportWidth:width];
3784 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3785 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3786 unsigned count([arguments count]);
3788 for (unsigned i(0); i != count; ++i)
3789 values[i] = [arguments objectAtIndex:i];
3790 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3793 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3794 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3796 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3798 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3804 @interface CydiaBrowserView : BrowserView {
3805 CydiaObject *cydia_;
3810 @implementation CydiaBrowserView
3817 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3818 [super webView:sender didClearWindowObject:window forFrame:frame];
3819 [window setValue:cydia_ forKey:@"cydia"];
3822 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3823 if (System_ != NULL)
3824 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3825 if (Machine_ != NULL)
3826 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3827 if (UniqueID_ != nil)
3828 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
3830 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3833 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3834 NSMutableURLRequest *copy = [request mutableCopy];
3835 [self _setMoreHeaders:copy];
3839 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
3840 if ((self = [super initWithBook:book forWidth:width ofClass:[CydiaBrowserView class]]) != nil) {
3841 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3843 WebView *webview([webview_ webView]);
3845 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3847 NSString *application = package == nil ? @"Cydia" : [NSString
3848 stringWithFormat:@"Cydia/%@",
3853 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3855 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3856 if (Product_ != nil)
3857 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3859 [webview setApplicationNameForUserAgent:application];
3865 @protocol ConfirmationViewDelegate
3871 @interface ConfirmationView : CydiaBrowserView {
3872 _transient Database *database_;
3873 UIActionSheet *essential_;
3880 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3884 @implementation ConfirmationView
3891 if (essential_ != nil)
3892 [essential_ release];
3898 [book_ popFromSuperviewAnimated:YES];
3901 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3902 NSString *context([sheet context]);
3904 if ([context isEqualToString:@"remove"]) {
3912 [delegate_ confirm];
3918 } else if ([context isEqualToString:@"unable"]) {
3922 [super alertSheet:sheet buttonClicked:button];
3925 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3926 [super webView:sender didClearWindowObject:window forFrame:frame];
3927 [window setValue:changes_ forKey:@"changes"];
3928 [window setValue:issues_ forKey:@"issues"];
3929 [window setValue:sizes_ forKey:@"sizes"];
3932 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3933 if ((self = [super initWithBook:book]) != nil) {
3934 database_ = database;
3936 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3937 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3938 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3939 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3940 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3944 pkgDepCache::Policy *policy([database_ policy]);
3946 pkgCacheFile &cache([database_ cache]);
3947 NSArray *packages = [database_ packages];
3948 for (Package *package in packages) {
3949 pkgCache::PkgIterator iterator = [package iterator];
3950 pkgDepCache::StateCache &state(cache[iterator]);
3952 NSString *name([package name]);
3954 if (state.NewInstall())
3955 [installing addObject:name];
3956 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3957 [reinstalling addObject:name];
3958 else if (state.Upgrade())
3959 [upgrading addObject:name];
3960 else if (state.Downgrade())
3961 [downgrading addObject:name];
3962 else if (state.Delete()) {
3963 if ([package essential])
3965 [removing addObject:name];
3968 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3969 substrate_ |= DepSubstrate(iterator.CurrentVer());
3974 else if (Advanced_) {
3975 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
3977 essential_ = [[UIActionSheet alloc]
3978 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
3979 buttons:[NSArray arrayWithObjects:
3980 [NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")],
3981 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
3983 defaultButtonIndex:0
3988 [essential_ setDestructiveButtonIndex:1];
3989 [essential_ setBodyText:UCLocalize("REMOVING_ESSENTIALS_EX")];
3991 essential_ = [[UIActionSheet alloc]
3992 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
3993 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
3994 defaultButtonIndex:0
3999 [essential_ setBodyText:UCLocalize("UNABLE_TO_COMPLY_EX")];
4002 changes_ = [[NSArray alloc] initWithObjects:
4010 issues_ = [database_ issues];
4012 issues_ = [issues_ retain];
4014 sizes_ = [[NSArray alloc] initWithObjects:
4015 SizeString([database_ fetcher].FetchNeeded()),
4016 SizeString([database_ fetcher].PartialPresent()),
4017 SizeString([database_ cache]->UsrSize()),
4020 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4024 - (NSString *) backButtonTitle {
4025 return UCLocalize("CONFIRM");
4028 - (NSString *) leftButtonTitle {
4029 return [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")];
4032 - (id) rightButtonTitle {
4033 return issues_ != nil ? nil : [super rightButtonTitle];
4036 - (id) _rightButtonTitle {
4037 #if AlwaysReload || IgnoreInstall
4038 return [super _rightButtonTitle];
4040 return UCLocalize("CONFIRM");
4044 - (void) _leftButtonClicked {
4049 - (void) _rightButtonClicked {
4051 return [super _rightButtonClicked];
4053 if (essential_ != nil)
4054 [essential_ popupAlertAnimated:YES];
4058 [delegate_ confirm];
4066 /* Progress Data {{{ */
4067 @interface ProgressData : NSObject {
4073 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4080 @implementation ProgressData
4082 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4083 if ((self = [super init]) != nil) {
4084 selector_ = selector;
4104 /* Progress View {{{ */
4105 @interface ProgressView : UIView <
4106 ConfigurationDelegate,
4109 _transient Database *database_;
4111 UIView *background_;
4112 UITransitionView *transition_;
4114 UINavigationBar *navbar_;
4115 UIProgressBar *progress_;
4116 UITextView *output_;
4117 UITextLabel *status_;
4118 UIPushButton *close_;
4121 SHA1SumValue springlist_;
4122 SHA1SumValue notifyconf_;
4126 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
4127 - (void) setContentView:(UIView *)view;
4130 - (void) _retachThread;
4131 - (void) _detachNewThreadData:(ProgressData *)data;
4132 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4138 @protocol ProgressViewDelegate
4139 - (void) progressViewIsComplete:(ProgressView *)sender;
4142 @implementation ProgressView
4145 [transition_ setDelegate:nil];
4146 [navbar_ setDelegate:nil];
4149 if (background_ != nil)
4150 [background_ release];
4151 [transition_ release];
4154 [progress_ release];
4163 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
4164 if ((self = [super initWithFrame:frame]) != nil) {
4165 database_ = database;
4166 delegate_ = delegate;
4168 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
4169 [transition_ setDelegate:self];
4171 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
4173 background_ = [[UIView alloc] initWithFrame:[self bounds]];
4174 [background_ setBackgroundColor:[UIColor blackColor]];
4175 [self addSubview:background_];
4177 [self addSubview:transition_];
4179 CGSize navsize = [UINavigationBar defaultSize];
4180 CGRect navrect = {{0, 0}, navsize};
4182 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
4183 [overlay_ addSubview:navbar_];
4185 [navbar_ setBarStyle:1];
4186 [navbar_ setDelegate:self];
4188 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
4189 [navbar_ pushNavigationItem:navitem];
4191 CGRect bounds = [overlay_ bounds];
4192 CGSize prgsize = [UIProgressBar defaultSize];
4195 (bounds.size.width - prgsize.width) / 2,
4196 bounds.size.height - prgsize.height - 20
4199 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
4200 [progress_ setStyle:0];
4202 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
4204 bounds.size.height - prgsize.height - 50,
4205 bounds.size.width - 20,
4209 [status_ setColor:[UIColor whiteColor]];
4210 [status_ setBackgroundColor:[UIColor clearColor]];
4212 [status_ setCentersHorizontally:YES];
4213 //[status_ setFont:font];
4215 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
4217 navrect.size.height + 20,
4218 bounds.size.width - 20,
4219 bounds.size.height - navsize.height - 62 - navrect.size.height
4222 //[output_ setTextFont:@"Courier New"];
4223 [output_ setFont:[[output_ font] fontWithSize:12]];
4225 [output_ setTextColor:[UIColor whiteColor]];
4226 [output_ setBackgroundColor:[UIColor clearColor]];
4228 [output_ setMarginTop:0];
4229 [output_ setAllowsRubberBanding:YES];
4230 [output_ setEditable:NO];
4232 [overlay_ addSubview:output_];
4234 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
4236 bounds.size.height - prgsize.height - 50,
4237 bounds.size.width - 20,
4241 [close_ setAutosizesToFit:NO];
4242 [close_ setDrawsShadow:YES];
4243 [close_ setStretchBackground:YES];
4244 [close_ setEnabled:YES];
4246 UIFont *bold = [UIFont boldSystemFontOfSize:22];
4247 [close_ setTitleFont:bold];
4249 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4250 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4251 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4255 - (void) setContentView:(UIView *)view {
4256 view_ = [view retain];
4259 - (void) resetView {
4260 [transition_ transition:6 toView:view_];
4263 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4264 NSString *context([sheet context]);
4266 if ([context isEqualToString:@"conffile"]) {
4267 FILE *input = [database_ input];
4271 fprintf(input, "N\n");
4275 fprintf(input, "Y\n");
4285 - (void) closeButtonPushed {
4294 [delegate_ terminateWithSuccess];
4295 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4296 [delegate_ suspendWithAnimation:YES];
4298 [delegate_ suspend];*/
4302 system("launchctl stop com.apple.SpringBoard");
4306 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4315 - (void) _retachThread {
4316 UINavigationItem *item([navbar_ topItem]);
4317 [item setTitle:UCLocalize("COMPLETE")];
4319 [overlay_ addSubview:close_];
4320 [progress_ removeFromSuperview];
4321 [status_ removeFromSuperview];
4323 [database_ popErrorWithTitle:title_];
4324 [delegate_ progressViewIsComplete:self];
4328 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4331 MMap mmap(file, MMap::ReadOnly);
4333 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4334 if (!(notifyconf_ == sha1.Result()))
4341 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4344 MMap mmap(file, MMap::ReadOnly);
4346 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4347 if (!(springlist_ == sha1.Result()))
4353 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break;
4354 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4355 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4356 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4357 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4360 #define ListCache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4361 #define IconCache_ "/User/Library/Caches/com.apple.springboard-imagecache-icons.plist"
4365 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ListCache_]) {
4366 [cache autorelease];
4368 NSFileManager *manager([NSFileManager defaultManager]);
4369 NSError *error(nil);
4371 id system([cache objectForKey:@"System"]);
4376 if (stat(ListCache_, &info) == -1)
4379 [system removeAllObjects];
4381 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4382 for (NSString *app in apps)
4383 if ([app hasSuffix:@".app"]) {
4384 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4385 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4386 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4388 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4389 [info setObject:path forKey:@"Path"];
4390 [info setObject:@"System" forKey:@"ApplicationType"];
4391 [system addInfoDictionary:info];
4397 [cache writeToFile:@ListCache_ atomically:YES];
4399 if (chown(ListCache_, info.st_uid, info.st_gid) == -1)
4401 if (chmod(ListCache_, info.st_mode) == -1)
4405 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4408 notify_post("com.apple.mobile.application_installed");
4410 [delegate_ setStatusBarShowsProgress:NO];
4413 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4414 [[data target] performSelector:[data selector] withObject:[data object]];
4417 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4420 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4426 title_ = [title retain];
4428 UINavigationItem *item([navbar_ topItem]);
4429 [item setTitle:title_];
4431 [status_ setText:nil];
4432 [output_ setText:@""];
4433 [progress_ setProgress:0];
4435 [close_ removeFromSuperview];
4436 [overlay_ addSubview:progress_];
4437 [overlay_ addSubview:status_];
4439 [delegate_ setStatusBarShowsProgress:YES];
4444 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4447 MMap mmap(file, MMap::ReadOnly);
4449 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4450 notifyconf_ = sha1.Result();
4456 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4459 MMap mmap(file, MMap::ReadOnly);
4461 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4462 springlist_ = sha1.Result();
4466 [transition_ transition:6 toView:overlay_];
4469 detachNewThreadSelector:@selector(_detachNewThreadData:)
4471 withObject:[[ProgressData alloc]
4472 initWithSelector:selector
4479 - (void) repairWithSelector:(SEL)selector {
4481 detachNewThreadSelector:selector
4484 title:UCLocalize("REPAIRING")
4488 - (void) setConfigurationData:(NSString *)data {
4490 performSelectorOnMainThread:@selector(_setConfigurationData:)
4496 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4497 CYActionSheet *sheet([[[CYActionSheet alloc]
4499 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4500 defaultButtonIndex:0
4503 [sheet setBodyText:error];
4504 [sheet yieldToPopupAlertAnimated:YES];
4508 - (void) setProgressTitle:(NSString *)title {
4510 performSelectorOnMainThread:@selector(_setProgressTitle:)
4516 - (void) setProgressPercent:(float)percent {
4518 performSelectorOnMainThread:@selector(_setProgressPercent:)
4519 withObject:[NSNumber numberWithFloat:percent]
4524 - (void) startProgress {
4527 - (void) addProgressOutput:(NSString *)output {
4529 performSelectorOnMainThread:@selector(_addProgressOutput:)
4535 - (bool) isCancelling:(size_t)received {
4539 - (void) _setConfigurationData:(NSString *)data {
4540 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4542 if (!conffile_r(data)) {
4543 lprintf("E:invalid conffile\n");
4547 NSString *ofile = conffile_r[1];
4548 //NSString *nfile = conffile_r[2];
4550 UIActionSheet *sheet = [[[UIActionSheet alloc]
4551 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4552 buttons:[NSArray arrayWithObjects:
4553 UCLocalize("KEEP_OLD_COPY"),
4554 UCLocalize("ACCEPT_NEW_COPY"),
4555 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4557 defaultButtonIndex:0
4562 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4563 [sheet popupAlertAnimated:YES];
4566 - (void) _setProgressTitle:(NSString *)title {
4567 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4568 for (size_t i(0), e([words count]); i != e; ++i) {
4569 NSString *word([words objectAtIndex:i]);
4570 if (Package *package = [database_ packageWithName:word])
4571 [words replaceObjectAtIndex:i withObject:[package name]];
4574 [status_ setText:[words componentsJoinedByString:@" "]];
4577 - (void) _setProgressPercent:(NSNumber *)percent {
4578 [progress_ setProgress:[percent floatValue]];
4581 - (void) _addProgressOutput:(NSString *)output {
4582 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4583 CGSize size = [output_ contentSize];
4584 CGRect rect = {{0, size.height}, {size.width, 0}};
4585 [output_ scrollRectToVisible:rect animated:YES];
4588 - (BOOL) isRunning {
4595 /* Package Cell {{{ */
4596 @interface ContentView : UIView {
4597 _transient id delegate_;
4602 @interface PackageCell : UITableViewCell {
4605 NSString *description_;
4611 ContentView *content_;
4617 - (PackageCell *) init;
4618 - (void) setPackage:(Package *)package;
4620 + (int) heightForPackage:(Package *)package;
4621 - (void) drawContentRect:(CGRect)rect;
4625 @implementation ContentView
4627 - (id) initWithFrame:(CGRect)frame {
4628 if ((self = [super initWithFrame:frame]) != nil) {
4632 - (void) setDelegate:(id)delegate {
4633 delegate_ = delegate;
4636 - (void) drawRect:(CGRect)rect {
4637 [super drawRect:rect];
4638 [delegate_ drawContentRect:rect];
4643 @implementation PackageCell
4645 - (void) clearPackage {
4656 if (description_ != nil) {
4657 [description_ release];
4661 if (source_ != nil) {
4666 if (badge_ != nil) {
4671 if (placard_ != nil) {
4681 [self clearPackage];
4688 return faded_ ? [self selectionPercent] : fade_;
4691 - (PackageCell *) init {
4692 CGRect frame(CGRectMake(0, 0, 320, 74));
4693 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4694 UIView *content([self contentView]);
4695 CGRect bounds([content bounds]);
4696 content_ = [[ContentView alloc] initWithFrame:bounds];
4697 [content_ setDelegate:self];
4698 [content_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
4699 [content_ setOpaque:YES];
4700 [content addSubview:content_];
4701 if ([self respondsToSelector:@selector(selectionPercent)])
4706 - (void) _setBackgroundColor {
4708 if (NSString *mode = [package_ mode]) {
4709 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4710 color = remove ? RemovingColor_ : InstallingColor_;
4712 color = [UIColor whiteColor];
4714 [content_ setBackgroundColor:color];
4715 [self setNeedsDisplay];
4718 - (void) setPackage:(Package *)package {
4719 [self clearPackage];
4722 Source *source = [package source];
4724 icon_ = [[package icon] retain];
4725 name_ = [[package name] retain];
4726 description_ = [[package shortDescription] retain];
4727 commercial_ = [package isCommercial];
4729 package_ = [package retain];
4731 NSString *label = nil;
4732 bool trusted = false;
4734 if (source != nil) {
4735 label = [source label];
4736 trusted = [source trusted];
4737 } else if ([[package id] isEqualToString:@"firmware"])
4738 label = UCLocalize("APPLE");
4740 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4742 NSString *from(label);
4744 NSString *section = [package simpleSection];
4745 if (section != nil && ![section isEqualToString:label]) {
4746 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4747 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4750 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4751 source_ = [from retain];
4753 if (NSString *purpose = [package primaryPurpose])
4754 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4755 badge_ = [badge_ retain];
4757 if ([package installed] != nil)
4758 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4759 placard_ = [placard_ retain];
4761 [self _setBackgroundColor];
4762 [content_ setNeedsDisplay];
4765 - (void) drawContentRect:(CGRect)rect {
4766 bool selected([self isSelected]);
4769 CGContextRef context(UIGraphicsGetCurrentContext());
4770 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4771 CGContextFillRect(context, rect);
4776 rect.size = [icon_ size];
4778 rect.size.width /= 2;
4779 rect.size.height /= 2;
4781 rect.origin.x = 25 - rect.size.width / 2;
4782 rect.origin.y = 25 - rect.size.height / 2;
4784 [icon_ drawInRect:rect];
4787 if (badge_ != nil) {
4788 CGSize size = [badge_ size];
4790 [badge_ drawAtPoint:CGPointMake(
4791 36 - size.width / 2,
4792 36 - size.height / 2
4800 UISetColor(commercial_ ? Purple_ : Black_);
4801 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(placard_ == nil ? 240 : 214) withFont:Font18Bold_ ellipsis:2];
4802 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4805 UISetColor(commercial_ ? Purplish_ : Gray_);
4806 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:274 withFont:Font14_ ellipsis:2];
4808 if (placard_ != nil)
4809 [placard_ drawAtPoint:CGPointMake(268, 9)];
4812 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4813 //[self _setBackgroundColor];
4814 [super setSelected:selected animated:fade];
4815 [content_ setNeedsDisplay];
4818 + (int) heightForPackage:(Package *)package {
4824 /* Section Cell {{{ */
4825 @interface SectionCell : UISimpleTableCell {
4831 _UISwitchSlider *switch_;
4836 - (void) setSection:(Section *)section editing:(BOOL)editing;
4840 @implementation SectionCell
4842 - (void) clearSection {
4843 if (basic_ != nil) {
4848 if (section_ != nil) {
4858 if (count_ != nil) {
4865 [self clearSection];
4872 if ((self = [super init]) != nil) {
4873 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4875 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4876 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventTouchUpInside];
4880 - (void) onSwitch:(id)sender {
4881 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4882 if (metadata == nil) {
4883 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4884 [Sections_ setObject:metadata forKey:basic_];
4888 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4891 - (void) setSection:(Section *)section editing:(BOOL)editing {
4892 if (editing != editing_) {
4894 [switch_ removeFromSuperview];
4896 [self addSubview:switch_];
4900 [self clearSection];
4902 if (section == nil) {
4903 name_ = [UCLocalize("ALL_PACKAGES") retain];
4906 basic_ = [section name];
4908 basic_ = [basic_ retain];
4910 section_ = [section localized];
4911 if (section_ != nil)
4912 section_ = [section_ retain];
4914 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4915 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4918 [switch_ setValue:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4922 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4923 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4930 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) 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 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5243 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5245 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5247 [self setFinishHook:nil];
5248 [self setPopupHook:nil];
5251 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5252 [super callFunction:special_];
5256 [self reloadButtons];
5259 - (bool) isLoading {
5260 return commercial_ ? [super isLoading] : false;
5263 - (void) reloadData {
5264 [self setPackage:[database_ packageWithName:name_]];
5269 /* Package Table {{{ */
5270 @interface PackageTable : RVPage {
5271 _transient Database *database_;
5273 NSMutableArray *packages_;
5274 NSMutableArray *sections_;
5276 NSMutableArray *index_;
5277 NSMutableDictionary *indices_;
5280 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5282 - (void) setDelegate:(id)delegate;
5284 - (void) reloadData;
5285 - (void) resetCursor;
5287 - (UITableView *) list;
5289 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5293 @implementation PackageTable
5296 [list_ setDataSource:nil];
5299 [packages_ release];
5300 [sections_ release];
5307 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5308 NSInteger count([sections_ count]);
5309 return count == 0 ? 1 : count;
5312 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5313 if ([sections_ count] == 0)
5315 return [[sections_ objectAtIndex:section] name];
5318 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5319 if ([sections_ count] == 0)
5321 return [[sections_ objectAtIndex:section] count];
5324 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5325 Section *section([sections_ objectAtIndex:[path section]]);
5326 NSInteger row([path row]);
5327 Package *package([packages_ objectAtIndex:([section row] + row)]);
5331 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5332 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
5334 cell = [[[PackageCell alloc] init] autorelease];
5335 [cell setPackage:[self packageAtIndexPath:path]];
5339 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5341 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5344 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5345 Package *package([self packageAtIndexPath:path]);
5346 package = [database_ packageWithName:[package id]];
5347 PackageView *view([delegate_ packageView]);
5348 [view setPackage:package];
5349 [view setDelegate:delegate_];
5350 [book_ pushPage:view];
5354 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5355 return [packages_ count] > 20 ? index_ : nil;
5358 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5362 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5363 if ((self = [super initWithBook:book]) != nil) {
5364 database_ = database;
5365 title_ = [title retain];
5367 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5368 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5370 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5371 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5373 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5374 [list_ setDataSource:self];
5375 [list_ setDelegate:self];
5377 [self addSubview:list_];
5379 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5380 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5384 - (void) setDelegate:(id)delegate {
5385 delegate_ = delegate;
5388 - (bool) hasPackage:(Package *)package {
5392 - (void) reloadData {
5393 NSArray *packages = [database_ packages];
5395 [packages_ removeAllObjects];
5396 [sections_ removeAllObjects];
5398 _profile(PackageTable$reloadData$Filter)
5399 for (Package *package in packages)
5400 if ([self hasPackage:package])
5401 [packages_ addObject:package];
5404 [index_ removeAllObjects];
5405 [indices_ removeAllObjects];
5407 Section *section = nil;
5409 _profile(PackageTable$reloadData$Section)
5410 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5414 _profile(PackageTable$reloadData$Section$Package)
5415 package = [packages_ objectAtIndex:offset];
5416 index = [package index];
5419 if (section == nil || [section index] != index) {
5420 _profile(PackageTable$reloadData$Section$Allocate)
5421 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5424 [index_ addObject:[section name]];
5425 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5427 _profile(PackageTable$reloadData$Section$Add)
5428 [sections_ addObject:section];
5432 [section addToCount];
5436 _profile(PackageTable$reloadData$List)
5441 - (NSString *) title {
5445 - (void) resetViewAnimated:(BOOL)animated {
5446 [list_ resetViewAnimated:animated];
5449 - (void) resetCursor {
5450 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5453 - (UITableView *) list {
5457 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5458 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5463 /* Filtered Package Table {{{ */
5464 @interface FilteredPackageTable : PackageTable {
5470 - (void) setObject:(id)object;
5472 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5476 @implementation FilteredPackageTable
5484 - (void) setObject:(id)object {
5490 object_ = [object retain];
5493 - (bool) hasPackage:(Package *)package {
5494 _profile(FilteredPackageTable$hasPackage)
5495 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5499 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5500 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5502 object_ = object == nil ? nil : [object retain];
5504 /* XXX: this is an unsafe optimization of doomy hell */
5505 Method method(class_getInstanceMethod([Package class], filter));
5506 _assert(method != NULL);
5507 imp_ = method_getImplementation(method);
5508 _assert(imp_ != NULL);
5517 /* Add Source View {{{ */
5518 @interface AddSourceView : RVPage {
5519 _transient Database *database_;
5522 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5526 @implementation AddSourceView
5528 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5529 if ((self = [super initWithBook:book]) != nil) {
5530 database_ = database;
5536 /* Source Cell {{{ */
5537 @interface SourceCell : UITableCell {
5540 NSString *description_;
5546 - (SourceCell *) initWithSource:(Source *)source;
5550 @implementation SourceCell
5555 [description_ release];
5560 - (SourceCell *) initWithSource:(Source *)source {
5561 if ((self = [super init]) != nil) {
5563 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5565 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5566 icon_ = [icon_ retain];
5568 origin_ = [[source name] retain];
5569 label_ = [[source uri] retain];
5570 description_ = [[source description] retain];
5574 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5576 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5583 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5587 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5591 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5593 [super drawContentInRect:rect selected:selected];
5598 /* Source Table {{{ */
5599 @interface SourceTable : RVPage {
5600 _transient Database *database_;
5601 UISectionList *list_;
5602 NSMutableArray *sources_;
5603 UIActionSheet *alert_;
5607 UIProgressHUD *hud_;
5610 //NSURLConnection *installer_;
5611 NSURLConnection *trivial_;
5612 NSURLConnection *trivial_bz2_;
5613 NSURLConnection *trivial_gz_;
5614 //NSURLConnection *automatic_;
5619 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5623 @implementation SourceTable
5625 - (void) _deallocConnection:(NSURLConnection *)connection {
5626 if (connection != nil) {
5627 [connection cancel];
5628 //[connection setDelegate:nil];
5629 [connection release];
5634 [[list_ table] setDelegate:nil];
5635 [list_ setDataSource:nil];
5644 //[self _deallocConnection:installer_];
5645 [self _deallocConnection:trivial_];
5646 [self _deallocConnection:trivial_gz_];
5647 [self _deallocConnection:trivial_bz2_];
5648 //[self _deallocConnection:automatic_];
5655 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5656 return offset_ == 0 ? 1 : 2;
5659 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5660 switch (section + (offset_ == 0 ? 1 : 0)) {
5661 case 0: return UCLocalize("ENTERED_BY_USER");
5662 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5668 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5669 switch (section + (offset_ == 0 ? 1 : 0)) {
5671 case 1: return offset_;
5677 - (int) numberOfRowsInTable:(UITable *)table {
5678 return [sources_ count];
5681 - (float) table:(UITable *)table heightForRow:(int)row {
5682 Source *source = [sources_ objectAtIndex:row];
5683 return [source description] == nil ? 56 : 73;
5686 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5687 Source *source = [sources_ objectAtIndex:row];
5688 // XXX: weird warning, stupid selectors ;P
5689 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5692 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5696 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5700 - (void) tableRowSelected:(NSNotification*)notification {
5701 UITable *table([list_ table]);
5702 int row([table selectedRow]);
5706 Source *source = [sources_ objectAtIndex:row];
5708 PackageTable *packages = [[[FilteredPackageTable alloc]
5711 title:[source label]
5712 filter:@selector(isVisibleInSource:)
5716 [packages setDelegate:delegate_];
5718 [book_ pushPage:packages];
5721 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5722 Source *source = [sources_ objectAtIndex:row];
5723 return [source record] != nil;
5726 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5727 [[list_ table] setDeleteConfirmationRow:row];
5730 - (void) table:(UITable *)table deleteRow:(int)row {
5731 Source *source = [sources_ objectAtIndex:row];
5732 [Sources_ removeObjectForKey:[source key]];
5733 [delegate_ syncData];
5737 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5740 @"./", @"Distribution",
5741 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5743 [delegate_ syncData];
5746 - (NSString *) getWarning {
5747 NSString *href(href_);
5748 NSRange colon([href rangeOfString:@"://"]);
5749 if (colon.location != NSNotFound)
5750 href = [href substringFromIndex:(colon.location + 3)];
5751 href = [href stringByAddingPercentEscapes];
5752 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5753 href = [href stringByCachingURLWithCurrentCDN];
5755 NSURL *url([NSURL URLWithString:href]);
5757 NSStringEncoding encoding;
5758 NSError *error(nil);
5760 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5761 return [warning length] == 0 ? nil : warning;
5765 - (void) _endConnection:(NSURLConnection *)connection {
5766 NSURLConnection **field = NULL;
5767 if (connection == trivial_)
5769 else if (connection == trivial_bz2_)
5770 field = &trivial_bz2_;
5771 else if (connection == trivial_gz_)
5772 field = &trivial_gz_;
5773 _assert(field != NULL);
5774 [connection release];
5779 trivial_bz2_ == nil &&
5785 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5788 UIActionSheet *sheet = [[[UIActionSheet alloc]
5789 initWithTitle:UCLocalize("SOURCE_WARNING")
5790 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_ANYWAY"), UCLocalize("CANCEL"), nil]
5791 defaultButtonIndex:0
5796 [sheet setNumberOfRows:1];
5798 [sheet setBodyText:warning];
5799 [sheet popupAlertAnimated:YES];
5802 } else if (error_ != nil) {
5803 UIActionSheet *sheet = [[[UIActionSheet alloc]
5804 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5805 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5806 defaultButtonIndex:0
5811 [sheet setBodyText:[error_ localizedDescription]];
5812 [sheet popupAlertAnimated:YES];
5814 UIActionSheet *sheet = [[[UIActionSheet alloc]
5815 initWithTitle:UCLocalize("NOT_REPOSITORY")
5816 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5817 defaultButtonIndex:0
5822 [sheet setBodyText:UCLocalize("NOT_REPOSITORY_EX")];
5823 [sheet popupAlertAnimated:YES];
5826 [delegate_ setStatusBarShowsProgress:NO];
5827 [delegate_ removeProgressHUD:hud_];
5837 if (error_ != nil) {
5844 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5845 switch ([response statusCode]) {
5851 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5852 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5854 error_ = [error retain];
5855 [self _endConnection:connection];
5858 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5859 [self _endConnection:connection];
5862 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5863 NSMutableURLRequest *request = [NSMutableURLRequest
5864 requestWithURL:[NSURL URLWithString:href]
5865 cachePolicy:NSURLRequestUseProtocolCachePolicy
5866 timeoutInterval:20.0
5869 [request setHTTPMethod:method];
5871 if (Machine_ != NULL)
5872 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5873 if (UniqueID_ != nil)
5874 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5877 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5879 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5882 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5883 NSString *context([sheet context]);
5885 if ([context isEqualToString:@"source"]) {
5888 NSString *href = [[sheet textField] text];
5890 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5892 if (![href hasSuffix:@"/"])
5893 href_ = [href stringByAppendingString:@"/"];
5896 href_ = [href_ retain];
5898 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
5899 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5900 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5901 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5905 hud_ = [[delegate_ addProgressHUD] retain];
5906 [hud_ setText:UCLocalize("VERIFYING_URL")];
5916 } else if ([context isEqualToString:@"trivial"])
5918 else if ([context isEqualToString:@"urlerror"])
5920 else if ([context isEqualToString:@"warning"]) {
5939 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5940 if ((self = [super initWithBook:book]) != nil) {
5941 database_ = database;
5942 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5944 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5945 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5946 [list_ setShouldHideHeaderInShortLists:NO];
5948 [self addSubview:list_];
5949 [list_ setDataSource:self];
5951 UITableColumn *column = [[UITableColumn alloc]
5952 initWithTitle:UCLocalize("NAME")
5954 width:[self frame].size.width
5957 UITable *table = [list_ table];
5958 [table setSeparatorStyle:1];
5959 [table addTableColumn:column];
5960 [table setDelegate:self];
5964 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5965 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5969 - (void) reloadData {
5971 if (!list.ReadMainList())
5974 [sources_ removeAllObjects];
5975 [sources_ addObjectsFromArray:[database_ sources]];
5977 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5980 int count([sources_ count]);
5981 for (offset_ = 0; offset_ != count; ++offset_) {
5982 Source *source = [sources_ objectAtIndex:offset_];
5983 if ([source record] == nil)
5990 - (void) resetViewAnimated:(BOOL)animated {
5991 [list_ resetViewAnimated:animated];
5994 - (void) _leftButtonClicked {
5995 /*[book_ pushPage:[[[AddSourceView alloc]
6000 UIActionSheet *sheet = [[[UIActionSheet alloc]
6001 initWithTitle:UCLocalize("ENTER_APT_URL")
6002 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_SOURCE"), UCLocalize("CANCEL"), nil]
6003 defaultButtonIndex:0
6008 [sheet setNumberOfRows:1];
6010 [sheet addTextFieldWithValue:@"http://" label:@""];
6012 UITextInputTraits *traits = [[sheet textField] textInputTraits];
6013 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6014 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6015 [traits setKeyboardType:UIKeyboardTypeURL];
6016 // XXX: UIReturnKeyDone
6017 [traits setReturnKeyType:UIReturnKeyNext];
6019 [sheet popupAlertAnimated:YES];
6022 - (void) _rightButtonClicked {
6023 UITable *table = [list_ table];
6024 BOOL editing = [table isRowDeletionEnabled];
6025 [table enableRowDeletion:!editing animated:YES];
6026 [book_ reloadButtonsForPage:self];
6029 - (NSString *) title {
6030 return UCLocalize("SOURCES");
6033 - (NSString *) leftButtonTitle {
6034 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("ADD") : nil;
6037 - (id) rightButtonTitle {
6038 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("DONE") : UCLocalize("EDIT");
6041 - (UINavigationButtonStyle) rightButtonStyle {
6042 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6048 /* Installed View {{{ */
6049 @interface InstalledView : RVPage {
6050 _transient Database *database_;
6051 FilteredPackageTable *packages_;
6055 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6059 @implementation InstalledView
6062 [packages_ release];
6066 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6067 if ((self = [super initWithBook:book]) != nil) {
6068 database_ = database;
6070 packages_ = [[FilteredPackageTable alloc]
6074 filter:@selector(isInstalledAndVisible:)
6075 with:[NSNumber numberWithBool:YES]
6078 [self addSubview:packages_];
6080 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6081 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6085 - (void) resetViewAnimated:(BOOL)animated {
6086 [packages_ resetViewAnimated:animated];
6089 - (void) reloadData {
6090 [packages_ reloadData];
6093 - (void) _rightButtonClicked {
6094 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6095 [packages_ reloadData];
6097 [book_ reloadButtonsForPage:self];
6100 - (NSString *) title {
6101 return UCLocalize("INSTALLED");
6104 - (NSString *) backButtonTitle {
6105 return UCLocalize("PACKAGES");
6108 - (id) rightButtonTitle {
6109 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE");
6112 - (UINavigationButtonStyle) rightButtonStyle {
6113 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6116 - (void) setDelegate:(id)delegate {
6117 [super setDelegate:delegate];
6118 [packages_ setDelegate:delegate];
6125 @interface HomeView : CydiaBrowserView {
6130 @implementation HomeView
6132 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6133 NSString *context([sheet context]);
6135 if ([context isEqualToString:@"about"])
6138 [super alertSheet:sheet buttonClicked:button];
6141 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6142 [super _setMoreHeaders:request];
6144 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6147 - (void) _leftButtonClicked {
6148 UIActionSheet *sheet = [[[UIActionSheet alloc]
6149 initWithTitle:UCLocalize("ABOUT_CYDIA")
6150 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
6151 defaultButtonIndex:0
6157 @"Copyright (C) 2008-2009\n"
6158 "Jay Freeman (saurik)\n"
6159 "saurik@saurik.com\n"
6160 "http://www.saurik.com/\n"
6163 "http://www.theokorigroup.com/\n"
6165 "College of Creative Studies,\n"
6166 "University of California,\n"
6168 "http://www.ccs.ucsb.edu/"
6171 [sheet popupAlertAnimated:YES];
6174 - (NSString *) leftButtonTitle {
6175 return UCLocalize("ABOUT");
6180 /* Manage View {{{ */
6181 @interface ManageView : CydiaBrowserView {
6186 @implementation ManageView
6188 - (NSString *) title {
6189 return UCLocalize("MANAGE");
6192 - (void) _leftButtonClicked {
6193 [delegate_ askForSettings];
6194 [delegate_ updateData];
6197 - (NSString *) leftButtonTitle {
6198 return UCLocalize("SETTINGS");
6202 - (id) _rightButtonTitle {
6203 return Queuing_ ? UCLocalize("QUEUE") : nil;
6206 - (UINavigationButtonStyle) rightButtonStyle {
6207 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6210 - (void) _rightButtonClicked {
6215 - (bool) isLoading {
6222 /* Cydia Book {{{ */
6223 @interface CYBook : RVBook <
6226 _transient Database *database_;
6227 UINavigationBar *overlay_;
6228 UINavigationBar *underlay_;
6229 UIProgressIndicator *indicator_;
6230 UITextLabel *prompt_;
6231 UIProgressBar *progress_;
6232 UINavigationButton *cancel_;
6236 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
6242 @implementation CYBook
6246 [indicator_ release];
6248 [progress_ release];
6253 - (NSString *) getTitleForPage:(RVPage *)page {
6254 return [super getTitleForPage:page];
6262 [UIView beginAnimations:nil context:NULL];
6264 CGRect ovrframe = [overlay_ frame];
6265 ovrframe.origin.y = 0;
6266 [overlay_ setFrame:ovrframe];
6268 CGRect barframe = [navbar_ frame];
6269 barframe.origin.y += ovrframe.size.height;
6270 [navbar_ setFrame:barframe];
6272 CGRect trnframe = [transition_ frame];
6273 trnframe.origin.y += ovrframe.size.height;
6274 trnframe.size.height -= ovrframe.size.height;
6275 [transition_ setFrame:trnframe];
6277 [UIView endAnimations];
6279 [indicator_ startAnimation];
6280 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6281 [progress_ setProgress:0];
6284 [overlay_ addSubview:cancel_];
6287 detachNewThreadSelector:@selector(_update)
6293 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6294 NSString *context([sheet context]);
6296 if ([context isEqualToString:@"refresh"])
6303 [indicator_ stopAnimation];
6305 [UIView beginAnimations:nil context:NULL];
6307 CGRect ovrframe = [overlay_ frame];
6308 ovrframe.origin.y = -ovrframe.size.height;
6309 [overlay_ setFrame:ovrframe];
6311 CGRect barframe = [navbar_ frame];
6312 barframe.origin.y -= ovrframe.size.height;
6313 [navbar_ setFrame:barframe];
6315 CGRect trnframe = [transition_ frame];
6316 trnframe.origin.y -= ovrframe.size.height;
6317 trnframe.size.height += ovrframe.size.height;
6318 [transition_ setFrame:trnframe];
6320 [UIView commitAnimations];
6322 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6325 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6326 if ((self = [super initWithFrame:frame]) != nil) {
6327 database_ = database;
6329 CGRect ovrrect([navbar_ bounds]);
6330 ovrrect.size.height = [UINavigationBar defaultSize].height;
6331 ovrrect.origin.y = -ovrrect.size.height;
6333 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6334 [self addSubview:overlay_];
6336 ovrrect.origin.y = frame.size.height;
6337 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6338 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6339 [self addSubview:underlay_];
6341 [overlay_ setBarStyle:1];
6342 [underlay_ setBarStyle:1];
6344 int barstyle([overlay_ _barStyle:NO]);
6345 bool ugly(barstyle == 0);
6347 UIProgressIndicatorStyle style = ugly ?
6348 UIProgressIndicatorStyleMediumBrown :
6349 UIProgressIndicatorStyleMediumWhite;
6351 CGSize indsize([UIProgressIndicator defaultSizeForStyle:style]);
6352 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6353 CGRect indrect = {{indoffset, indoffset}, indsize};
6355 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6356 [indicator_ setStyle:style];
6357 [overlay_ addSubview:indicator_];
6359 CGSize prmsize = {215, indsize.height + 4};
6362 indoffset * 2 + indsize.width,
6363 unsigned(ovrrect.size.height - prmsize.height) / 2 - 1
6366 UIFont *font([UIFont systemFontOfSize:15]);
6368 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6370 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6371 [prompt_ setBackgroundColor:[UIColor clearColor]];
6372 [prompt_ setFont:font];
6374 [overlay_ addSubview:prompt_];
6376 CGSize prgsize = {75, 100};
6379 ovrrect.size.width - prgsize.width - 10,
6380 (ovrrect.size.height - prgsize.height) / 2
6383 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6384 [progress_ setStyle:0];
6385 [overlay_ addSubview:progress_];
6387 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6388 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6390 CGRect frame = [cancel_ frame];
6391 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6392 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6393 [cancel_ setFrame:frame];
6395 [cancel_ setBarStyle:barstyle];
6399 - (void) _onCancel {
6401 [cancel_ removeFromSuperview];
6404 - (void) _update { _pooled
6406 status.setDelegate(self);
6407 [database_ updateWithStatus:status];
6410 performSelectorOnMainThread:@selector(_update_)
6416 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6417 [prompt_ setText:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6421 UIActionSheet *sheet = [[[UIActionSheet alloc]
6422 initWithTitle:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), UCLocalize("REFRESH")]
6423 buttons:[NSArray arrayWithObjects:
6426 defaultButtonIndex:0
6431 [sheet setBodyText:error];
6432 [sheet popupAlertAnimated:YES];
6434 [self reloadButtons];
6437 - (void) setProgressTitle:(NSString *)title {
6439 performSelectorOnMainThread:@selector(_setProgressTitle:)
6445 - (void) setProgressPercent:(float)percent {
6447 performSelectorOnMainThread:@selector(_setProgressPercent:)
6448 withObject:[NSNumber numberWithFloat:percent]
6453 - (void) startProgress {
6456 - (void) addProgressOutput:(NSString *)output {
6458 performSelectorOnMainThread:@selector(_addProgressOutput:)
6464 - (bool) isCancelling:(size_t)received {
6468 - (void) _setProgressTitle:(NSString *)title {
6469 [prompt_ setText:title];
6472 - (void) _setProgressPercent:(NSNumber *)percent {
6473 [progress_ setProgress:[percent floatValue]];
6476 - (void) _addProgressOutput:(NSString *)output {
6481 /* Cydia:// Protocol {{{ */
6482 @interface CydiaURLProtocol : NSURLProtocol {
6487 @implementation CydiaURLProtocol
6489 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6490 NSURL *url([request URL]);
6493 NSString *scheme([[url scheme] lowercaseString]);
6494 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6499 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6503 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6504 id<NSURLProtocolClient> client([self client]);
6506 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6508 NSData *data(UIImagePNGRepresentation(icon));
6510 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6511 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6512 [client URLProtocol:self didLoadData:data];
6513 [client URLProtocolDidFinishLoading:self];
6517 - (void) startLoading {
6518 id<NSURLProtocolClient> client([self client]);
6519 NSURLRequest *request([self request]);
6521 NSURL *url([request URL]);
6522 NSString *href([url absoluteString]);
6524 NSString *path([href substringFromIndex:8]);
6525 NSRange slash([path rangeOfString:@"/"]);
6528 if (slash.location == NSNotFound) {
6532 command = [path substringToIndex:slash.location];
6533 path = [path substringFromIndex:(slash.location + 1)];
6536 Database *database([Database sharedInstance]);
6538 if ([command isEqualToString:@"package-icon"]) {
6541 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6542 Package *package([database packageWithName:path]);
6545 UIImage *icon([package icon]);
6546 [self _returnPNGWithImage:icon forRequest:request];
6547 } else if ([command isEqualToString:@"source-icon"]) {
6550 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6551 NSString *source(Simplify(path));
6552 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6554 icon = [UIImage applicationImageNamed:@"unknown.png"];
6555 [self _returnPNGWithImage:icon forRequest:request];
6556 } else if ([command isEqualToString:@"uikit-image"]) {
6559 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6560 UIImage *icon(_UIImageWithName(path));
6561 [self _returnPNGWithImage:icon forRequest:request];
6562 } else if ([command isEqualToString:@"section-icon"]) {
6565 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6566 NSString *section(Simplify(path));
6567 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6569 icon = [UIImage applicationImageNamed:@"unknown.png"];
6570 [self _returnPNGWithImage:icon forRequest:request];
6572 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6576 - (void) stopLoading {
6582 /* Sections View {{{ */
6583 @interface SectionsView : RVPage {
6584 _transient Database *database_;
6585 NSMutableArray *sections_;
6586 NSMutableArray *filtered_;
6587 UITransitionView *transition_;
6593 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6594 - (void) reloadData;
6599 @implementation SectionsView
6602 [list_ setDataSource:nil];
6603 [list_ setDelegate:nil];
6605 [sections_ release];
6606 [filtered_ release];
6607 [transition_ release];
6609 [accessory_ release];
6613 - (int) numberOfRowsInTable:(UITable *)table {
6614 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6617 - (float) table:(UITable *)table heightForRow:(int)row {
6621 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6623 reusing = [[[SectionCell alloc] init] autorelease];
6624 [(SectionCell *)reusing setSection:(editing_ ?
6625 [sections_ objectAtIndex:row] :
6626 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6627 ) editing:editing_];
6631 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6635 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6639 - (void) tableRowSelected:(NSNotification *)notification {
6640 int row = [[notification object] selectedRow];
6651 title = UCLocalize("ALL_PACKAGES");
6653 section = [filtered_ objectAtIndex:(row - 1)];
6654 name = [section name];
6657 name = [NSString stringWithString:name];
6658 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6661 title = UCLocalize("NO_SECTION");
6665 PackageTable *table = [[[FilteredPackageTable alloc]
6669 filter:@selector(isVisibleInSection:)
6673 [table setDelegate:delegate_];
6675 [book_ pushPage:table];
6678 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6679 if ((self = [super initWithBook:book]) != nil) {
6680 database_ = database;
6682 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6683 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6685 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6686 [self addSubview:transition_];
6688 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6689 [transition_ transition:0 toView:list_];
6691 UITableColumn *column = [[[UITableColumn alloc]
6692 initWithTitle:UCLocalize("NAME")
6694 width:[self frame].size.width
6697 [list_ setDataSource:self];
6698 [list_ setSeparatorStyle:1];
6699 [list_ addTableColumn:column];
6700 [list_ setDelegate:self];
6701 [list_ setReusesTableCells:YES];
6705 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6706 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6710 - (void) reloadData {
6711 NSArray *packages = [database_ packages];
6713 [sections_ removeAllObjects];
6714 [filtered_ removeAllObjects];
6717 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6718 SectionMap sections;
6719 sections.resize(64);
6721 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6725 for (Package *package in packages) {
6726 NSString *name([package section]);
6727 NSString *key(name == nil ? @"" : name);
6732 _profile(SectionsView$reloadData$Section)
6733 section = §ions[key];
6734 if (*section == nil) {
6735 _profile(SectionsView$reloadData$Section$Allocate)
6736 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6741 [*section addToCount];
6743 _profile(SectionsView$reloadData$Filter)
6744 if (![package valid] || ![package visible])
6748 [*section addToRow];
6752 _profile(SectionsView$reloadData$Section)
6753 section = [sections objectForKey:key];
6754 if (section == nil) {
6755 _profile(SectionsView$reloadData$Section$Allocate)
6756 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6757 [sections setObject:section forKey:key];
6762 [section addToCount];
6764 _profile(SectionsView$reloadData$Filter)
6765 if (![package valid] || ![package visible])
6775 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6776 [sections_ addObject:i->second];
6778 [sections_ addObjectsFromArray:[sections allValues]];
6781 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6783 for (Section *section in sections_) {
6784 size_t count([section row]);
6788 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6789 [section setCount:count];
6790 [filtered_ addObject:section];
6797 - (void) resetView {
6799 [self _rightButtonClicked];
6802 - (void) resetViewAnimated:(BOOL)animated {
6803 [list_ resetViewAnimated:animated];
6806 - (void) _rightButtonClicked {
6807 if ((editing_ = !editing_))
6810 [delegate_ updateData];
6811 [book_ reloadTitleForPage:self];
6812 [book_ reloadButtonsForPage:self];
6815 - (NSString *) title {
6816 return editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS");
6819 - (NSString *) backButtonTitle {
6820 return UCLocalize("SECTIONS");
6823 - (id) rightButtonTitle {
6824 return [sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT");
6827 - (UINavigationButtonStyle) rightButtonStyle {
6828 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6831 - (UIView *) accessoryView {
6837 /* Changes View {{{ */
6838 @interface ChangesView : RVPage {
6839 _transient Database *database_;
6840 NSMutableArray *packages_;
6841 NSMutableArray *sections_;
6846 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6847 - (void) reloadData;
6851 @implementation ChangesView
6854 [list_ setDelegate:nil];
6855 [list_ setDataSource:nil];
6857 [packages_ release];
6858 [sections_ release];
6863 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6864 NSInteger count([sections_ count]);
6865 return count == 0 ? 1 : count;
6868 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6869 if ([sections_ count] == 0)
6871 return [[sections_ objectAtIndex:section] name];
6874 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6875 if ([sections_ count] == 0)
6877 return [[sections_ objectAtIndex:section] count];
6880 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6881 Section *section([sections_ objectAtIndex:[path section]]);
6882 NSInteger row([path row]);
6883 return [packages_ objectAtIndex:([section row] + row)];
6886 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6887 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
6889 cell = [[[PackageCell alloc] init] autorelease];
6890 [cell setPackage:[self packageAtIndexPath:path]];
6894 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6896 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6899 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6900 Package *package([self packageAtIndexPath:path]);
6901 PackageView *view([delegate_ packageView]);
6902 [view setDelegate:delegate_];
6903 [view setPackage:package];
6904 [book_ pushPage:view];
6908 - (void) _leftButtonClicked {
6909 [(CYBook *)book_ update];
6910 [self reloadButtons];
6913 - (void) _rightButtonClicked {
6914 [delegate_ distUpgrade];
6917 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6918 if ((self = [super initWithBook:book]) != nil) {
6919 database_ = database;
6921 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6922 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6924 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
6925 [self addSubview:list_];
6927 //XXX:[list_ setShouldHideHeaderInShortLists:NO];
6928 [list_ setDataSource:self];
6929 [list_ setDelegate:self];
6930 //[list_ setSectionListStyle:1];
6934 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6935 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6939 - (void) reloadData {
6940 NSArray *packages = [database_ packages];
6942 [packages_ removeAllObjects];
6943 [sections_ removeAllObjects];
6946 for (Package *package in packages)
6948 [package uninstalled] && [package valid] && [package visible] ||
6949 [package upgradableAndEssential:YES]
6951 [packages_ addObject:package];
6954 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6957 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6958 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6959 Section *section = nil;
6963 bool unseens = false;
6965 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6967 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6968 Package *package = [packages_ objectAtIndex:offset];
6970 BOOL uae = [package upgradableAndEssential:YES];
6976 _profile(ChangesView$reloadData$Remember)
6977 seen = [package seen];
6980 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6985 name = UCLocalize("UNKNOWN");
6987 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6991 _profile(ChangesView$reloadData$Allocate)
6992 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
6993 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6994 [sections_ addObject:section];
6998 [section addToCount];
6999 } else if ([package ignored])
7000 [ignored addToCount];
7003 [upgradable addToCount];
7008 CFRelease(formatter);
7011 Section *last = [sections_ lastObject];
7012 size_t count = [last count];
7013 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7014 [sections_ removeLastObject];
7017 if ([ignored count] != 0)
7018 [sections_ insertObject:ignored atIndex:0];
7020 [sections_ insertObject:upgradable atIndex:0];
7023 [self reloadButtons];
7026 - (void) resetViewAnimated:(BOOL)animated {
7027 [list_ resetViewAnimated:animated];
7030 - (NSString *) leftButtonTitle {
7031 return [(CYBook *)book_ updating] ? nil : UCLocalize("REFRESH");
7034 - (id) rightButtonTitle {
7035 return upgrades_ == 0 ? nil : [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
7038 - (NSString *) title {
7039 return UCLocalize("CHANGES");
7044 /* Search View {{{ */
7045 @protocol SearchViewDelegate
7046 - (void) showKeyboard:(BOOL)show;
7049 @interface SearchView : RVPage {
7051 UISearchField *field_;
7052 FilteredPackageTable *table_;
7057 - (id) initWithBook:(RVBook *)book database:(Database *)database;
7058 - (void) reloadData;
7062 @implementation SearchView
7065 [field_ setDelegate:nil];
7067 [accessory_ release];
7074 - (void) _showKeyboard:(BOOL)show {
7075 CGSize keysize = [UIKeyboard defaultSize];
7076 CGRect keydown = [book_ pageBounds];
7077 CGRect keyup = keydown;
7078 keyup.size.height -= keysize.height - ButtonBarHeight_;
7080 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
7082 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
7083 [animation setSignificantRectFields:8];
7086 [animation setStartFrame:keydown];
7087 [animation setEndFrame:keyup];
7089 [animation setStartFrame:keyup];
7090 [animation setEndFrame:keydown];
7093 UIAnimator *animator = [UIAnimator sharedAnimator];
7096 addAnimations:[NSArray arrayWithObjects:animation, nil]
7097 withDuration:(KeyboardTime_ - delay)
7102 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
7104 [delegate_ showKeyboard:show];
7107 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
7108 [self _showKeyboard:YES];
7111 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
7112 [self _showKeyboard:NO];
7115 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
7117 NSString *text([field_ text]);
7118 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
7124 - (void) textFieldClearButtonPressed:(UITextField *)field {
7128 - (void) keyboardInputShouldDelete:(id)input {
7132 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
7133 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
7137 [field_ resignFirstResponder];
7142 - (id) initWithBook:(RVBook *)book database:(Database *)database {
7143 if ((self = [super initWithBook:book]) != nil) {
7144 CGRect pageBounds = [book_ pageBounds];
7146 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
7147 CGColor dimmed(space_, 0, 0, 0, 0.5);
7148 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
7150 table_ = [[FilteredPackageTable alloc]
7154 filter:@selector(isUnfilteredAndSearchedForBy:)
7158 [table_ setShouldHideHeaderInShortLists:NO];
7159 [self addSubview:table_];
7161 CGRect cnfrect = {{7, 38}, {17, 18}};
7168 area.size.width = [self bounds].size.width - area.origin.x * 2;
7169 area.size.height = [UISearchField defaultHeight];
7171 field_ = [[UISearchField alloc] initWithFrame:area];
7173 UIFont *font = [UIFont systemFontOfSize:16];
7174 [field_ setFont:font];
7176 [field_ setPlaceholder:UCLocalize("SEARCH_EX")];
7177 [field_ setDelegate:self];
7179 [field_ setPaddingTop:5];
7181 UITextInputTraits *traits([field_ textInputTraits]);
7182 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7183 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7184 [traits setReturnKeyType:UIReturnKeySearch];
7186 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
7188 accessory_ = [[UIView alloc] initWithFrame:accrect];
7189 [accessory_ addSubview:field_];
7191 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7192 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7196 - (void) resetViewAnimated:(BOOL)animated {
7197 [table_ resetViewAnimated:animated];
7200 - (void) _reloadData {
7203 - (void) reloadData {
7204 [table_ setObject:[field_ text]];
7205 _profile(SearchView$reloadData)
7206 [table_ reloadData];
7209 [table_ resetCursor];
7212 - (UIView *) accessoryView {
7216 - (NSString *) title {
7220 - (NSString *) backButtonTitle {
7221 return UCLocalize("SEARCH");
7224 - (void) setDelegate:(id)delegate {
7225 [table_ setDelegate:delegate];
7226 [super setDelegate:delegate];
7231 /* Settings View {{{ */
7232 @interface SettingsView : RVPage {
7233 _transient Database *database_;
7236 UIPreferencesTable *table_;
7237 _UISwitchSlider *subscribedSwitch_;
7238 _UISwitchSlider *ignoredSwitch_;
7239 UIPreferencesControlTableCell *subscribedCell_;
7240 UIPreferencesControlTableCell *ignoredCell_;
7243 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7247 @implementation SettingsView
7250 [table_ setDataSource:nil];
7253 if (package_ != nil)
7256 [subscribedSwitch_ release];
7257 [ignoredSwitch_ release];
7258 [subscribedCell_ release];
7259 [ignoredCell_ release];
7263 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7264 if (package_ == nil)
7270 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7271 if (package_ == nil)
7284 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7285 if (package_ == nil)
7298 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7299 if (package_ == nil)
7312 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7313 if (package_ == nil)
7316 _UISwitchSlider *slider([cell control]);
7317 BOOL value([slider value] != 0);
7318 NSMutableDictionary *metadata([package_ metadata]);
7321 if (NSNumber *number = [metadata objectForKey:key])
7322 before = [number boolValue];
7326 if (value != before) {
7327 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7329 [delegate_ updateData];
7333 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7334 [self onSomething:cell withKey:@"IsSubscribed"];
7337 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7338 [self onSomething:cell withKey:@"IsIgnored"];
7341 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7342 if (package_ == nil)
7346 case 0: switch (row) {
7348 return subscribedCell_;
7350 return ignoredCell_;
7354 case 1: switch (row) {
7356 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7357 [cell setShowSelection:NO];
7358 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7371 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7372 if ((self = [super initWithBook:book])) {
7373 database_ = database;
7374 name_ = [package retain];
7376 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7377 [self addSubview:table_];
7379 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7380 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
7382 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7383 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
7385 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7386 [subscribedCell_ setShowSelection:NO];
7387 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7388 [subscribedCell_ setControl:subscribedSwitch_];
7390 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7391 [ignoredCell_ setShowSelection:NO];
7392 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7393 [ignoredCell_ setControl:ignoredSwitch_];
7395 [table_ setDataSource:self];
7400 - (void) resetViewAnimated:(BOOL)animated {
7401 [table_ resetViewAnimated:animated];
7404 - (void) reloadData {
7405 if (package_ != nil)
7406 [package_ autorelease];
7407 package_ = [database_ packageWithName:name_];
7408 if (package_ != nil) {
7410 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7411 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7414 [table_ reloadData];
7417 - (NSString *) title {
7418 return UCLocalize("SETTINGS");
7424 /* Signature View {{{ */
7425 @interface SignatureView : CydiaBrowserView {
7426 _transient Database *database_;
7430 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7434 @implementation SignatureView
7441 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7443 [super webView:sender didClearWindowObject:window forFrame:frame];
7446 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7447 if ((self = [super initWithBook:book]) != nil) {
7448 database_ = database;
7449 package_ = [package retain];
7454 - (void) resetViewAnimated:(BOOL)animated {
7457 - (void) reloadData {
7458 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7464 @interface Cydia : UIApplication <
7465 ConfirmationViewDelegate,
7466 ProgressViewDelegate,
7475 UIToolbar *toolbar_;
7479 NSMutableArray *essential_;
7480 NSMutableArray *broken_;
7482 Database *database_;
7483 ProgressView *progress_;
7487 UIKeyboard *keyboard_;
7488 UIProgressHUD *hud_;
7490 SectionsView *sections_;
7491 ChangesView *changes_;
7492 ManageView *manage_;
7493 SearchView *search_;
7495 #if RecyclePackageViews
7496 NSMutableArray *details_;
7500 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7501 - (void) setPage:(RVPage *)page;
7505 static _finline void _setHomePage(Cydia *self) {
7506 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeView class]]];
7509 @implementation Cydia
7512 if ([broken_ count] != 0) {
7513 int count = [broken_ count];
7515 UIActionSheet *sheet = [[[UIActionSheet alloc]
7516 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7517 buttons:[NSArray arrayWithObjects:
7518 UCLocalize("FORCIBLY_CLEAR"),
7519 UCLocalize("TEMPORARY_IGNORE"),
7521 defaultButtonIndex:0
7526 [sheet setBodyText:UCLocalize("HALFINSTALLED_PACKAGE_EX")];
7527 [sheet popupAlertAnimated:YES];
7528 } else if (!Ignored_ && [essential_ count] != 0) {
7529 int count = [essential_ count];
7531 UIActionSheet *sheet = [[[UIActionSheet alloc]
7532 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7533 buttons:[NSArray arrayWithObjects:
7534 UCLocalize("UPGRADE_ESSENTIAL"),
7535 UCLocalize("COMPLETE_UPGRADE"),
7536 UCLocalize("TEMPORARY_IGNORE"),
7538 defaultButtonIndex:0
7543 [sheet setBodyText:UCLocalize("ESSENTIAL_UPGRADE_EX")];
7544 [sheet popupAlertAnimated:YES];
7548 - (void) _saveConfig {
7551 NSString *error(nil);
7552 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7554 NSError *error(nil);
7555 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7556 NSLog(@"failure to save metadata data: %@", error);
7559 NSLog(@"failure to serialize metadata: %@", error);
7567 - (void) _updateData {
7570 /* XXX: this is just stupid */
7571 if (tag_ != 2 && sections_ != nil)
7572 [sections_ reloadData];
7573 if (tag_ != 3 && changes_ != nil)
7574 [changes_ reloadData];
7575 if (tag_ != 5 && search_ != nil)
7576 [search_ reloadData];
7581 - (void) _reloadData {
7584 static bool loaded(false);
7585 UIProgressHUD *hud([self addProgressHUD]);
7586 [hud setText:(loaded ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7588 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7591 [self removeProgressHUD:hud];
7595 [essential_ removeAllObjects];
7596 [broken_ removeAllObjects];
7598 NSArray *packages([database_ packages]);
7599 for (Package *package in packages) {
7601 [broken_ addObject:package];
7602 if ([package upgradableAndEssential:NO]) {
7603 if ([package essential])
7604 [essential_ addObject:package];
7610 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7611 [toolbar_ setBadgeValue:badge forButton:3];
7612 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7613 [toolbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7614 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7615 [self setApplicationBadge:badge];
7617 [self setApplicationBadgeString:badge];
7619 [toolbar_ setBadgeValue:nil forButton:3];
7620 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7621 [toolbar_ setBadgeAnimated:NO forButton:3];
7622 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7623 [self removeApplicationBadge];
7624 else // XXX: maybe use setApplicationBadgeString also?
7625 [self setApplicationIconBadgeNumber:0];
7629 [toolbar_ setBadgeValue:nil forButton:4];
7633 if (loaded || ManualRefresh) loaded:
7638 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7639 NSTimeInterval interval([update timeIntervalSinceNow]);
7640 if (interval <= 0 && interval > -(15*60))
7648 - (void) updateData {
7649 [database_ setVisible];
7658 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
7659 _assert(file != NULL);
7661 for (NSString *key in [Sources_ allKeys]) {
7662 NSDictionary *source([Sources_ objectForKey:key]);
7664 fprintf(file, "%s %s %s\n",
7665 [[source objectForKey:@"Type"] UTF8String],
7666 [[source objectForKey:@"URI"] UTF8String],
7667 [[source objectForKey:@"Distribution"] UTF8String]
7676 detachNewThreadSelector:@selector(update_)
7679 title:UCLocalize("UPDATING_SOURCES")
7683 - (void) reloadData {
7684 @synchronized (self) {
7685 if (confirm_ == nil)
7691 pkgProblemResolver *resolver = [database_ resolver];
7693 resolver->InstallProtect();
7694 if (!resolver->Resolve(true))
7698 - (void) popUpBook:(RVBook *)book {
7699 [underlay_ popSubview:book];
7702 - (CGRect) popUpBounds {
7703 return [underlay_ bounds];
7707 if (![database_ prepare])
7710 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7711 [confirm_ setDelegate:self];
7713 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7714 [page setDelegate:self];
7716 [confirm_ setPage:page];
7717 [self popUpBook:confirm_];
7723 @synchronized (self) {
7728 - (void) clearPackage:(Package *)package {
7729 @synchronized (self) {
7736 - (void) installPackage:(Package *)package {
7737 @synchronized (self) {
7744 - (void) removePackage:(Package *)package {
7745 @synchronized (self) {
7752 - (void) distUpgrade {
7753 @synchronized (self) {
7754 if (![database_ upgrade])
7761 [self slideUp:[[[UIActionSheet alloc]
7763 buttons:[NSArray arrayWithObjects:UCLocalize("CONTINUE_QUEUING"), UCLocalize("CANCEL_CLEAR"), nil]
7764 defaultButtonIndex:1
7771 @synchronized (self) {
7774 if (confirm_ != nil) {
7782 [overlay_ removeFromSuperview];
7786 detachNewThreadSelector:@selector(perform)
7789 title:UCLocalize("RUNNING")
7793 - (void) progressViewIsComplete:(ProgressView *)progress {
7794 if (confirm_ != nil) {
7795 [underlay_ addSubview:overlay_];
7796 [confirm_ popFromSuperviewAnimated:NO];
7802 - (void) setPage:(RVPage *)page {
7803 [page resetViewAnimated:NO];
7804 [page setDelegate:self];
7805 [book_ setPage:page];
7808 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7809 CydiaBrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7810 [browser loadURL:url];
7814 - (SectionsView *) sectionsView {
7815 if (sections_ == nil)
7816 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7820 - (void) buttonBarItemTapped:(id)sender {
7821 unsigned tag = [sender tag];
7823 [book_ resetViewAnimated:YES];
7825 } else if (tag_ == 2)
7826 [[self sectionsView] resetView];
7829 case 1: _setHomePage(self); break;
7831 case 2: [self setPage:[self sectionsView]]; break;
7832 case 3: [self setPage:changes_]; break;
7833 case 4: [self setPage:manage_]; break;
7834 case 5: [self setPage:search_]; break;
7842 - (void) askForSettings {
7843 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
7845 CYActionSheet *role([[[CYActionSheet alloc]
7846 initWithTitle:UCLocalize("WHO_ARE_YOU")
7847 buttons:[NSArray arrayWithObjects:
7848 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
7849 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
7850 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
7852 defaultButtonIndex:-1
7855 [role setBodyText:UCLocalize("ROLE_EX")];
7857 int button([role yieldToPopupAlertAnimated:YES]);
7860 case 1: Role_ = @"User"; break;
7861 case 2: Role_ = @"Hacker"; break;
7862 case 3: Role_ = @"Developer"; break;
7867 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7871 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7878 - (void) setPackageView:(PackageView *)view {
7880 [view setPackage:nil];
7881 #if RecyclePackageViews
7882 if ([details_ count] < 3)
7883 [details_ addObject:view];
7888 - (PackageView *) _packageView {
7889 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7892 - (PackageView *) packageView {
7893 #if RecyclePackageViews
7895 size_t count([details_ count]);
7898 view = [self _packageView];
7900 [details_ addObject:[self _packageView]];
7902 view = [[[details_ lastObject] retain] autorelease];
7903 [details_ removeLastObject];
7910 return [self _packageView];
7914 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7915 NSString *context([sheet context]);
7917 if ([context isEqualToString:@"missing"])
7919 else if ([context isEqualToString:@"cancel"]) {
7936 @synchronized (self) {
7941 [toolbar_ setBadgeValue:UCLocalize("Q_D") forButton:4];
7945 if (confirm_ != nil) {
7950 } else if ([context isEqualToString:@"fixhalf"]) {
7953 @synchronized (self) {
7954 for (Package *broken in broken_) {
7957 NSString *id = [broken id];
7958 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7959 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7960 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7961 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7970 [broken_ removeAllObjects];
7978 } else if ([context isEqualToString:@"upgrade"]) {
7981 @synchronized (self) {
7982 for (Package *essential in essential_)
7983 [essential install];
8005 - (void) system:(NSString *)command { _pooled
8006 system([command UTF8String]);
8009 - (void) applicationWillSuspend {
8011 [super applicationWillSuspend];
8014 - (void) applicationSuspend:(__GSEvent *)event {
8015 if (hud_ == nil && ![progress_ isRunning])
8016 [super applicationSuspend:event];
8019 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8021 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8024 - (void) _setSuspended:(BOOL)value {
8026 [super _setSuspended:value];
8029 - (UIProgressHUD *) addProgressHUD {
8030 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8031 [window_ setUserInteractionEnabled:NO];
8033 [progress_ addSubview:hud];
8037 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8039 [hud removeFromSuperview];
8040 [window_ setUserInteractionEnabled:YES];
8043 - (RVPage *) pageForPackage:(NSString *)name {
8044 if (Package *package = [database_ packageWithName:name]) {
8045 PackageView *view([self packageView]);
8046 [view setPackage:package];
8049 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8050 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8051 return [self _pageForURL:url withClass:[CydiaBrowserView class]];
8055 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8059 NSString *href([url absoluteString]);
8060 if ([href hasPrefix:@"apptapp://package/"])
8061 return [self pageForPackage:[href substringFromIndex:18]];
8063 NSString *scheme([[url scheme] lowercaseString]);
8064 if (![scheme isEqualToString:@"cydia"])
8066 NSString *path([url absoluteString]);
8067 if ([path length] < 8)
8069 path = [path substringFromIndex:8];
8070 if (![path hasPrefix:@"/"])
8071 path = [@"/" stringByAppendingString:path];
8073 if ([path isEqualToString:@"/add-source"])
8074 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8075 else if ([path isEqualToString:@"/storage"])
8076 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CydiaBrowserView class]];
8077 else if ([path isEqualToString:@"/sources"])
8078 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8079 else if ([path isEqualToString:@"/packages"])
8080 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8081 else if ([path hasPrefix:@"/url/"])
8082 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CydiaBrowserView class]];
8083 else if ([path hasPrefix:@"/launch/"])
8084 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8085 else if ([path hasPrefix:@"/package-settings/"])
8086 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8087 else if ([path hasPrefix:@"/package-signature/"])
8088 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8089 else if ([path hasPrefix:@"/package/"])
8090 return [self pageForPackage:[path substringFromIndex:9]];
8091 else if ([path hasPrefix:@"/files/"]) {
8092 NSString *name = [path substringFromIndex:7];
8094 if (Package *package = [database_ packageWithName:name]) {
8095 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8096 [files setPackage:package];
8104 - (void) applicationOpenURL:(NSURL *)url {
8105 [super applicationOpenURL:url];
8107 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8108 [self setPage:page];
8109 [toolbar_ showSelectionForButton:tag];
8114 - (void) applicationDidFinishLaunching:(id)unused {
8115 [BrowserView _initialize];
8117 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8119 Font12_ = [[UIFont systemFontOfSize:12] retain];
8120 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8121 Font14_ = [[UIFont systemFontOfSize:14] retain];
8122 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8123 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8127 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8128 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8130 window_ = [[UIWindow alloc] initWithContentRect:[UIHardware fullScreenApplicationContentRect]];
8131 [window_ orderFront:self];
8132 [window_ makeKey:self];
8133 [window_ setHidden:NO];
8135 database_ = [Database sharedInstance];
8137 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8138 [database_ setDelegate:progress_];
8139 [window_ setContentView:progress_];
8141 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8142 [progress_ setContentView:underlay_];
8144 [progress_ resetView];
8147 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8148 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8149 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8150 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8151 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8152 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8153 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8154 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8155 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8158 [self setIdleTimerDisabled:YES];
8160 hud_ = [self addProgressHUD];
8161 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8162 [self setStatusBarShowsProgress:YES];
8164 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8166 [self setStatusBarShowsProgress:NO];
8167 [self removeProgressHUD:hud_];
8170 if (ExecFork() == 0) {
8171 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8172 perror("launchctl stop");
8179 [self askForSettings];
8182 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
8184 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8185 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
8186 0, 0, screenrect.size.width, screenrect.size.height - 48
8187 ) database:database_];
8189 [book_ setDelegate:self];
8191 [overlay_ addSubview:book_];
8193 NSArray *buttonitems = [NSArray arrayWithObjects:
8194 [NSDictionary dictionaryWithObjectsAndKeys:
8195 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8196 @"home-up.png", kUIButtonBarButtonInfo,
8197 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
8198 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
8199 self, kUIButtonBarButtonTarget,
8200 @"Cydia", kUIButtonBarButtonTitle,
8201 @"0", kUIButtonBarButtonType,
8204 [NSDictionary dictionaryWithObjectsAndKeys:
8205 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8206 @"install-up.png", kUIButtonBarButtonInfo,
8207 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
8208 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
8209 self, kUIButtonBarButtonTarget,
8210 UCLocalize("SECTIONS"), kUIButtonBarButtonTitle,
8211 @"0", kUIButtonBarButtonType,
8214 [NSDictionary dictionaryWithObjectsAndKeys:
8215 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8216 @"changes-up.png", kUIButtonBarButtonInfo,
8217 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
8218 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
8219 self, kUIButtonBarButtonTarget,
8220 UCLocalize("CHANGES"), kUIButtonBarButtonTitle,
8221 @"0", kUIButtonBarButtonType,
8224 [NSDictionary dictionaryWithObjectsAndKeys:
8225 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8226 @"manage-up.png", kUIButtonBarButtonInfo,
8227 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
8228 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
8229 self, kUIButtonBarButtonTarget,
8230 UCLocalize("MANAGE"), kUIButtonBarButtonTitle,
8231 @"0", kUIButtonBarButtonType,
8234 [NSDictionary dictionaryWithObjectsAndKeys:
8235 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8236 @"search-up.png", kUIButtonBarButtonInfo,
8237 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
8238 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
8239 self, kUIButtonBarButtonTarget,
8240 UCLocalize("SEARCH"), kUIButtonBarButtonTitle,
8241 @"0", kUIButtonBarButtonType,
8245 toolbar_ = [[UIToolbar alloc]
8247 withFrame:CGRectMake(
8248 0, screenrect.size.height - ButtonBarHeight_,
8249 screenrect.size.width, ButtonBarHeight_
8251 withItemList:buttonitems
8254 [toolbar_ setDelegate:self];
8255 [toolbar_ setBarStyle:1];
8256 [toolbar_ setButtonBarTrackingMode:2];
8258 int buttons[5] = {1, 2, 3, 4, 5};
8259 [toolbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
8260 [toolbar_ showButtonGroup:0 withDuration:0];
8262 for (int i = 0; i != 5; ++i)
8263 [[toolbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
8264 i * 64 + 2, 1, 60, ButtonBarHeight_
8267 [toolbar_ showSelectionForButton:1];
8268 [overlay_ addSubview:toolbar_];
8270 [UIKeyboard initImplementationNow];
8271 CGSize keysize = [UIKeyboard defaultSize];
8272 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
8273 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
8274 [overlay_ addSubview:keyboard_];
8276 [underlay_ addSubview:overlay_];
8280 [self sectionsView];
8281 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
8282 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
8284 manage_ = (ManageView *) [[self
8285 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8286 withClass:[ManageView class]
8289 #if RecyclePackageViews
8290 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8291 [details_ addObject:[self _packageView]];
8292 [details_ addObject:[self _packageView]];
8300 - (void) showKeyboard:(BOOL)show {
8301 CGSize keysize([UIKeyboard defaultSize]);
8302 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8303 CGRect keyup(keydown);
8304 keyup.origin.y -= keysize.height;
8306 UIFrameAnimation *animation([[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease]);
8307 [animation setSignificantRectFields:2];
8310 [animation setStartFrame:keydown];
8311 [animation setEndFrame:keyup];
8312 [keyboard_ activate];
8314 [animation setStartFrame:keyup];
8315 [animation setEndFrame:keydown];
8316 [keyboard_ deactivate];
8319 [[UIAnimator sharedAnimator]
8320 addAnimations:[NSArray arrayWithObjects:animation, nil]
8321 withDuration:KeyboardTime_
8326 - (void) slideUp:(UIActionSheet *)alert {
8327 [alert presentSheetInView:overlay_];
8333 id Alloc_(id self, SEL selector) {
8334 id object = alloc_(self, selector);
8335 lprintf("[%s]A-%p\n", self->isa->name, object);
8340 id Dealloc_(id self, SEL selector) {
8341 id object = dealloc_(self, selector);
8342 lprintf("[%s]D-%p\n", self->isa->name, object);
8346 Class $WebDefaultUIKitDelegate;
8348 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8349 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8350 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8351 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8354 int main(int argc, char *argv[]) { _pooled
8357 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8359 /* Library Hacks {{{ */
8360 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8362 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8363 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8364 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8365 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8366 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8369 /* Set Locale {{{ */
8370 Locale_ = CFLocaleCopyCurrent();
8371 Languages_ = [NSLocale preferredLanguages];
8372 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8373 //NSLog(@"%@", [Languages_ description]);
8376 if (Languages_ == nil || [Languages_ count] == 0)
8377 // XXX: consider just setting to C and then falling through?
8380 lang = [[Languages_ objectAtIndex:0] UTF8String];
8381 setenv("LANG", lang, true);
8384 //std::setlocale(LC_ALL, lang);
8385 NSLog(@"Setting Language: %s", lang);
8388 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8390 /* Parse Arguments {{{ */
8391 bool substrate(false);
8397 for (int argi(1); argi != argc; ++argi)
8398 if (strcmp(argv[argi], "--") == 0) {
8400 argv[argi] = argv[0];
8406 for (int argi(1); argi != arge; ++argi)
8407 if (strcmp(args[argi], "--substrate") == 0)
8410 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8414 App_ = [[NSBundle mainBundle] bundlePath];
8415 Home_ = NSHomeDirectory();
8421 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8422 alloc_ = alloc->method_imp;
8423 alloc->method_imp = (IMP) &Alloc_;*/
8425 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8426 dealloc_ = dealloc->method_imp;
8427 dealloc->method_imp = (IMP) &Dealloc_;*/
8429 /* System Information {{{ */
8433 size = sizeof(maxproc);
8434 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8435 perror("sysctlbyname(\"kern.maxproc\", ?)");
8436 else if (maxproc < 64) {
8438 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8439 perror("sysctlbyname(\"kern.maxproc\", #)");
8442 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8443 char *osversion = new char[size];
8444 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8445 perror("sysctlbyname(\"kern.osversion\", ?)");
8447 System_ = [NSString stringWithUTF8String:osversion];
8449 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8450 char *machine = new char[size];
8451 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8452 perror("sysctlbyname(\"hw.machine\", ?)");
8456 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8457 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8458 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8459 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8463 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8464 NSData *data((NSData *) ecid);
8465 size_t length([data length]);
8466 uint8_t bytes[length];
8467 [data getBytes:bytes];
8468 char string[length * 2 + 1];
8469 for (size_t i(0); i != length; ++i)
8470 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8471 ChipID_ = [NSString stringWithUTF8String:string];
8475 IOObjectRelease(service);
8479 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8481 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8482 Build_ = [system objectForKey:@"ProductBuildVersion"];
8483 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8484 Product_ = [info objectForKey:@"SafariProductVersion"];
8485 Safari_ = [info objectForKey:@"CFBundleVersion"];
8488 /* Load Database {{{ */
8490 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8492 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8495 if (Metadata_ == NULL)
8496 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8498 Settings_ = [Metadata_ objectForKey:@"Settings"];
8500 Packages_ = [Metadata_ objectForKey:@"Packages"];
8501 Sections_ = [Metadata_ objectForKey:@"Sections"];
8502 Sources_ = [Metadata_ objectForKey:@"Sources"];
8505 if (Settings_ != nil)
8506 Role_ = [Settings_ objectForKey:@"Role"];
8508 if (Packages_ == nil) {
8509 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8510 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8513 if (Sections_ == nil) {
8514 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8515 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8518 if (Sources_ == nil) {
8519 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8520 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8525 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8528 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8530 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8531 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8532 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8533 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8535 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8536 unlink("/tmp/.cydia.fw");
8538 } else if (access("/User", F_OK) != 0) {
8541 system("/usr/libexec/cydia/firmware.sh");
8545 _assert([[NSFileManager defaultManager]
8546 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8547 withIntermediateDirectories:YES
8552 if (access("/tmp/cydia.chk", F_OK) == 0) {
8553 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8554 _assert(errno == ENOENT);
8555 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8556 _assert(errno == ENOENT);
8559 /* APT Initialization {{{ */
8560 _assert(pkgInitConfig(*_config));
8561 _assert(pkgInitSystem(*_config, _system));
8564 _config->Set("APT::Acquire::Translation", lang);
8565 _config->Set("Acquire::http::Timeout", 15);
8566 _config->Set("Acquire::http::MaxParallel", 3);
8568 /* Color Choices {{{ */
8569 space_ = CGColorSpaceCreateDeviceRGB();
8571 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8572 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8573 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8574 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8575 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8576 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8577 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8578 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8579 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8581 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8582 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8584 /* UIKit Configuration {{{ */
8585 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8586 if ($GSFontSetUseLegacyFontMetrics != NULL)
8587 $GSFontSetUseLegacyFontMetrics(YES);
8589 UIKeyboardDisableAutomaticAppearance();
8592 Colon_ = UCLocalize("COLON_DELIMITED");
8593 Error_ = UCLocalize("ERROR");
8594 Warning_ = UCLocalize("WARNING");
8597 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8599 CGColorSpaceRelease(space_);