1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2009 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #import "UICaboodle/UCPlatform.h"
45 #import "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <GraphicsServices/GraphicsServices.h>
52 #include <Foundation/Foundation.h>
55 #define DEPLOYMENT_TARGET_MACOSX 1
56 #define CF_BUILDING_CF 1
57 #include <CoreFoundation/CFInternal.h>
60 #include <CoreFoundation/CFPriv.h>
61 #include <CoreFoundation/CFUniChar.h>
63 #import <UIKit/UIKit.h>
65 #include <WebCore/WebCoreThread.h>
66 #import <WebKit/WebDefaultUIKitDelegate.h>
73 #include <ext/stdio_filebuf.h>
75 #include <apt-pkg/acquire.h>
76 #include <apt-pkg/acquire-item.h>
77 #include <apt-pkg/algorithms.h>
78 #include <apt-pkg/cachefile.h>
79 #include <apt-pkg/clean.h>
80 #include <apt-pkg/configuration.h>
81 #include <apt-pkg/debindexfile.h>
82 #include <apt-pkg/debmetaindex.h>
83 #include <apt-pkg/error.h>
84 #include <apt-pkg/init.h>
85 #include <apt-pkg/mmap.h>
86 #include <apt-pkg/pkgrecords.h>
87 #include <apt-pkg/sha1.h>
88 #include <apt-pkg/sourcelist.h>
89 #include <apt-pkg/sptr.h>
90 #include <apt-pkg/strutl.h>
91 #include <apt-pkg/tagfile.h>
93 #include <apr-1/apr_pools.h>
95 #include <sys/types.h>
97 #include <sys/sysctl.h>
98 #include <sys/param.h>
99 #include <sys/mount.h>
105 #include <mach-o/nlist.h>
115 #include <ext/hash_map>
117 #import "UICaboodle/BrowserView.h"
118 #import "UICaboodle/ResetView.h"
120 #import "substrate.h"
127 #define _timestamp ({ \
129 gettimeofday(&tv, NULL); \
130 tv.tv_sec * 1000000 + tv.tv_usec; \
133 typedef std::vector<class ProfileTime *> TimeList;
143 ProfileTime(const char *name) :
147 times_.push_back(this);
150 void AddTime(uint64_t time) {
157 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
169 ProfileTimer(ProfileTime &time) :
176 time_.AddTime(_timestamp - start_);
181 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
183 std::cerr << "========" << std::endl;
186 #define _profile(name) { \
187 static ProfileTime name(#name); \
188 ProfileTimer _ ## name(name);
193 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
195 void NSLogPoint(const char *fix, const CGPoint &point) {
196 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
199 void NSLogRect(const char *fix, const CGRect &rect) {
200 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
203 static _finline NSString *CydiaURL(NSString *path) {
205 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
206 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
207 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
208 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
209 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
210 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
213 /* [NSObject yieldToSelector:(withObject:)] {{{*/
214 @interface NSObject (Cydia)
215 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
216 - (id) yieldToSelector:(SEL)selector;
219 @implementation NSObject (Cydia)
224 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
225 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
226 id object([[context objectAtIndex:1] nonretainedObjectValue]);
227 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
229 /* XXX: deal with exceptions */
230 id value([self performSelector:selector withObject:object]);
232 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
233 [context removeAllObjects];
234 if ([signature methodReturnLength] != 0 && value != nil)
235 [context addObject:value];
240 performSelectorOnMainThread:@selector(doNothing)
246 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
247 /*return [self performSelector:selector withObject:object];*/
249 volatile bool stopped(false);
251 NSMutableArray *context([NSMutableArray arrayWithObjects:
252 [NSValue valueWithPointer:selector],
253 [NSValue valueWithNonretainedObject:object],
254 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
257 NSThread *thread([[[NSThread alloc]
259 selector:@selector(_yieldToContext:)
265 NSRunLoop *loop([NSRunLoop currentRunLoop]);
266 NSDate *future([NSDate distantFuture]);
268 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
270 return [context count] == 0 ? nil : [context objectAtIndex:0];
273 - (id) yieldToSelector:(SEL)selector {
274 return [self yieldToSelector:selector withObject:nil];
280 @interface CYActionSheet : UIActionSheet {
284 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
287 @implementation CYActionSheet
289 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
290 if ((self = [super initWithTitle:title buttons:buttons defaultButtonIndex:index delegate:self context:nil]) != nil) {
294 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
298 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
300 [self popupAlertAnimated:animated];
301 NSRunLoop *loop([NSRunLoop currentRunLoop]);
302 NSDate *future([NSDate distantFuture]);
303 while (button_ == 0 && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
309 /* NSForcedOrderingSearch doesn't work on the iPhone */
310 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
311 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
312 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
314 /* Information Dictionaries {{{ */
315 @interface NSMutableArray (Cydia)
316 - (void) addInfoDictionary:(NSDictionary *)info;
319 @implementation NSMutableArray (Cydia)
321 - (void) addInfoDictionary:(NSDictionary *)info {
322 [self addObject:info];
327 @interface NSMutableDictionary (Cydia)
328 - (void) addInfoDictionary:(NSDictionary *)info;
331 @implementation NSMutableDictionary (Cydia)
333 - (void) addInfoDictionary:(NSDictionary *)info {
334 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
339 /* Pop Transitions {{{ */
340 @interface PopTransitionView : UITransitionView {
345 @implementation PopTransitionView
347 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
348 if (from != nil && to == nil)
349 [self removeFromSuperview];
354 @implementation UIView (PopUpView)
356 - (void) popFromSuperviewAnimated:(BOOL)animated {
357 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
360 - (void) popSubview:(UIView *)view {
361 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
362 [transition setDelegate:transition];
363 [self addSubview:transition];
365 UIView *blank = [[[UIView alloc] initWithFrame:[transition bounds]] autorelease];
366 [transition transition:UITransitionNone toView:blank];
367 [transition transition:UITransitionPushFromBottom toView:view];
373 #define lprintf(args...) fprintf(stderr, args)
376 #define TraceLogging (1 && !ForRelease)
377 #define HistogramInsertionSort (0 && !ForRelease)
378 #define ProfileTimes (0 && !ForRelease)
379 #define ForSaurik (1 && !ForRelease)
380 #define LogBrowser (0 && !ForRelease)
381 #define TrackResize (0 && !ForRelease)
382 #define ManualRefresh (1 && !ForRelease)
383 #define ShowInternals (0 && !ForRelease)
384 #define IgnoreInstall (0 && !ForRelease)
385 #define RecycleWebViews 0
386 #define RecyclePackageViews (1 && ForRelease)
387 #define AlwaysReload (1 && !ForRelease)
391 #define _trace(args...)
396 #define _profile(name) {
399 #define PrintTimes() do {} while (false)
403 typedef uint32_t (*SKRadixFunction)(id, void *);
405 @interface NSMutableArray (Radix)
406 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
407 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
415 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
416 struct RadixItem_ *lhs(swap), *rhs(swap + count);
418 static const size_t width = 32;
419 static const size_t bits = 11;
420 static const size_t slots = 1 << bits;
421 static const size_t passes = (width + (bits - 1)) / bits;
423 size_t *hist(new size_t[slots]);
425 for (size_t pass(0); pass != passes; ++pass) {
426 memset(hist, 0, sizeof(size_t) * slots);
428 for (size_t i(0); i != count; ++i) {
429 uint32_t key(lhs[i].key);
431 key &= _not(uint32_t) >> width - bits;
436 for (size_t i(0); i != slots; ++i) {
437 size_t local(offset);
442 for (size_t i(0); i != count; ++i) {
443 uint32_t key(lhs[i].key);
445 key &= _not(uint32_t) >> width - bits;
446 rhs[hist[key]++] = lhs[i];
449 RadixItem_ *tmp(lhs);
456 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
457 for (size_t i(0); i != count; ++i)
458 [values addObject:[self objectAtIndex:lhs[i].index]];
459 [self setArray:values];
464 @implementation NSMutableArray (Radix)
466 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
467 size_t count([self count]);
472 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
473 [invocation setSelector:selector];
474 [invocation setArgument:&object atIndex:2];
476 /* XXX: this is an unsafe optimization of doomy hell */
477 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
478 _assert(method != NULL);
479 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
480 _assert(imp != NULL);
483 struct RadixItem_ *swap(new RadixItem_[count * 2]);
485 for (size_t i(0); i != count; ++i) {
486 RadixItem_ &item(swap[i]);
489 id object([self objectAtIndex:i]);
492 [invocation setTarget:object];
494 [invocation getReturnValue:&item.key];
496 item.key = imp(object, selector, object);
500 RadixSort_(self, count, swap);
503 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
504 size_t count([self count]);
505 struct RadixItem_ *swap(new RadixItem_[count * 2]);
507 for (size_t i(0); i != count; ++i) {
508 RadixItem_ &item(swap[i]);
511 id object([self objectAtIndex:i]);
512 item.key = function(object, argument);
515 RadixSort_(self, count, swap);
520 /* Insertion Sort {{{ */
522 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
523 const char *ptr = (const char *)list;
525 CFIndex half = count / 2;
526 const char *probe = ptr + elementSize * half;
527 CFComparisonResult cr = comparator(element, probe, context);
528 if (0 == cr) return (probe - (const char *)list) / elementSize;
529 ptr = (cr < 0) ? ptr : probe + elementSize;
530 count = (cr < 0) ? half : (half + (count & 1) - 1);
532 return (ptr - (const char *)list) / elementSize;
535 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
536 const char *ptr = (const char *)list;
538 CFIndex half = count / 2;
539 const char *probe = ptr + elementSize * half;
540 CFComparisonResult cr = comparator(element, probe, context);
541 if (0 == cr) return (probe - (const char *)list) / elementSize;
542 ptr = (cr < 0) ? ptr : probe + elementSize;
543 count = (cr < 0) ? half : (half + (count & 1) - 1);
545 return (ptr - (const char *)list) / elementSize;
548 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
549 if (range.length == 0)
551 const void **values(new const void *[range.length]);
552 CFArrayGetValues(array, range, values);
554 #if HistogramInsertionSort
555 uint32_t total(0), *offsets(new uint32_t[range.length]);
558 for (CFIndex index(1); index != range.length; ++index) {
559 const void *value(values[index]);
560 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
561 CFIndex correct(index);
562 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
565 if (correct != index) {
566 size_t offset(index - correct);
567 #if HistogramInsertionSort
571 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
573 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
574 values[correct] = value;
578 CFArrayReplaceValues(array, range, values, range.length);
581 #if HistogramInsertionSort
582 for (CFIndex index(0); index != range.length; ++index)
583 if (offsets[index] != 0)
584 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
585 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
592 /* Apple Bug Fixes {{{ */
593 @implementation UIWebDocumentView (Cydia)
595 - (void) _setScrollerOffset:(CGPoint)offset {
596 UIScroller *scroller([self _scroller]);
598 CGSize size([scroller contentSize]);
599 CGSize bounds([scroller bounds].size);
602 max.x = size.width - bounds.width;
603 max.y = size.height - bounds.height;
611 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
612 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
614 [scroller setOffset:offset];
620 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
621 size_t length([self length] - state->state);
624 else if (length > count)
626 for (size_t i(0); i != length; ++i)
627 objects[i] = [self item:state->state++];
628 state->itemsPtr = objects;
629 state->mutationsPtr = (unsigned long *) self;
633 @interface NSString (UIKit)
634 - (NSString *) stringByAddingPercentEscapes;
637 /* Cydia NSString Additions {{{ */
638 @interface NSString (Cydia)
639 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
640 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
641 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
642 - (NSComparisonResult) compareByPath:(NSString *)other;
643 - (NSString *) stringByCachingURLWithCurrentCDN;
644 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
647 @implementation NSString (Cydia)
649 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
650 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
653 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
654 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
655 memcpy(data, bytes, length);
656 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
659 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
660 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
663 - (NSComparisonResult) compareByPath:(NSString *)other {
664 NSString *prefix = [self commonPrefixWithString:other options:0];
665 size_t length = [prefix length];
667 NSRange lrange = NSMakeRange(length, [self length] - length);
668 NSRange rrange = NSMakeRange(length, [other length] - length);
670 lrange = [self rangeOfString:@"/" options:0 range:lrange];
671 rrange = [other rangeOfString:@"/" options:0 range:rrange];
673 NSComparisonResult value;
675 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
676 value = NSOrderedSame;
677 else if (lrange.location == NSNotFound)
678 value = NSOrderedAscending;
679 else if (rrange.location == NSNotFound)
680 value = NSOrderedDescending;
682 value = NSOrderedSame;
684 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
685 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
686 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
687 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
689 NSComparisonResult result = [lpath compare:rpath];
690 return result == NSOrderedSame ? value : result;
693 - (NSString *) stringByCachingURLWithCurrentCDN {
695 stringByReplacingOccurrencesOfString:@"://"
696 withString:@"://ne.edgecastcdn.net/8003A4/"
698 /* XXX: this is somewhat inaccurate */
699 range:NSMakeRange(0, 10)
703 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
704 return [(id)CFURLCreateStringByAddingPercentEscapes(
709 kCFStringEncodingUTF8
716 /* C++ NSString Wrapper Cache {{{ */
723 _finline void clear_() {
724 if (cache_ != NULL) {
731 _finline bool empty() const {
735 _finline size_t size() const {
739 _finline char *data() const {
743 _finline void clear() {
748 _finline CYString() :
755 _finline ~CYString() {
759 void operator =(const CYString &rhs) {
763 if (rhs.cache_ == nil)
766 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
769 void set(apr_pool_t *pool, const char *data, size_t size) {
775 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
776 memcpy(temp, data, size);
783 _finline void set(apr_pool_t *pool, const char *data) {
784 set(pool, data, data == NULL ? 0 : strlen(data));
787 _finline void set(apr_pool_t *pool, const std::string &rhs) {
788 set(pool, rhs.data(), rhs.size());
791 bool operator ==(const CYString &rhs) const {
792 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
795 operator CFStringRef() {
796 if (cache_ == NULL) {
799 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
803 _finline operator id() {
804 return (NSString *) static_cast<CFStringRef>(*this);
808 /* C++ NSString Algorithm Adapters {{{ */
810 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
813 struct NSStringMapHash :
814 std::unary_function<NSString *, size_t>
816 _finline size_t operator ()(NSString *value) const {
817 return CFStringHashNSString((CFStringRef) value);
821 struct NSStringMapLess :
822 std::binary_function<NSString *, NSString *, bool>
824 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
825 return [lhs compare:rhs] == NSOrderedAscending;
829 struct NSStringMapEqual :
830 std::binary_function<NSString *, NSString *, bool>
832 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
833 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
834 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
835 //[lhs isEqualToString:rhs];
840 /* Perl-Compatible RegEx {{{ */
850 Pcre(const char *regex) :
855 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
858 lprintf("%d:%s\n", offset, error);
862 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
863 matches_ = new int[(capture_ + 1) * 3];
871 NSString *operator [](size_t match) {
872 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
875 bool operator ()(NSString *data) {
876 // XXX: length is for characters, not for bytes
877 return operator ()([data UTF8String], [data length]);
880 bool operator ()(const char *data, size_t size) {
882 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
886 /* Mime Addresses {{{ */
887 @interface Address : NSObject {
893 - (NSString *) address;
895 - (void) setAddress:(NSString *)address;
897 + (Address *) addressWithString:(NSString *)string;
898 - (Address *) initWithString:(NSString *)string;
901 @implementation Address
910 - (NSString *) name {
914 - (NSString *) address {
918 - (void) setAddress:(NSString *)address {
920 [address_ autorelease];
924 address_ = [address retain];
927 + (Address *) addressWithString:(NSString *)string {
928 return [[[Address alloc] initWithString:string] autorelease];
931 + (NSArray *) _attributeKeys {
932 return [NSArray arrayWithObjects:@"address", @"name", nil];
935 - (NSArray *) attributeKeys {
936 return [[self class] _attributeKeys];
939 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
940 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
943 - (Address *) initWithString:(NSString *)string {
944 if ((self = [super init]) != nil) {
945 const char *data = [string UTF8String];
946 size_t size = [string length];
948 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
950 if (address_r(data, size)) {
951 name_ = [address_r[1] retain];
952 address_ = [address_r[2] retain];
954 name_ = [string retain];
962 /* CoreGraphics Primitives {{{ */
973 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
976 Set(space, red, green, blue, alpha);
981 CGColorRelease(color_);
988 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
990 float color[] = {red, green, blue, alpha};
991 color_ = CGColorCreate(space, color);
994 operator CGColorRef() {
1000 /* Random Global Variables {{{ */
1001 static const int PulseInterval_ = 50000;
1002 static const int ButtonBarHeight_ = 48;
1003 static const float KeyboardTime_ = 0.3f;
1006 static NSArray *Finishes_;
1008 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1009 #define NotifyConfig_ "/etc/notify.conf"
1011 static bool Queuing_;
1013 static CGColor Blue_;
1014 static CGColor Blueish_;
1015 static CGColor Black_;
1016 static CGColor Off_;
1017 static CGColor White_;
1018 static CGColor Gray_;
1019 static CGColor Green_;
1020 static CGColor Purple_;
1021 static CGColor Purplish_;
1023 static UIColor *InstallingColor_;
1024 static UIColor *RemovingColor_;
1026 static NSString *App_;
1027 static NSString *Home_;
1029 static BOOL Advanced_;
1030 static BOOL Ignored_;
1032 static UIFont *Font12_;
1033 static UIFont *Font12Bold_;
1034 static UIFont *Font14_;
1035 static UIFont *Font18Bold_;
1036 static UIFont *Font22Bold_;
1038 static const char *Machine_ = NULL;
1039 static const NSString *System_ = NULL;
1040 static const NSString *SerialNumber_ = nil;
1041 static const NSString *ChipID_ = nil;
1042 static const NSString *UniqueID_ = nil;
1043 static const NSString *Build_ = nil;
1044 static const NSString *Product_ = nil;
1045 static const NSString *Safari_ = nil;
1047 static CFLocaleRef Locale_;
1048 static NSArray *Languages_;
1049 static CGColorSpaceRef space_;
1051 static bool reload_;
1053 static NSDictionary *SectionMap_;
1054 static NSMutableDictionary *Metadata_;
1055 static _transient NSMutableDictionary *Settings_;
1056 static _transient NSString *Role_;
1057 static _transient NSMutableDictionary *Packages_;
1058 static _transient NSMutableDictionary *Sections_;
1059 static _transient NSMutableDictionary *Sources_;
1060 static bool Changed_;
1061 static NSDate *now_;
1064 static NSMutableArray *Documents_;
1068 /* Display Helpers {{{ */
1069 inline float Interpolate(float begin, float end, float fraction) {
1070 return (end - begin) * fraction + begin;
1073 /* XXX: localize this! */
1074 NSString *SizeString(double size) {
1075 bool negative = size < 0;
1080 while (size > 1024) {
1085 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1087 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1090 static _finline CFStringRef CFCString(const char *value) {
1091 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1094 const char *StripVersion_(const char *version) {
1095 const char *colon(strchr(version, ':'));
1097 version = colon + 1;
1101 CFStringRef StripVersion(const char *version) {
1102 const char *colon(strchr(version, ':'));
1104 version = colon + 1;
1105 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1107 return CFCString(version);
1110 NSString *LocalizeSection(NSString *section) {
1111 static Pcre title_r("^(.*?) \\((.*)\\)$");
1112 if (title_r(section)) {
1113 NSString *parent(title_r[1]);
1114 NSString *child(title_r[2]);
1116 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1117 LocalizeSection(parent),
1118 LocalizeSection(child)
1122 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1125 NSString *Simplify(NSString *title) {
1126 const char *data = [title UTF8String];
1127 size_t size = [title length];
1129 static Pcre square_r("^\\[(.*)\\]$");
1130 if (square_r(data, size))
1131 return Simplify(square_r[1]);
1133 static Pcre paren_r("^\\((.*)\\)$");
1134 if (paren_r(data, size))
1135 return Simplify(paren_r[1]);
1137 static Pcre title_r("^(.*?) \\((.*)\\)$");
1138 if (title_r(data, size))
1139 return Simplify(title_r[1]);
1145 NSString *GetLastUpdate() {
1146 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1149 return UCLocalize("NEVER_OR_UNKNOWN");
1151 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1152 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1154 CFRelease(formatter);
1156 return [(NSString *) formatted autorelease];
1159 bool isSectionVisible(NSString *section) {
1160 NSDictionary *metadata([Sections_ objectForKey:section]);
1161 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1162 return hidden == nil || ![hidden boolValue];
1165 /* Delegate Prototypes {{{ */
1169 @interface NSObject (ProgressDelegate)
1172 @protocol ProgressDelegate
1173 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1174 - (void) setProgressTitle:(NSString *)title;
1175 - (void) setProgressPercent:(float)percent;
1176 - (void) startProgress;
1177 - (void) addProgressOutput:(NSString *)output;
1178 - (bool) isCancelling:(size_t)received;
1181 @protocol ConfigurationDelegate
1182 - (void) repairWithSelector:(SEL)selector;
1183 - (void) setConfigurationData:(NSString *)data;
1188 @protocol CydiaDelegate
1189 - (void) setPackageView:(PackageView *)view;
1190 - (void) clearPackage:(Package *)package;
1191 - (void) installPackage:(Package *)package;
1192 - (void) removePackage:(Package *)package;
1193 - (void) slideUp:(UIActionSheet *)alert;
1194 - (void) distUpgrade;
1195 - (void) updateData;
1197 - (void) askForSettings;
1198 - (UIProgressHUD *) addProgressHUD;
1199 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1200 - (RVPage *) pageForPackage:(NSString *)name;
1201 - (PackageView *) packageView;
1205 /* Status Delegation {{{ */
1207 public pkgAcquireStatus
1210 _transient NSObject<ProgressDelegate> *delegate_;
1218 void setDelegate(id delegate) {
1219 delegate_ = delegate;
1222 NSObject<ProgressDelegate> *getDelegate() const {
1226 virtual bool MediaChange(std::string media, std::string drive) {
1230 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1233 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1234 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1235 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1238 virtual void Done(pkgAcquire::ItemDesc &item) {
1241 virtual void Fail(pkgAcquire::ItemDesc &item) {
1243 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1244 item.Owner->Status == pkgAcquire::Item::StatDone
1248 std::string &error(item.Owner->ErrorText);
1252 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1253 NSArray *fields([description componentsSeparatedByString:@" "]);
1254 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1256 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1257 withObject:[NSArray arrayWithObjects:
1258 [NSString stringWithUTF8String:error.c_str()],
1265 virtual bool Pulse(pkgAcquire *Owner) {
1266 bool value = pkgAcquireStatus::Pulse(Owner);
1269 double(CurrentBytes + CurrentItems) /
1270 double(TotalBytes + TotalItems)
1273 [delegate_ setProgressPercent:percent];
1274 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1277 virtual void Start() {
1278 [delegate_ startProgress];
1281 virtual void Stop() {
1285 /* Progress Delegation {{{ */
1290 _transient id<ProgressDelegate> delegate_;
1294 virtual void Update() {
1295 /*if (abs(Percent - percent_) > 2)
1296 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1300 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1301 [delegate_ setProgressPercent:(Percent / 100)];*/
1311 void setDelegate(id delegate) {
1312 delegate_ = delegate;
1315 id getDelegate() const {
1319 virtual void Done() {
1321 //[delegate_ setProgressPercent:1];
1326 /* Database Interface {{{ */
1327 typedef std::map< unsigned long, _H<Source> > SourceMap;
1329 @interface Database : NSObject {
1335 pkgCacheFile cache_;
1336 pkgDepCache::Policy *policy_;
1337 pkgRecords *records_;
1338 pkgProblemResolver *resolver_;
1339 pkgAcquire *fetcher_;
1341 SPtr<pkgPackageManager> manager_;
1342 pkgSourceList *list_;
1345 NSMutableArray *packages_;
1347 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1356 + (Database *) sharedInstance;
1359 - (void) _readCydia:(NSNumber *)fd;
1360 - (void) _readStatus:(NSNumber *)fd;
1361 - (void) _readOutput:(NSNumber *)fd;
1365 - (Package *) packageWithName:(NSString *)name;
1367 - (pkgCacheFile &) cache;
1368 - (pkgDepCache::Policy *) policy;
1369 - (pkgRecords *) records;
1370 - (pkgProblemResolver *) resolver;
1371 - (pkgAcquire &) fetcher;
1372 - (pkgSourceList &) list;
1373 - (NSArray *) packages;
1374 - (NSArray *) sources;
1375 - (void) reloadData;
1383 - (void) setVisible;
1385 - (void) updateWithStatus:(Status &)status;
1387 - (void) setDelegate:(id)delegate;
1388 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1391 /* Delegate Helpers {{{ */
1392 @implementation NSObject(ProgressDelegate)
1394 - (void) _setProgressErrorPackage:(NSArray *)args {
1395 [self performSelector:@selector(setProgressError:forPackage:)
1396 withObject:[args objectAtIndex:0]
1397 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1401 - (void) _setProgressErrorTitle:(NSArray *)args {
1402 [self performSelector:@selector(setProgressError:withTitle:)
1403 withObject:[args objectAtIndex:0]
1404 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1408 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1409 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1410 withObject:[NSArray arrayWithObjects:error, title, nil]
1415 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1416 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1417 // XXX: holy typecast batman!
1418 [(id<ProgressDelegate>)self setProgressError:error withTitle:(package == nil ? id : [package name])];
1424 /* Source Class {{{ */
1425 @interface Source : NSObject {
1426 CYString depiction_;
1427 CYString description_;
1433 CYString distribution_;
1438 NSString *authority_;
1440 CYString defaultIcon_;
1442 NSDictionary *record_;
1446 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1448 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1450 - (NSString *) depictionForPackage:(NSString *)package;
1451 - (NSString *) supportForPackage:(NSString *)package;
1453 - (NSDictionary *) record;
1457 - (NSString *) distribution;
1458 - (NSString *) type;
1460 - (NSString *) host;
1462 - (NSString *) name;
1463 - (NSString *) description;
1464 - (NSString *) label;
1465 - (NSString *) origin;
1466 - (NSString *) version;
1468 - (NSString *) defaultIcon;
1472 @implementation Source
1476 distribution_.clear();
1479 description_.clear();
1485 defaultIcon_.clear();
1487 if (record_ != nil) {
1497 if (authority_ != nil) {
1498 [authority_ release];
1508 + (NSArray *) _attributeKeys {
1509 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1512 - (NSArray *) attributeKeys {
1513 return [[self class] _attributeKeys];
1516 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1517 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1520 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1523 trusted_ = index->IsTrusted();
1525 uri_.set(pool, index->GetURI());
1526 distribution_.set(pool, index->GetDist());
1527 type_.set(pool, index->GetType());
1529 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1530 if (dindex != NULL) {
1532 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1535 pkgTagFile tags(&fd);
1537 pkgTagSection section;
1544 {"default-icon", &defaultIcon_},
1545 {"depiction", &depiction_},
1546 {"description", &description_},
1548 {"origin", &origin_},
1549 {"support", &support_},
1550 {"version", &version_},
1553 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1554 const char *start, *end;
1556 if (section.Find(names[i].name_, start, end)) {
1557 CYString &value(*names[i].value_);
1558 value.set(pool, start, end - start);
1564 record_ = [Sources_ objectForKey:[self key]];
1566 record_ = [record_ retain];
1568 NSURL *url([NSURL URLWithString:uri_]);
1572 host_ = [[host_ lowercaseString] retain];
1577 authority_ = [url path];
1579 if (authority_ != nil)
1580 authority_ = [authority_ retain];
1583 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1584 if ((self = [super init]) != nil) {
1585 [self setMetaIndex:index inPool:pool];
1589 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1590 NSDictionary *lhr = [self record];
1591 NSDictionary *rhr = [source record];
1594 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1596 NSString *lhs = [self name];
1597 NSString *rhs = [source name];
1599 if ([lhs length] != 0 && [rhs length] != 0) {
1600 unichar lhc = [lhs characterAtIndex:0];
1601 unichar rhc = [rhs characterAtIndex:0];
1603 if (isalpha(lhc) && !isalpha(rhc))
1604 return NSOrderedAscending;
1605 else if (!isalpha(lhc) && isalpha(rhc))
1606 return NSOrderedDescending;
1609 return [lhs compare:rhs options:LaxCompareOptions_];
1612 - (NSString *) depictionForPackage:(NSString *)package {
1613 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1616 - (NSString *) supportForPackage:(NSString *)package {
1617 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1620 - (NSDictionary *) record {
1628 - (NSString *) uri {
1632 - (NSString *) distribution {
1633 return distribution_;
1636 - (NSString *) type {
1640 - (NSString *) key {
1641 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1644 - (NSString *) host {
1648 - (NSString *) name {
1649 return origin_.empty() ? authority_ : origin_;
1652 - (NSString *) description {
1653 return description_;
1656 - (NSString *) label {
1657 return label_.empty() ? authority_ : label_;
1660 - (NSString *) origin {
1664 - (NSString *) version {
1668 - (NSString *) defaultIcon {
1669 return defaultIcon_;
1674 /* Relationship Class {{{ */
1675 @interface Relationship : NSObject {
1680 - (NSString *) type;
1682 - (NSString *) name;
1686 @implementation Relationship
1694 - (NSString *) type {
1702 - (NSString *) name {
1709 /* Package Class {{{ */
1710 @interface Package : NSObject {
1714 pkgCache::VerIterator version_;
1715 pkgCache::PkgIterator iterator_;
1716 _transient Database *database_;
1717 pkgCache::VerFileIterator file_;
1724 NSString *section$_;
1730 CYString installed_;
1736 CYString depiction_;
1747 NSMutableArray *tags_;
1750 NSArray *relationships_;
1752 NSMutableDictionary *metadata_;
1753 _transient NSDate *firstSeen_;
1754 _transient NSDate *lastSeen_;
1758 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1759 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1761 - (pkgCache::PkgIterator) iterator;
1764 - (NSString *) section;
1765 - (NSString *) simpleSection;
1767 - (NSString *) longSection;
1768 - (NSString *) shortSection;
1772 - (Address *) maintainer;
1774 - (NSString *) longDescription;
1775 - (NSString *) shortDescription;
1778 - (NSMutableDictionary *) metadata;
1780 - (BOOL) subscribed;
1783 - (NSString *) latest;
1784 - (NSString *) installed;
1785 - (BOOL) uninstalled;
1788 - (BOOL) upgradableAndEssential:(BOOL)essential;
1791 - (BOOL) unfiltered;
1795 - (BOOL) halfConfigured;
1796 - (BOOL) halfInstalled;
1798 - (NSString *) mode;
1800 - (void) setVisible;
1803 - (NSString *) name;
1805 - (NSString *) homepage;
1806 - (NSString *) depiction;
1807 - (Address *) author;
1809 - (NSString *) support;
1811 - (NSArray *) files;
1812 - (NSArray *) relationships;
1813 - (NSArray *) warnings;
1814 - (NSArray *) applications;
1816 - (Source *) source;
1817 - (NSString *) role;
1819 - (BOOL) matches:(NSString *)text;
1821 - (bool) hasSupportingRole;
1822 - (BOOL) hasTag:(NSString *)tag;
1823 - (NSString *) primaryPurpose;
1824 - (NSArray *) purposes;
1825 - (bool) isCommercial;
1827 - (CYString &) cyname;
1829 - (uint32_t) compareBySection:(NSArray *)sections;
1831 - (uint32_t) compareForChanges;
1836 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1837 - (bool) isInstalledAndVisible:(NSNumber *)number;
1838 - (bool) isVisibleInSection:(NSString *)section;
1839 - (bool) isVisibleInSource:(Source *)source;
1843 uint32_t PackageChangesRadix(Package *self, void *) {
1848 uint32_t timestamp : 30;
1849 uint32_t ignored : 1;
1850 uint32_t upgradable : 1;
1854 bool upgradable([self upgradableAndEssential:YES]);
1855 value.bits.upgradable = upgradable ? 1 : 0;
1858 value.bits.timestamp = 0;
1859 value.bits.ignored = [self ignored] ? 0 : 1;
1860 value.bits.upgradable = 1;
1862 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1863 value.bits.ignored = 0;
1864 value.bits.upgradable = 0;
1867 return _not(uint32_t) - value.key;
1870 _finline static void Stifle(uint8_t &value) {
1873 uint32_t PackagePrefixRadix(Package *self, void *context) {
1874 size_t offset(reinterpret_cast<size_t>(context));
1875 CYString &name([self cyname]);
1877 size_t size(name.size());
1880 char *text(name.data());
1883 if (!isdigit(text[0]))
1887 while (size != digits && isdigit(text[digits]))
1897 if (offset == 0 && zeros != 0) {
1898 memset(data, '0', zeros);
1899 memcpy(data + zeros, text, 4 - zeros);
1901 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1902 if (size <= offset - zeros)
1905 text += offset - zeros;
1906 size -= offset - zeros;
1909 memcpy(data, text, 4);
1911 memcpy(data, text, size);
1912 memset(data + size, 0, 4 - size);
1915 for (size_t i(0); i != 4; ++i)
1916 if (isalpha(data[i]))
1921 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1923 /* XXX: ntohl may be more honest */
1924 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1927 CYString &(*PackageName)(Package *self, SEL sel);
1929 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1930 _profile(PackageNameCompare)
1931 CYString &lhi(PackageName(lhs, @selector(cyname)));
1932 CYString &rhi(PackageName(rhs, @selector(cyname)));
1933 CFStringRef lhn(lhi), rhn(rhi);
1936 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1937 else if (rhn == NULL)
1938 return NSOrderedDescending;
1940 _profile(PackageNameCompare$NumbersLast)
1941 if (!lhi.empty() && !rhi.empty()) {
1942 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1943 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1944 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1945 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1946 return lha ? NSOrderedAscending : NSOrderedDescending;
1950 CFIndex length = CFStringGetLength(lhn);
1952 _profile(PackageNameCompare$Compare)
1953 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1958 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1959 return PackageNameCompare(*lhs, *rhs, context);
1962 struct PackageNameOrdering :
1963 std::binary_function<Package *, Package *, bool>
1965 _finline bool operator ()(Package *lhs, Package *rhs) const {
1966 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1970 @implementation Package
1972 - (NSString *) description {
1973 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1979 if (section$_ != nil)
1980 [section$_ release];
1985 if (sponsor$_ != nil)
1986 [sponsor$_ release];
1987 if (author$_ != nil)
1994 if (relationships_ != nil)
1995 [relationships_ release];
1996 if (metadata_ != nil)
1997 [metadata_ release];
2002 + (NSString *) webScriptNameForSelector:(SEL)selector {
2003 if (selector == @selector(hasTag:))
2009 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2010 return [self webScriptNameForSelector:selector] == nil;
2013 + (NSArray *) _attributeKeys {
2014 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];
2017 - (NSArray *) attributeKeys {
2018 return [[self class] _attributeKeys];
2021 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2022 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2032 _profile(Package$parse)
2033 pkgRecords::Parser *parser;
2035 _profile(Package$parse$Lookup)
2036 parser = &[database_ records]->Lookup(file_);
2041 _profile(Package$parse$Find)
2047 {"depiction", &depiction_},
2048 {"homepage", &homepage_},
2049 {"website", &website},
2051 {"support", &support_},
2052 {"sponsor", &sponsor_},
2053 {"author", &author_},
2056 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2057 const char *start, *end;
2059 if (parser->Find(names[i].name_, start, end)) {
2060 CYString &value(*names[i].value_);
2061 _profile(Package$parse$Value)
2062 value.set(pool_, start, end - start);
2068 _profile(Package$parse$Tagline)
2069 const char *start, *end;
2070 if (parser->ShortDesc(start, end)) {
2071 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2074 while (stop != start && stop[-1] == '\r')
2076 tagline_.set(pool_, start, stop - start);
2080 _profile(Package$parse$Retain)
2081 if (homepage_.empty())
2082 homepage_ = website;
2083 if (homepage_ == depiction_)
2089 - (void) setVisible {
2090 visible_ = required_ && [self hasSupportingRole] && [self unfiltered];
2093 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2094 if ((self = [super init]) != nil) {
2095 _profile(Package$initWithVersion)
2096 @synchronized (database) {
2097 era_ = [database era];
2101 iterator_ = version.ParentPkg();
2102 database_ = database;
2104 _profile(Package$initWithVersion$Latest)
2105 latest_ = (NSString *) StripVersion(version_.VerStr());
2108 pkgCache::VerIterator current;
2109 _profile(Package$initWithVersion$Versions)
2110 current = iterator_.CurrentVer();
2112 installed_.set(pool_, StripVersion_(current.VerStr()));
2114 if (!version_.end())
2115 file_ = version_.FileList();
2117 pkgCache &cache([database_ cache]);
2118 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2122 _profile(Package$initWithVersion$Name)
2123 id_.set(pool_, iterator_.Name());
2124 name_.set(pool, iterator_.Display());
2128 _profile(Package$initWithVersion$Source)
2129 source_ = [database_ getSource:file_.File()];
2138 _profile(Package$initWithVersion$Tags)
2139 pkgCache::TagIterator tag(iterator_.TagList());
2141 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2143 const char *name(tag.Name());
2144 [tags_ addObject:(NSString *)CFCString(name)];
2145 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2146 role_ = (NSString *) CFCString(name + 6);
2147 if (required_ && strncmp(name, "require::", 9) == 0 && (
2152 } while (!tag.end());
2156 bool changed(false);
2157 NSString *key([id_ lowercaseString]);
2159 _profile(Package$initWithVersion$Metadata)
2160 metadata_ = [Packages_ objectForKey:key];
2162 if (metadata_ == nil) {
2165 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2166 firstSeen_, @"FirstSeen",
2167 latest_, @"LastVersion",
2172 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2173 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2175 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2176 subscribed_ = [subscribed boolValue];
2178 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2180 if (firstSeen_ == nil) {
2181 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2182 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2186 if (version == nil) {
2187 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2190 if (![version isEqualToString:latest_]) {
2191 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2193 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2198 metadata_ = [metadata_ retain];
2201 [Packages_ setObject:metadata_ forKey:key];
2206 _profile(Package$initWithVersion$Section)
2207 section_.set(pool_, iterator_.Section());
2210 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2212 } _end } return self;
2215 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2216 @synchronized ([Database class]) {
2217 pkgCache::VerIterator version;
2219 _profile(Package$packageWithIterator$GetCandidateVer)
2220 version = [database policy]->GetCandidateVer(iterator);
2226 return [[[Package alloc]
2227 initWithVersion:version
2234 - (pkgCache::PkgIterator) iterator {
2238 - (NSString *) section {
2239 if (section$_ == nil) {
2240 if (section_.empty())
2243 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2244 NSString *name(section_);
2247 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2248 if (NSString *rename = [value objectForKey:@"Rename"]) {
2253 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2257 - (NSString *) simpleSection {
2258 if (NSString *section = [self section])
2259 return Simplify(section);
2264 - (NSString *) longSection {
2265 return LocalizeSection([self section]);
2268 - (NSString *) shortSection {
2269 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2272 - (NSString *) uri {
2275 pkgIndexFile *index;
2276 pkgCache::PkgFileIterator file(file_.File());
2277 if (![database_ list].FindIndex(file, index))
2279 return [NSString stringWithUTF8String:iterator_->Path];
2280 //return [NSString stringWithUTF8String:file.Site()];
2281 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2285 - (Address *) maintainer {
2288 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2289 const std::string &maintainer(parser->Maintainer());
2290 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2294 return version_.end() ? 0 : version_->InstalledSize;
2297 - (NSString *) longDescription {
2300 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2301 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2303 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2304 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2305 if ([lines count] < 2)
2308 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2309 for (size_t i(1), e([lines count]); i != e; ++i) {
2310 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2311 [trimmed addObject:trim];
2314 return [trimmed componentsJoinedByString:@"\n"];
2317 - (NSString *) shortDescription {
2322 _profile(Package$index)
2323 CFStringRef name((CFStringRef) [self name]);
2324 if (CFStringGetLength(name) == 0)
2326 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2327 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2329 return toupper(character);
2333 - (NSMutableDictionary *) metadata {
2338 if (subscribed_ && lastSeen_ != nil)
2343 - (BOOL) subscribed {
2348 NSDictionary *metadata([self metadata]);
2349 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2350 return [ignored boolValue];
2355 - (NSString *) latest {
2359 - (NSString *) installed {
2363 - (BOOL) uninstalled {
2364 return installed_.empty();
2368 return !version_.end();
2371 - (BOOL) upgradableAndEssential:(BOOL)essential {
2372 _profile(Package$upgradableAndEssential)
2373 pkgCache::VerIterator current(iterator_.CurrentVer());
2375 return essential && essential_ && visible_;
2377 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2381 - (BOOL) essential {
2386 return [database_ cache][iterator_].InstBroken();
2389 - (BOOL) unfiltered {
2390 NSString *section([self section]);
2391 return section == nil || isSectionVisible(section);
2399 unsigned char current(iterator_->CurrentState);
2400 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2403 - (BOOL) halfConfigured {
2404 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2407 - (BOOL) halfInstalled {
2408 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2412 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2413 return state.Mode != pkgDepCache::ModeKeep;
2416 - (NSString *) mode {
2417 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2419 switch (state.Mode) {
2420 case pkgDepCache::ModeDelete:
2421 if ((state.iFlags & pkgDepCache::Purge) != 0)
2425 case pkgDepCache::ModeKeep:
2426 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2427 return @"REINSTALL";
2428 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2432 case pkgDepCache::ModeInstall:
2433 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2434 return @"REINSTALL";
2435 else*/ switch (state.Status) {
2437 return @"DOWNGRADE";
2443 return @"NEW_INSTALL";
2454 - (NSString *) name {
2455 return name_.empty() ? id_ : name_;
2458 - (UIImage *) icon {
2459 NSString *section = [self simpleSection];
2463 if ([icon_ hasPrefix:@"file:///"])
2464 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2465 if (icon == nil) if (section != nil)
2466 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2467 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2468 if ([dicon hasPrefix:@"file:///"])
2469 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2471 icon = [UIImage applicationImageNamed:@"unknown.png"];
2475 - (NSString *) homepage {
2479 - (NSString *) depiction {
2480 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2483 - (Address *) sponsor {
2484 if (sponsor$_ == nil) {
2485 if (sponsor_.empty())
2487 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2491 - (Address *) author {
2492 if (author$_ == nil) {
2493 if (author_.empty())
2495 author$_ = [[Address addressWithString:author_] retain];
2499 - (NSString *) support {
2500 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2503 - (NSArray *) files {
2504 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2505 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2508 fin.open([path UTF8String]);
2513 while (std::getline(fin, line))
2514 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2519 - (NSArray *) relationships {
2520 return relationships_;
2523 - (NSArray *) warnings {
2524 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2525 const char *name(iterator_.Name());
2527 size_t length(strlen(name));
2528 if (length < 2) invalid:
2529 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2530 else for (size_t i(0); i != length; ++i)
2532 /* XXX: technically this is not allowed */
2533 (name[i] < 'A' || name[i] > 'Z') &&
2534 (name[i] < 'a' || name[i] > 'z') &&
2535 (name[i] < '0' || name[i] > '9') &&
2536 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2539 if (strcmp(name, "cydia") != 0) {
2542 bool _private = false;
2545 bool repository = [[self section] isEqualToString:@"Repositories"];
2547 if (NSArray *files = [self files])
2548 for (NSString *file in files)
2549 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2551 else if (!user && [file isEqualToString:@"/User"])
2553 else if (!_private && [file isEqualToString:@"/private"])
2555 else if (!stash && [file isEqualToString:@"/var/stash"])
2558 /* XXX: this is not sensitive enough. only some folders are valid. */
2559 if (cydia && !repository)
2560 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2562 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2564 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2566 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2569 return [warnings count] == 0 ? nil : warnings;
2572 - (NSArray *) applications {
2573 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2575 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2577 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2578 if (NSArray *files = [self files])
2579 for (NSString *file in files)
2580 if (application_r(file)) {
2581 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2582 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2583 if ([id isEqualToString:me])
2586 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2588 display = application_r[1];
2590 NSString *bundle([file stringByDeletingLastPathComponent]);
2591 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2592 if (icon == nil || [icon length] == 0)
2594 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2596 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2597 [applications addObject:application];
2599 [application addObject:id];
2600 [application addObject:display];
2601 [application addObject:url];
2604 return [applications count] == 0 ? nil : applications;
2607 - (Source *) source {
2609 @synchronized (database_) {
2610 if ([database_ era] != era_ || file_.end())
2613 source_ = [database_ getSource:file_.File()];
2625 - (NSString *) role {
2629 - (BOOL) matches:(NSString *)text {
2635 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2636 if (range.location != NSNotFound)
2639 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2640 if (range.location != NSNotFound)
2643 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2644 if (range.location != NSNotFound)
2650 - (bool) hasSupportingRole {
2653 if ([role_ isEqualToString:@"enduser"])
2655 if ([Role_ isEqualToString:@"User"])
2657 if ([role_ isEqualToString:@"hacker"])
2659 if ([Role_ isEqualToString:@"Hacker"])
2661 if ([role_ isEqualToString:@"developer"])
2663 if ([Role_ isEqualToString:@"Developer"])
2668 - (BOOL) hasTag:(NSString *)tag {
2669 return tags_ == nil ? NO : [tags_ containsObject:tag];
2672 - (NSString *) primaryPurpose {
2673 for (NSString *tag in tags_)
2674 if ([tag hasPrefix:@"purpose::"])
2675 return [tag substringFromIndex:9];
2679 - (NSArray *) purposes {
2680 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2681 for (NSString *tag in tags_)
2682 if ([tag hasPrefix:@"purpose::"])
2683 [purposes addObject:[tag substringFromIndex:9]];
2684 return [purposes count] == 0 ? nil : purposes;
2687 - (bool) isCommercial {
2688 return [self hasTag:@"cydia::commercial"];
2691 - (CYString &) cyname {
2692 return name_.empty() ? id_ : name_;
2695 - (uint32_t) compareBySection:(NSArray *)sections {
2696 NSString *section([self section]);
2697 for (size_t i(0), e([sections count]); i != e; ++i) {
2698 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2702 return _not(uint32_t);
2705 - (uint32_t) compareForChanges {
2710 uint32_t timestamp : 30;
2711 uint32_t ignored : 1;
2712 uint32_t upgradable : 1;
2716 bool upgradable([self upgradableAndEssential:YES]);
2717 value.bits.upgradable = upgradable ? 1 : 0;
2720 value.bits.timestamp = 0;
2721 value.bits.ignored = [self ignored] ? 0 : 1;
2722 value.bits.upgradable = 1;
2724 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2725 value.bits.ignored = 0;
2726 value.bits.upgradable = 0;
2729 return _not(uint32_t) - value.key;
2733 pkgProblemResolver *resolver = [database_ resolver];
2734 resolver->Clear(iterator_);
2735 resolver->Protect(iterator_);
2739 pkgProblemResolver *resolver = [database_ resolver];
2740 resolver->Clear(iterator_);
2741 resolver->Protect(iterator_);
2742 pkgCacheFile &cache([database_ cache]);
2743 cache->MarkInstall(iterator_, false);
2744 pkgDepCache::StateCache &state((*cache)[iterator_]);
2745 if (!state.Install())
2746 cache->SetReInstall(iterator_, true);
2750 pkgProblemResolver *resolver = [database_ resolver];
2751 resolver->Clear(iterator_);
2752 resolver->Protect(iterator_);
2753 resolver->Remove(iterator_);
2754 [database_ cache]->MarkDelete(iterator_, true);
2757 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2758 _profile(Package$isUnfilteredAndSearchedForBy)
2761 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2762 value &= [self unfiltered];
2765 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2766 value &= [self matches:search];
2773 - (bool) isInstalledAndVisible:(NSNumber *)number {
2774 return (![number boolValue] || [self visible]) && ![self uninstalled];
2777 - (bool) isVisibleInSection:(NSString *)name {
2778 NSString *section = [self section];
2783 section == nil && [name length] == 0 ||
2784 [name isEqualToString:section]
2788 - (bool) isVisibleInSource:(Source *)source {
2789 return [self source] == source && [self visible];
2794 /* Section Class {{{ */
2795 @interface Section : NSObject {
2800 NSString *localized_;
2803 - (NSComparisonResult) compareByLocalized:(Section *)section;
2804 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2805 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2806 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2807 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2808 - (NSString *) name;
2815 - (void) addToCount;
2817 - (void) setCount:(size_t)count;
2818 - (NSString *) localized;
2822 @implementation Section
2826 if (localized_ != nil)
2827 [localized_ release];
2831 - (NSComparisonResult) compareByLocalized:(Section *)section {
2832 NSString *lhs(localized_);
2833 NSString *rhs([section localized]);
2835 /*if ([lhs length] != 0 && [rhs length] != 0) {
2836 unichar lhc = [lhs characterAtIndex:0];
2837 unichar rhc = [rhs characterAtIndex:0];
2839 if (isalpha(lhc) && !isalpha(rhc))
2840 return NSOrderedAscending;
2841 else if (!isalpha(lhc) && isalpha(rhc))
2842 return NSOrderedDescending;
2845 return [lhs compare:rhs options:LaxCompareOptions_];
2848 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2849 if ((self = [self initWithName:name localize:NO]) != nil) {
2850 if (localized != nil)
2851 localized_ = [localized retain];
2855 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2856 return [self initWithName:name row:0 localize:localize];
2859 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2860 if ((self = [super init]) != nil) {
2861 name_ = [name retain];
2865 localized_ = [LocalizeSection(name_) retain];
2869 /* XXX: localize the index thingees */
2870 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2871 if ((self = [super init]) != nil) {
2872 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2878 - (NSString *) name {
2898 - (void) addToCount {
2902 - (void) setCount:(size_t)count {
2906 - (NSString *) localized {
2913 static NSString *Colon_;
2914 static NSString *Error_;
2915 static NSString *Warning_;
2917 /* Database Implementation {{{ */
2918 @implementation Database
2920 + (Database *) sharedInstance {
2921 static Database *instance;
2922 if (instance == nil)
2923 instance = [[Database alloc] init];
2933 NSRecycleZone(zone_);
2934 // XXX: malloc_destroy_zone(zone_);
2935 apr_pool_destroy(pool_);
2939 - (void) _readCydia:(NSNumber *)fd { _pooled
2940 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2941 std::istream is(&ib);
2944 static Pcre finish_r("^finish:([^:]*)$");
2946 while (std::getline(is, line)) {
2947 const char *data(line.c_str());
2948 size_t size = line.size();
2949 lprintf("C:%s\n", data);
2951 if (finish_r(data, size)) {
2952 NSString *finish = finish_r[1];
2953 int index = [Finishes_ indexOfObject:finish];
2954 if (index != INT_MAX && index > Finish_)
2962 - (void) _readStatus:(NSNumber *)fd { _pooled
2963 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2964 std::istream is(&ib);
2967 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2968 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2970 while (std::getline(is, line)) {
2971 const char *data(line.c_str());
2972 size_t size(line.size());
2973 lprintf("S:%s\n", data);
2975 if (conffile_r(data, size)) {
2976 [delegate_ setConfigurationData:conffile_r[1]];
2977 } else if (strncmp(data, "status: ", 8) == 0) {
2978 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2979 [delegate_ setProgressTitle:string];
2980 } else if (pmstatus_r(data, size)) {
2981 std::string type([pmstatus_r[1] UTF8String]);
2982 NSString *id = pmstatus_r[2];
2984 float percent([pmstatus_r[3] floatValue]);
2985 [delegate_ setProgressPercent:(percent / 100)];
2987 NSString *string = pmstatus_r[4];
2989 if (type == "pmerror")
2990 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
2991 withObject:[NSArray arrayWithObjects:string, id, nil]
2994 else if (type == "pmstatus") {
2995 [delegate_ setProgressTitle:string];
2996 } else if (type == "pmconffile")
2997 [delegate_ setConfigurationData:string];
2999 lprintf("E:unknown pmstatus\n");
3001 lprintf("E:unknown status\n");
3007 - (void) _readOutput:(NSNumber *)fd { _pooled
3008 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3009 std::istream is(&ib);
3012 while (std::getline(is, line)) {
3013 lprintf("O:%s\n", line.c_str());
3014 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3024 - (Package *) packageWithName:(NSString *)name {
3025 @synchronized ([Database class]) {
3026 if (static_cast<pkgDepCache *>(cache_) == NULL)
3028 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3029 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3032 - (Database *) init {
3033 if ((self = [super init]) != nil) {
3040 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3041 apr_pool_create(&pool_, NULL);
3043 packages_ = [[NSMutableArray alloc] init];
3047 _assert(pipe(fds) != -1);
3050 _config->Set("APT::Keep-Fds::", cydiafd_);
3051 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3054 detachNewThreadSelector:@selector(_readCydia:)
3056 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3059 _assert(pipe(fds) != -1);
3063 detachNewThreadSelector:@selector(_readStatus:)
3065 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3068 _assert(pipe(fds) != -1);
3069 _assert(dup2(fds[0], 0) != -1);
3070 _assert(close(fds[0]) != -1);
3072 input_ = fdopen(fds[1], "a");
3074 _assert(pipe(fds) != -1);
3075 _assert(dup2(fds[1], 1) != -1);
3076 _assert(close(fds[1]) != -1);
3079 detachNewThreadSelector:@selector(_readOutput:)
3081 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3086 - (pkgCacheFile &) cache {
3090 - (pkgDepCache::Policy *) policy {
3094 - (pkgRecords *) records {
3098 - (pkgProblemResolver *) resolver {
3102 - (pkgAcquire &) fetcher {
3106 - (pkgSourceList &) list {
3110 - (NSArray *) packages {
3114 - (NSArray *) sources {
3115 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3116 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3117 [sources addObject:i->second];
3121 - (NSArray *) issues {
3122 if (cache_->BrokenCount() == 0)
3125 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3127 for (Package *package in packages_) {
3128 if (![package broken])
3130 pkgCache::PkgIterator pkg([package iterator]);
3132 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3133 [entry addObject:[package name]];
3134 [issues addObject:entry];
3136 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3140 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3141 pkgCache::DepIterator start;
3142 pkgCache::DepIterator end;
3143 dep.GlobOr(start, end); // ++dep
3145 if (!cache_->IsImportantDep(end))
3147 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3150 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3151 [entry addObject:failure];
3152 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3154 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3155 if (Package *package = [self packageWithName:name])
3156 name = [package name];
3157 [failure addObject:name];
3159 pkgCache::PkgIterator target(start.TargetPkg());
3160 if (target->ProvidesList != 0)
3161 [failure addObject:@"?"];
3163 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3165 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3166 else if (!cache_[target].CandidateVerIter(cache_).end())
3167 [failure addObject:@"-"];
3168 else if (target->ProvidesList == 0)
3169 [failure addObject:@"!"];
3171 [failure addObject:@"%"];
3175 if (start.TargetVer() != 0)
3176 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3187 - (bool) popErrorWithTitle:(NSString *)title {
3189 std::string message;
3191 while (!_error->empty()) {
3193 bool warning(!_error->PopMessage(error));
3197 size_t size(error.size());
3198 if (size == 0 || error[size - 1] != '\n')
3200 error.resize(size - 1);
3202 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3204 if (!message.empty())
3209 if (fatal && !message.empty())
3210 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3215 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3216 return [self popErrorWithTitle:title] || !success;
3219 - (void) reloadData { _pooled
3220 @synchronized ([Database class]) {
3221 @synchronized (self) {
3225 [packages_ removeAllObjects];
3251 apr_pool_clear(pool_);
3252 NSRecycleZone(zone_);
3254 int chk(creat("/tmp/cydia.chk", 0644));
3258 NSString *title(UCLocalize("DATABASE"));
3261 if (!cache_.Open(progress_, true)) { pop:
3263 bool warning(!_error->PopMessage(error));
3264 lprintf("cache_.Open():[%s]\n", error.c_str());
3266 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3267 [delegate_ repairWithSelector:@selector(configure)];
3268 else if (error == "The package lists or status file could not be parsed or opened.")
3269 [delegate_ repairWithSelector:@selector(update)];
3270 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3271 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3272 // else if (error == "The list of sources could not be read.")
3274 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3283 unlink("/tmp/cydia.chk");
3285 now_ = [[NSDate date] retain];
3287 policy_ = new pkgDepCache::Policy();
3288 records_ = new pkgRecords(cache_);
3289 resolver_ = new pkgProblemResolver(cache_);
3290 fetcher_ = new pkgAcquire(&status_);
3293 list_ = new pkgSourceList();
3294 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3297 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3298 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3302 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3305 if (cache_->BrokenCount() != 0) {
3306 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3309 if (cache_->BrokenCount() != 0) {
3310 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3314 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3320 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3321 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3322 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3323 // XXX: this could be more intelligent
3324 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3325 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3327 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3334 /*std::vector<Package *> packages;
3335 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3336 [packages_ release];
3341 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3342 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3343 //packages.push_back(package);
3344 [packages_ addObject:package];
3348 /*if (packages.empty())
3349 packages_ = [[NSArray alloc] init];
3351 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3354 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3355 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3356 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3364 /*if (!packages.empty())
3365 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3366 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3368 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3370 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3372 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3378 - (void) configure {
3379 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3380 system([dpkg UTF8String]);
3384 // XXX: I don't remember this condition
3389 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3391 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3393 if ([self popErrorWithTitle:title])
3397 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3400 public pkgArchiveCleaner
3403 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3408 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3415 fetcher_->Shutdown();
3417 pkgRecords records(cache_);
3419 lock_ = new FileFd();
3420 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3422 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3424 if ([self popErrorWithTitle:title])
3428 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3431 manager_ = (_system->CreatePM(cache_));
3432 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3439 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3441 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3443 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3445 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3446 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3449 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3454 bool failed = false;
3455 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3456 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3458 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3461 std::string uri = (*item)->DescURI();
3462 std::string error = (*item)->ErrorText;
3464 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3467 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3468 withObject:[NSArray arrayWithObjects:
3469 [NSString stringWithUTF8String:error.c_str()],
3481 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3483 if (_error->PendingError()) {
3488 if (result == pkgPackageManager::Failed) {
3493 if (result != pkgPackageManager::Completed) {
3498 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3500 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3502 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3503 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3506 if (![before isEqualToArray:after])
3511 NSString *title(UCLocalize("UPGRADE"));
3512 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3518 [self updateWithStatus:status_];
3521 - (void) setVisible {
3522 for (Package *package in packages_)
3523 [package setVisible];
3526 - (void) updateWithStatus:(Status &)status {
3527 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3528 NSString *title(UCLocalize("REFRESHING_DATA"));
3531 if (!list.ReadMainList())
3532 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3535 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3536 if ([self popErrorWithTitle:title])
3539 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3540 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */;
3542 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3546 - (void) setDelegate:(id)delegate {
3547 delegate_ = delegate;
3548 status_.setDelegate(delegate);
3549 progress_.setDelegate(delegate);
3552 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3553 SourceMap::const_iterator i(sources_.find(file->ID));
3554 return i == sources_.end() ? nil : i->second;
3560 /* Confirmation View {{{ */
3561 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3562 if (!iterator.end())
3563 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3564 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3566 pkgCache::PkgIterator package(dep.TargetPkg());
3569 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3576 /* Web Scripting {{{ */
3577 @interface CydiaObject : NSObject {
3581 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3584 @implementation CydiaObject
3587 [indirect_ release];
3591 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3592 if ((self = [super init]) != nil) {
3593 indirect_ = [indirect retain];
3597 + (NSArray *) _attributeKeys {
3598 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3601 - (NSArray *) attributeKeys {
3602 return [[self class] _attributeKeys];
3605 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3606 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3609 - (NSString *) device {
3610 return [[UIDevice currentDevice] uniqueIdentifier];
3613 #if 0 // XXX: implement!
3614 - (NSString *) mac {
3615 if (![indirect_ promptForSensitive:@"Mac Address"])
3619 - (NSString *) serial {
3620 if (![indirect_ promptForSensitive:@"Serial #"])
3624 - (NSString *) firewire {
3625 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3629 - (NSString *) imei {
3630 if (![indirect_ promptForSensitive:@"IMEI"])
3635 + (NSString *) webScriptNameForSelector:(SEL)selector {
3636 if (selector == @selector(close))
3638 else if (selector == @selector(getInstalledPackages))
3639 return @"getInstalledPackages";
3640 else if (selector == @selector(getPackageById:))
3641 return @"getPackageById";
3642 else if (selector == @selector(setAutoPopup:))
3643 return @"setAutoPopup";
3644 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3645 return @"setButtonImage";
3646 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3647 return @"setButtonTitle";
3648 else if (selector == @selector(setFinishHook:))
3649 return @"setFinishHook";
3650 else if (selector == @selector(setPopupHook:))
3651 return @"setPopupHook";
3652 else if (selector == @selector(setSpecial:))
3653 return @"setSpecial";
3654 else if (selector == @selector(setViewportWidth:))
3655 return @"setViewportWidth";
3656 else if (selector == @selector(supports:))
3658 else if (selector == @selector(stringWithFormat:arguments:))
3660 else if (selector == @selector(localizedStringForKey:value:table:))
3662 else if (selector == @selector(du:))
3664 else if (selector == @selector(statfs:))
3670 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3671 return [self webScriptNameForSelector:selector] == nil;
3674 - (BOOL) supports:(NSString *)feature {
3675 return [feature isEqualToString:@"window.open"];
3678 - (NSArray *) getInstalledPackages {
3679 NSArray *packages([[Database sharedInstance] packages]);
3680 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3681 for (Package *package in installed)
3682 if ([package installed] != nil)
3683 [installed addObject:package];
3687 - (Package *) getPackageById:(NSString *)id {
3688 Package *package([[Database sharedInstance] packageWithName:id]);
3693 - (NSArray *) statfs:(NSString *)path {
3696 if (path == nil || statfs([path UTF8String], &stat) == -1)
3699 return [NSArray arrayWithObjects:
3700 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3701 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3702 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3706 - (NSNumber *) du:(NSString *)path {
3707 NSNumber *value(nil);
3710 _assert(pipe(fds) != -1);
3712 pid_t pid(ExecFork());
3714 _assert(dup2(fds[1], 1) != -1);
3715 _assert(close(fds[0]) != -1);
3716 _assert(close(fds[1]) != -1);
3717 /* XXX: this should probably not use du */
3718 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3723 _assert(close(fds[1]) != -1);
3725 if (FILE *du = fdopen(fds[0], "r")) {
3727 while (fgets(line, sizeof(line), du) != NULL) {
3728 size_t length(strlen(line));
3729 while (length != 0 && line[length - 1] == '\n')
3730 line[--length] = '\0';
3731 if (char *tab = strchr(line, '\t')) {
3733 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3738 } else _assert(close(fds[0]));
3742 if (waitpid(pid, &status, 0) == -1)
3745 else _assert(false);
3754 - (void) setAutoPopup:(BOOL)popup {
3755 [indirect_ setAutoPopup:popup];
3758 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3759 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3762 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3763 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3766 - (void) setSpecial:(id)function {
3767 [indirect_ setSpecial:function];
3770 - (void) setFinishHook:(id)function {
3771 [indirect_ setFinishHook:function];
3774 - (void) setPopupHook:(id)function {
3775 [indirect_ setPopupHook:function];
3778 - (void) setViewportWidth:(float)width {
3779 [indirect_ setViewportWidth:width];
3782 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3783 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3784 unsigned count([arguments count]);
3786 for (unsigned i(0); i != count; ++i)
3787 values[i] = [arguments objectAtIndex:i];
3788 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
3791 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3792 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3794 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3796 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3802 @interface CydiaBrowserView : BrowserView {
3803 CydiaObject *cydia_;
3808 @implementation CydiaBrowserView
3815 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3816 [super webView:sender didClearWindowObject:window forFrame:frame];
3817 [window setValue:cydia_ forKey:@"cydia"];
3820 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3821 if (System_ != NULL)
3822 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3823 if (Machine_ != NULL)
3824 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3825 if (UniqueID_ != nil)
3826 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
3828 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3831 - (NSURLRequest *) webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)source {
3832 NSMutableURLRequest *copy = [request mutableCopy];
3833 [self _setMoreHeaders:copy];
3837 - (id) initWithBook:(RVBook *)book forWidth:(float)width {
3838 if ((self = [super initWithBook:book forWidth:width ofClass:[CydiaBrowserView class]]) != nil) {
3839 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3841 WebView *webview([webview_ webView]);
3843 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3845 NSString *application = package == nil ? @"Cydia" : [NSString
3846 stringWithFormat:@"Cydia/%@",
3851 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3853 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3854 if (Product_ != nil)
3855 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3857 [webview setApplicationNameForUserAgent:application];
3863 @protocol ConfirmationViewDelegate
3869 @interface ConfirmationView : CydiaBrowserView {
3870 _transient Database *database_;
3871 UIActionSheet *essential_;
3878 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3882 @implementation ConfirmationView
3889 if (essential_ != nil)
3890 [essential_ release];
3896 [book_ popFromSuperviewAnimated:YES];
3899 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3900 NSString *context([sheet context]);
3902 if ([context isEqualToString:@"remove"]) {
3910 [delegate_ confirm];
3916 } else if ([context isEqualToString:@"unable"]) {
3920 [super alertSheet:sheet buttonClicked:button];
3923 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3924 [super webView:sender didClearWindowObject:window forFrame:frame];
3925 [window setValue:changes_ forKey:@"changes"];
3926 [window setValue:issues_ forKey:@"issues"];
3927 [window setValue:sizes_ forKey:@"sizes"];
3930 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3931 if ((self = [super initWithBook:book]) != nil) {
3932 database_ = database;
3934 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3935 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3936 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3937 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3938 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3942 pkgDepCache::Policy *policy([database_ policy]);
3944 pkgCacheFile &cache([database_ cache]);
3945 NSArray *packages = [database_ packages];
3946 for (Package *package in packages) {
3947 pkgCache::PkgIterator iterator = [package iterator];
3948 pkgDepCache::StateCache &state(cache[iterator]);
3950 NSString *name([package name]);
3952 if (state.NewInstall())
3953 [installing addObject:name];
3954 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3955 [reinstalling addObject:name];
3956 else if (state.Upgrade())
3957 [upgrading addObject:name];
3958 else if (state.Downgrade())
3959 [downgrading addObject:name];
3960 else if (state.Delete()) {
3961 if ([package essential])
3963 [removing addObject:name];
3966 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3967 substrate_ |= DepSubstrate(iterator.CurrentVer());
3972 else if (Advanced_) {
3973 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
3975 essential_ = [[UIActionSheet alloc]
3976 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
3977 buttons:[NSArray arrayWithObjects:
3978 [NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")],
3979 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
3981 defaultButtonIndex:0
3986 [essential_ setDestructiveButtonIndex:1];
3987 [essential_ setBodyText:UCLocalize("REMOVING_ESSENTIALS_EX")];
3989 essential_ = [[UIActionSheet alloc]
3990 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
3991 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
3992 defaultButtonIndex:0
3997 [essential_ setBodyText:UCLocalize("UNABLE_TO_COMPLY_EX")];
4000 changes_ = [[NSArray alloc] initWithObjects:
4008 issues_ = [database_ issues];
4010 issues_ = [issues_ retain];
4012 sizes_ = [[NSArray alloc] initWithObjects:
4013 SizeString([database_ fetcher].FetchNeeded()),
4014 SizeString([database_ fetcher].PartialPresent()),
4015 SizeString([database_ cache]->UsrSize()),
4018 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4022 - (NSString *) backButtonTitle {
4023 return UCLocalize("CONFIRM");
4026 - (NSString *) leftButtonTitle {
4027 return [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")];
4030 - (id) rightButtonTitle {
4031 return issues_ != nil ? nil : [super rightButtonTitle];
4034 - (id) _rightButtonTitle {
4035 #if AlwaysReload || IgnoreInstall
4036 return [super _rightButtonTitle];
4038 return UCLocalize("CONFIRM");
4042 - (void) _leftButtonClicked {
4047 - (void) _rightButtonClicked {
4049 return [super _rightButtonClicked];
4051 if (essential_ != nil)
4052 [essential_ popupAlertAnimated:YES];
4056 [delegate_ confirm];
4064 /* Progress Data {{{ */
4065 @interface ProgressData : NSObject {
4071 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4078 @implementation ProgressData
4080 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4081 if ((self = [super init]) != nil) {
4082 selector_ = selector;
4102 /* Progress View {{{ */
4103 @interface ProgressView : UIView <
4104 ConfigurationDelegate,
4107 _transient Database *database_;
4109 UIView *background_;
4110 UITransitionView *transition_;
4112 UINavigationBar *navbar_;
4113 UIProgressBar *progress_;
4114 UITextView *output_;
4115 UITextLabel *status_;
4116 UIPushButton *close_;
4119 SHA1SumValue springlist_;
4120 SHA1SumValue notifyconf_;
4124 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
4125 - (void) setContentView:(UIView *)view;
4128 - (void) _retachThread;
4129 - (void) _detachNewThreadData:(ProgressData *)data;
4130 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4136 @protocol ProgressViewDelegate
4137 - (void) progressViewIsComplete:(ProgressView *)sender;
4140 @implementation ProgressView
4143 [transition_ setDelegate:nil];
4144 [navbar_ setDelegate:nil];
4147 if (background_ != nil)
4148 [background_ release];
4149 [transition_ release];
4152 [progress_ release];
4161 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
4162 if ((self = [super initWithFrame:frame]) != nil) {
4163 database_ = database;
4164 delegate_ = delegate;
4166 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
4167 [transition_ setDelegate:self];
4169 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
4171 background_ = [[UIView alloc] initWithFrame:[self bounds]];
4172 [background_ setBackgroundColor:[UIColor blackColor]];
4173 [self addSubview:background_];
4175 [self addSubview:transition_];
4177 CGSize navsize = [UINavigationBar defaultSize];
4178 CGRect navrect = {{0, 0}, navsize};
4180 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
4181 [overlay_ addSubview:navbar_];
4183 [navbar_ setBarStyle:1];
4184 [navbar_ setDelegate:self];
4186 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
4187 [navbar_ pushNavigationItem:navitem];
4189 CGRect bounds = [overlay_ bounds];
4190 CGSize prgsize = [UIProgressBar defaultSize];
4193 (bounds.size.width - prgsize.width) / 2,
4194 bounds.size.height - prgsize.height - 20
4197 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
4198 [progress_ setStyle:0];
4200 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
4202 bounds.size.height - prgsize.height - 50,
4203 bounds.size.width - 20,
4207 [status_ setColor:[UIColor whiteColor]];
4208 [status_ setBackgroundColor:[UIColor clearColor]];
4210 [status_ setCentersHorizontally:YES];
4211 //[status_ setFont:font];
4213 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
4215 navrect.size.height + 20,
4216 bounds.size.width - 20,
4217 bounds.size.height - navsize.height - 62 - navrect.size.height
4220 //[output_ setTextFont:@"Courier New"];
4221 [output_ setFont:[[output_ font] fontWithSize:12]];
4223 [output_ setTextColor:[UIColor whiteColor]];
4224 [output_ setBackgroundColor:[UIColor clearColor]];
4226 [output_ setMarginTop:0];
4227 [output_ setAllowsRubberBanding:YES];
4228 [output_ setEditable:NO];
4230 [overlay_ addSubview:output_];
4232 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
4234 bounds.size.height - prgsize.height - 50,
4235 bounds.size.width - 20,
4239 [close_ setAutosizesToFit:NO];
4240 [close_ setDrawsShadow:YES];
4241 [close_ setStretchBackground:YES];
4242 [close_ setEnabled:YES];
4244 UIFont *bold = [UIFont boldSystemFontOfSize:22];
4245 [close_ setTitleFont:bold];
4247 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4248 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4249 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4253 - (void) setContentView:(UIView *)view {
4254 view_ = [view retain];
4257 - (void) resetView {
4258 [transition_ transition:6 toView:view_];
4261 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4262 NSString *context([sheet context]);
4264 if ([context isEqualToString:@"conffile"]) {
4265 FILE *input = [database_ input];
4269 fprintf(input, "N\n");
4273 fprintf(input, "Y\n");
4283 - (void) closeButtonPushed {
4292 [delegate_ terminateWithSuccess];
4293 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4294 [delegate_ suspendWithAnimation:YES];
4296 [delegate_ suspend];*/
4300 system("launchctl stop com.apple.SpringBoard");
4304 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4313 - (void) _retachThread {
4314 UINavigationItem *item([navbar_ topItem]);
4315 [item setTitle:UCLocalize("COMPLETE")];
4317 [overlay_ addSubview:close_];
4318 [progress_ removeFromSuperview];
4319 [status_ removeFromSuperview];
4321 [database_ popErrorWithTitle:title_];
4322 [delegate_ progressViewIsComplete:self];
4326 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4329 MMap mmap(file, MMap::ReadOnly);
4331 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4332 if (!(notifyconf_ == sha1.Result()))
4339 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4342 MMap mmap(file, MMap::ReadOnly);
4344 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4345 if (!(springlist_ == sha1.Result()))
4351 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break;
4352 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4353 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4354 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4355 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4358 #define ListCache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4359 #define IconCache_ "/User/Library/Caches/com.apple.springboard-imagecache-icons.plist"
4363 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ListCache_]) {
4364 [cache autorelease];
4366 NSFileManager *manager([NSFileManager defaultManager]);
4367 NSError *error(nil);
4369 id system([cache objectForKey:@"System"]);
4374 if (stat(ListCache_, &info) == -1)
4377 [system removeAllObjects];
4379 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4380 for (NSString *app in apps)
4381 if ([app hasSuffix:@".app"]) {
4382 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4383 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4384 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4386 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4387 [info setObject:path forKey:@"Path"];
4388 [info setObject:@"System" forKey:@"ApplicationType"];
4389 [system addInfoDictionary:info];
4395 [cache writeToFile:@ListCache_ atomically:YES];
4397 if (chown(ListCache_, info.st_uid, info.st_gid) == -1)
4399 if (chmod(ListCache_, info.st_mode) == -1)
4403 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4406 notify_post("com.apple.mobile.application_installed");
4408 [delegate_ setStatusBarShowsProgress:NO];
4411 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4412 [[data target] performSelector:[data selector] withObject:[data object]];
4415 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4418 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4424 title_ = [title retain];
4426 UINavigationItem *item([navbar_ topItem]);
4427 [item setTitle:title_];
4429 [status_ setText:nil];
4430 [output_ setText:@""];
4431 [progress_ setProgress:0];
4433 [close_ removeFromSuperview];
4434 [overlay_ addSubview:progress_];
4435 [overlay_ addSubview:status_];
4437 [delegate_ setStatusBarShowsProgress:YES];
4442 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4445 MMap mmap(file, MMap::ReadOnly);
4447 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4448 notifyconf_ = sha1.Result();
4454 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4457 MMap mmap(file, MMap::ReadOnly);
4459 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4460 springlist_ = sha1.Result();
4464 [transition_ transition:6 toView:overlay_];
4467 detachNewThreadSelector:@selector(_detachNewThreadData:)
4469 withObject:[[ProgressData alloc]
4470 initWithSelector:selector
4477 - (void) repairWithSelector:(SEL)selector {
4479 detachNewThreadSelector:selector
4482 title:UCLocalize("REPAIRING")
4486 - (void) setConfigurationData:(NSString *)data {
4488 performSelectorOnMainThread:@selector(_setConfigurationData:)
4494 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4495 CYActionSheet *sheet([[[CYActionSheet alloc]
4497 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4498 defaultButtonIndex:0
4501 [sheet setBodyText:error];
4502 [sheet yieldToPopupAlertAnimated:YES];
4506 - (void) setProgressTitle:(NSString *)title {
4508 performSelectorOnMainThread:@selector(_setProgressTitle:)
4514 - (void) setProgressPercent:(float)percent {
4516 performSelectorOnMainThread:@selector(_setProgressPercent:)
4517 withObject:[NSNumber numberWithFloat:percent]
4522 - (void) startProgress {
4525 - (void) addProgressOutput:(NSString *)output {
4527 performSelectorOnMainThread:@selector(_addProgressOutput:)
4533 - (bool) isCancelling:(size_t)received {
4537 - (void) _setConfigurationData:(NSString *)data {
4538 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4540 if (!conffile_r(data)) {
4541 lprintf("E:invalid conffile\n");
4545 NSString *ofile = conffile_r[1];
4546 //NSString *nfile = conffile_r[2];
4548 UIActionSheet *sheet = [[[UIActionSheet alloc]
4549 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4550 buttons:[NSArray arrayWithObjects:
4551 UCLocalize("KEEP_OLD_COPY"),
4552 UCLocalize("ACCEPT_NEW_COPY"),
4553 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4555 defaultButtonIndex:0
4560 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4561 [sheet popupAlertAnimated:YES];
4564 - (void) _setProgressTitle:(NSString *)title {
4565 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4566 for (size_t i(0), e([words count]); i != e; ++i) {
4567 NSString *word([words objectAtIndex:i]);
4568 if (Package *package = [database_ packageWithName:word])
4569 [words replaceObjectAtIndex:i withObject:[package name]];
4572 [status_ setText:[words componentsJoinedByString:@" "]];
4575 - (void) _setProgressPercent:(NSNumber *)percent {
4576 [progress_ setProgress:[percent floatValue]];
4579 - (void) _addProgressOutput:(NSString *)output {
4580 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4581 CGSize size = [output_ contentSize];
4582 CGRect rect = {{0, size.height}, {size.width, 0}};
4583 [output_ scrollRectToVisible:rect animated:YES];
4586 - (BOOL) isRunning {
4593 /* Package Cell {{{ */
4594 @interface ContentView : UIView {
4595 _transient id delegate_;
4600 @interface PackageCell : UITableViewCell {
4603 NSString *description_;
4609 ContentView *content_;
4615 - (PackageCell *) init;
4616 - (void) setPackage:(Package *)package;
4618 + (int) heightForPackage:(Package *)package;
4619 - (void) drawContentRect:(CGRect)rect;
4623 @implementation ContentView
4625 - (id) initWithFrame:(CGRect)frame {
4626 if ((self = [super initWithFrame:frame]) != nil) {
4630 - (void) setDelegate:(id)delegate {
4631 delegate_ = delegate;
4634 - (void) drawRect:(CGRect)rect {
4635 [super drawRect:rect];
4636 [delegate_ drawContentRect:rect];
4641 @implementation PackageCell
4643 - (void) clearPackage {
4654 if (description_ != nil) {
4655 [description_ release];
4659 if (source_ != nil) {
4664 if (badge_ != nil) {
4669 if (placard_ != nil) {
4679 [self clearPackage];
4686 return faded_ ? [self selectionPercent] : fade_;
4689 - (PackageCell *) init {
4690 CGRect frame(CGRectMake(0, 0, 320, 74));
4691 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4692 UIView *content([self contentView]);
4693 CGRect bounds([content bounds]);
4694 content_ = [[ContentView alloc] initWithFrame:bounds];
4695 [content_ setDelegate:self];
4696 [content_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
4697 [content_ setOpaque:YES];
4698 [content addSubview:content_];
4699 if ([self respondsToSelector:@selector(selectionPercent)])
4704 - (void) _setBackgroundColor {
4706 if (NSString *mode = [package_ mode]) {
4707 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4708 color = remove ? RemovingColor_ : InstallingColor_;
4710 color = [UIColor whiteColor];
4712 [content_ setBackgroundColor:color];
4713 [self setNeedsDisplay];
4716 - (void) setPackage:(Package *)package {
4717 [self clearPackage];
4720 Source *source = [package source];
4722 icon_ = [[package icon] retain];
4723 name_ = [[package name] retain];
4724 description_ = [[package shortDescription] retain];
4725 commercial_ = [package isCommercial];
4727 package_ = [package retain];
4729 NSString *label = nil;
4730 bool trusted = false;
4732 if (source != nil) {
4733 label = [source label];
4734 trusted = [source trusted];
4735 } else if ([[package id] isEqualToString:@"firmware"])
4736 label = UCLocalize("APPLE");
4738 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4740 NSString *from(label);
4742 NSString *section = [package simpleSection];
4743 if (section != nil && ![section isEqualToString:label]) {
4744 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4745 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4748 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4749 source_ = [from retain];
4751 if (NSString *purpose = [package primaryPurpose])
4752 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4753 badge_ = [badge_ retain];
4755 if ([package installed] != nil)
4756 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4757 placard_ = [placard_ retain];
4759 [self _setBackgroundColor];
4760 [content_ setNeedsDisplay];
4763 - (void) drawContentRect:(CGRect)rect {
4764 bool selected([self isSelected]);
4767 CGContextRef context(UIGraphicsGetCurrentContext());
4768 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4769 CGContextFillRect(context, rect);
4774 rect.size = [icon_ size];
4776 rect.size.width /= 2;
4777 rect.size.height /= 2;
4779 rect.origin.x = 25 - rect.size.width / 2;
4780 rect.origin.y = 25 - rect.size.height / 2;
4782 [icon_ drawInRect:rect];
4785 if (badge_ != nil) {
4786 CGSize size = [badge_ size];
4788 [badge_ drawAtPoint:CGPointMake(
4789 36 - size.width / 2,
4790 36 - size.height / 2
4798 UISetColor(commercial_ ? Purple_ : Black_);
4799 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(placard_ == nil ? 240 : 214) withFont:Font18Bold_ ellipsis:2];
4800 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4803 UISetColor(commercial_ ? Purplish_ : Gray_);
4804 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:274 withFont:Font14_ ellipsis:2];
4806 if (placard_ != nil)
4807 [placard_ drawAtPoint:CGPointMake(268, 9)];
4810 - (void) setSelected:(BOOL)selected animated:(BOOL)fade {
4811 //[self _setBackgroundColor];
4812 [super setSelected:selected animated:fade];
4813 [content_ setNeedsDisplay];
4816 + (int) heightForPackage:(Package *)package {
4822 /* Section Cell {{{ */
4823 @interface SectionCell : UISimpleTableCell {
4828 _UISwitchSlider *switch_;
4833 - (void) setSection:(Section *)section editing:(BOOL)editing;
4837 @implementation SectionCell
4839 - (void) clearSection {
4840 if (section_ != nil) {
4850 if (count_ != nil) {
4857 [self clearSection];
4864 if ((self = [super init]) != nil) {
4865 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4867 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4868 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventTouchUpInside];
4872 - (void) onSwitch:(id)sender {
4873 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4874 if (metadata == nil) {
4875 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4876 [Sections_ setObject:metadata forKey:section_];
4880 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4883 - (void) setSection:(Section *)section editing:(BOOL)editing {
4884 if (editing != editing_) {
4886 [switch_ removeFromSuperview];
4888 [self addSubview:switch_];
4892 [self clearSection];
4894 if (section == nil) {
4895 name_ = [UCLocalize("ALL_PACKAGES") retain];
4898 section_ = [section localized];
4899 if (section_ != nil)
4900 section_ = [section_ retain];
4901 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4902 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4905 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4909 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4910 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4917 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4919 CGSize size = [count_ sizeWithFont:Font14_];
4923 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4925 [super drawContentInRect:rect selected:selected];
4931 /* File Table {{{ */
4932 @interface FileTable : RVPage {
4933 _transient Database *database_;
4936 NSMutableArray *files_;
4940 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4941 - (void) setPackage:(Package *)package;
4945 @implementation FileTable
4948 if (package_ != nil)
4957 - (int) numberOfRowsInTable:(UITable *)table {
4958 return files_ == nil ? 0 : [files_ count];
4961 - (float) table:(UITable *)table heightForRow:(int)row {
4965 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4966 if (reusing == nil) {
4967 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4968 UIFont *font = [UIFont systemFontOfSize:16];
4969 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4971 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4975 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4979 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4980 if ((self = [super initWithBook:book]) != nil) {
4981 database_ = database;
4983 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4985 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4986 [self addSubview:list_];
4988 UITableColumn *column = [[[UITableColumn alloc]
4989 initWithTitle:UCLocalize("NAME")
4991 width:[self frame].size.width
4994 [list_ setDataSource:self];
4995 [list_ setSeparatorStyle:1];
4996 [list_ addTableColumn:column];
4997 [list_ setDelegate:self];
4998 [list_ setReusesTableCells:YES];
5002 - (void) setPackage:(Package *)package {
5003 if (package_ != nil) {
5004 [package_ autorelease];
5013 [files_ removeAllObjects];
5015 if (package != nil) {
5016 package_ = [package retain];
5017 name_ = [[package id] retain];
5019 if (NSArray *files = [package files])
5020 [files_ addObjectsFromArray:files];
5022 if ([files_ count] != 0) {
5023 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5024 [files_ removeObjectAtIndex:0];
5025 [files_ sortUsingSelector:@selector(compareByPath:)];
5027 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5028 [stack addObject:@"/"];
5030 for (int i(0), e([files_ count]); i != e; ++i) {
5031 NSString *file = [files_ objectAtIndex:i];
5032 while (![file hasPrefix:[stack lastObject]])
5033 [stack removeLastObject];
5034 NSString *directory = [stack lastObject];
5035 [stack addObject:[file stringByAppendingString:@"/"]];
5036 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5037 ([stack count] - 2) * 3, "",
5038 [file substringFromIndex:[directory length]]
5047 - (void) resetViewAnimated:(BOOL)animated {
5048 [list_ resetViewAnimated:animated];
5051 - (void) reloadData {
5052 [self setPackage:[database_ packageWithName:name_]];
5053 [self reloadButtons];
5056 - (NSString *) title {
5057 return UCLocalize("INSTALLED_FILES");
5060 - (NSString *) backButtonTitle {
5061 return UCLocalize("FILES");
5066 /* Package View {{{ */
5067 @interface PackageView : CydiaBrowserView {
5068 _transient Database *database_;
5072 NSMutableArray *buttons_;
5075 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5076 - (void) setPackage:(Package *)package;
5080 @implementation PackageView
5083 if (package_ != nil)
5092 if ([self retainCount] == 1)
5093 [delegate_ setPackageView:self];
5097 /* XXX: this is not safe at all... localization of /fail/ */
5098 - (void) _clickButtonWithName:(NSString *)name {
5099 if ([name isEqualToString:UCLocalize("CLEAR")])
5100 [delegate_ clearPackage:package_];
5101 else if ([name isEqualToString:UCLocalize("INSTALL")])
5102 [delegate_ installPackage:package_];
5103 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5104 [delegate_ installPackage:package_];
5105 else if ([name isEqualToString:UCLocalize("REMOVE")])
5106 [delegate_ removePackage:package_];
5107 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5108 [delegate_ installPackage:package_];
5109 else _assert(false);
5112 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5113 NSString *context([sheet context]);
5115 if ([context isEqualToString:@"modify"]) {
5116 int count = [buttons_ count];
5117 _assert(count != 0);
5118 _assert(button <= count + 1);
5120 if (count != button - 1)
5121 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
5125 [super alertSheet:sheet buttonClicked:button];
5128 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
5129 return [super webView:sender didFinishLoadForFrame:frame];
5132 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5133 [super webView:sender didClearWindowObject:window forFrame:frame];
5134 [window setValue:package_ forKey:@"package"];
5137 - (bool) _allowJavaScriptPanel {
5142 - (void) __rightButtonClicked {
5143 int count([buttons_ count]);
5148 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5150 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
5151 [buttons addObjectsFromArray:buttons_];
5152 [buttons addObject:UCLocalize("CANCEL")];
5154 [delegate_ slideUp:[[[UIActionSheet alloc]
5157 defaultButtonIndex:([buttons count] - 1)
5164 - (void) _rightButtonClicked {
5166 [super _rightButtonClicked];
5168 [self __rightButtonClicked];
5172 - (id) _rightButtonTitle {
5173 int count = [buttons_ count];
5174 return count == 0 ? nil : count != 1 ? UCLocalize("MODIFY") : [buttons_ objectAtIndex:0];
5177 - (NSString *) backButtonTitle {
5181 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5182 if ((self = [super initWithBook:book]) != nil) {
5183 database_ = database;
5184 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5185 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5189 - (void) setPackage:(Package *)package {
5190 if (package_ != nil) {
5191 [package_ autorelease];
5200 [buttons_ removeAllObjects];
5202 if (package != nil) {
5205 package_ = [package retain];
5206 name_ = [[package id] retain];
5207 commercial_ = [package isCommercial];
5209 if ([package_ mode] != nil)
5210 [buttons_ addObject:UCLocalize("CLEAR")];
5211 if ([package_ source] == nil);
5212 else if ([package_ upgradableAndEssential:NO])
5213 [buttons_ addObject:UCLocalize("UPGRADE")];
5214 else if ([package_ uninstalled])
5215 [buttons_ addObject:UCLocalize("INSTALL")];
5217 [buttons_ addObject:UCLocalize("REINSTALL")];
5218 if (![package_ uninstalled])
5219 [buttons_ addObject:UCLocalize("REMOVE")];
5221 if (special_ != NULL) {
5222 CGRect frame([webview_ frame]);
5223 frame.size.width = 320;
5224 frame.size.height = 0;
5225 [webview_ setFrame:frame];
5227 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5230 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5232 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5234 [self setFinishHook:nil];
5235 [self setPopupHook:nil];
5238 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5239 [super callFunction:special_];
5243 [self reloadButtons];
5246 - (bool) isLoading {
5247 return commercial_ ? [super isLoading] : false;
5250 - (void) reloadData {
5251 [self setPackage:[database_ packageWithName:name_]];
5256 /* Package Table {{{ */
5257 @interface PackageTable : RVPage {
5258 _transient Database *database_;
5260 NSMutableArray *packages_;
5261 NSMutableArray *sections_;
5263 NSMutableArray *index_;
5264 NSMutableDictionary *indices_;
5267 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5269 - (void) setDelegate:(id)delegate;
5271 - (void) reloadData;
5272 - (void) resetCursor;
5274 - (UITableView *) list;
5276 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5280 @implementation PackageTable
5283 [list_ setDataSource:nil];
5286 [packages_ release];
5287 [sections_ release];
5294 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5295 NSInteger count([sections_ count]);
5296 return count == 0 ? 1 : count;
5299 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5300 if ([sections_ count] == 0)
5302 return [[sections_ objectAtIndex:section] name];
5305 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5306 if ([sections_ count] == 0)
5308 return [[sections_ objectAtIndex:section] count];
5311 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5312 Section *section([sections_ objectAtIndex:[path section]]);
5313 NSInteger row([path row]);
5314 Package *package([packages_ objectAtIndex:([section row] + row)]);
5318 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5319 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
5321 cell = [[[PackageCell alloc] init] autorelease];
5322 [cell setPackage:[self packageAtIndexPath:path]];
5326 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5328 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5331 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5332 Package *package([self packageAtIndexPath:path]);
5333 package = [database_ packageWithName:[package id]];
5334 PackageView *view([delegate_ packageView]);
5335 [view setPackage:package];
5336 [view setDelegate:delegate_];
5337 [book_ pushPage:view];
5341 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5342 return [packages_ count] > 20 ? index_ : nil;
5345 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5349 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5350 if ((self = [super initWithBook:book]) != nil) {
5351 database_ = database;
5352 title_ = [title retain];
5354 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5355 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5357 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5358 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5360 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5361 [list_ setDataSource:self];
5362 [list_ setDelegate:self];
5364 [self addSubview:list_];
5366 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5367 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5371 - (void) setDelegate:(id)delegate {
5372 delegate_ = delegate;
5375 - (bool) hasPackage:(Package *)package {
5379 - (void) reloadData {
5380 NSArray *packages = [database_ packages];
5382 [packages_ removeAllObjects];
5383 [sections_ removeAllObjects];
5385 _profile(PackageTable$reloadData$Filter)
5386 for (Package *package in packages)
5387 if ([self hasPackage:package])
5388 [packages_ addObject:package];
5391 [index_ removeAllObjects];
5392 [indices_ removeAllObjects];
5394 Section *section = nil;
5396 _profile(PackageTable$reloadData$Section)
5397 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5401 _profile(PackageTable$reloadData$Section$Package)
5402 package = [packages_ objectAtIndex:offset];
5403 index = [package index];
5406 if (section == nil || [section index] != index) {
5407 _profile(PackageTable$reloadData$Section$Allocate)
5408 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5411 [index_ addObject:[section name]];
5412 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5414 _profile(PackageTable$reloadData$Section$Add)
5415 [sections_ addObject:section];
5419 [section addToCount];
5423 _profile(PackageTable$reloadData$List)
5428 - (NSString *) title {
5432 - (void) resetViewAnimated:(BOOL)animated {
5433 [list_ resetViewAnimated:animated];
5436 - (void) resetCursor {
5437 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5440 - (UITableView *) list {
5444 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5445 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5450 /* Filtered Package Table {{{ */
5451 @interface FilteredPackageTable : PackageTable {
5457 - (void) setObject:(id)object;
5459 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5463 @implementation FilteredPackageTable
5471 - (void) setObject:(id)object {
5477 object_ = [object retain];
5480 - (bool) hasPackage:(Package *)package {
5481 _profile(FilteredPackageTable$hasPackage)
5482 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5486 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5487 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5489 object_ = object == nil ? nil : [object retain];
5491 /* XXX: this is an unsafe optimization of doomy hell */
5492 Method method(class_getInstanceMethod([Package class], filter));
5493 _assert(method != NULL);
5494 imp_ = method_getImplementation(method);
5495 _assert(imp_ != NULL);
5504 /* Add Source View {{{ */
5505 @interface AddSourceView : RVPage {
5506 _transient Database *database_;
5509 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5513 @implementation AddSourceView
5515 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5516 if ((self = [super initWithBook:book]) != nil) {
5517 database_ = database;
5523 /* Source Cell {{{ */
5524 @interface SourceCell : UITableCell {
5527 NSString *description_;
5533 - (SourceCell *) initWithSource:(Source *)source;
5537 @implementation SourceCell
5542 [description_ release];
5547 - (SourceCell *) initWithSource:(Source *)source {
5548 if ((self = [super init]) != nil) {
5550 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5552 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5553 icon_ = [icon_ retain];
5555 origin_ = [[source name] retain];
5556 label_ = [[source uri] retain];
5557 description_ = [[source description] retain];
5561 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5563 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5570 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5574 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5578 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5580 [super drawContentInRect:rect selected:selected];
5585 /* Source Table {{{ */
5586 @interface SourceTable : RVPage {
5587 _transient Database *database_;
5588 UISectionList *list_;
5589 NSMutableArray *sources_;
5590 UIActionSheet *alert_;
5594 UIProgressHUD *hud_;
5597 //NSURLConnection *installer_;
5598 NSURLConnection *trivial_;
5599 NSURLConnection *trivial_bz2_;
5600 NSURLConnection *trivial_gz_;
5601 //NSURLConnection *automatic_;
5606 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5610 @implementation SourceTable
5612 - (void) _deallocConnection:(NSURLConnection *)connection {
5613 if (connection != nil) {
5614 [connection cancel];
5615 //[connection setDelegate:nil];
5616 [connection release];
5621 [[list_ table] setDelegate:nil];
5622 [list_ setDataSource:nil];
5631 //[self _deallocConnection:installer_];
5632 [self _deallocConnection:trivial_];
5633 [self _deallocConnection:trivial_gz_];
5634 [self _deallocConnection:trivial_bz2_];
5635 //[self _deallocConnection:automatic_];
5642 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5643 return offset_ == 0 ? 1 : 2;
5646 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5647 switch (section + (offset_ == 0 ? 1 : 0)) {
5648 case 0: return UCLocalize("ENTERED_BY_USER");
5649 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5655 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5656 switch (section + (offset_ == 0 ? 1 : 0)) {
5658 case 1: return offset_;
5664 - (int) numberOfRowsInTable:(UITable *)table {
5665 return [sources_ count];
5668 - (float) table:(UITable *)table heightForRow:(int)row {
5669 Source *source = [sources_ objectAtIndex:row];
5670 return [source description] == nil ? 56 : 73;
5673 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5674 Source *source = [sources_ objectAtIndex:row];
5675 // XXX: weird warning, stupid selectors ;P
5676 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5679 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5683 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5687 - (void) tableRowSelected:(NSNotification*)notification {
5688 UITable *table([list_ table]);
5689 int row([table selectedRow]);
5693 Source *source = [sources_ objectAtIndex:row];
5695 PackageTable *packages = [[[FilteredPackageTable alloc]
5698 title:[source label]
5699 filter:@selector(isVisibleInSource:)
5703 [packages setDelegate:delegate_];
5705 [book_ pushPage:packages];
5708 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5709 Source *source = [sources_ objectAtIndex:row];
5710 return [source record] != nil;
5713 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5714 [[list_ table] setDeleteConfirmationRow:row];
5717 - (void) table:(UITable *)table deleteRow:(int)row {
5718 Source *source = [sources_ objectAtIndex:row];
5719 [Sources_ removeObjectForKey:[source key]];
5720 [delegate_ syncData];
5724 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5727 @"./", @"Distribution",
5728 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5730 [delegate_ syncData];
5733 - (NSString *) getWarning {
5734 NSString *href(href_);
5735 NSRange colon([href rangeOfString:@"://"]);
5736 if (colon.location != NSNotFound)
5737 href = [href substringFromIndex:(colon.location + 3)];
5738 href = [href stringByAddingPercentEscapes];
5739 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5740 href = [href stringByCachingURLWithCurrentCDN];
5742 NSURL *url([NSURL URLWithString:href]);
5744 NSStringEncoding encoding;
5745 NSError *error(nil);
5747 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5748 return [warning length] == 0 ? nil : warning;
5752 - (void) _endConnection:(NSURLConnection *)connection {
5753 NSURLConnection **field = NULL;
5754 if (connection == trivial_)
5756 else if (connection == trivial_bz2_)
5757 field = &trivial_bz2_;
5758 else if (connection == trivial_gz_)
5759 field = &trivial_gz_;
5760 _assert(field != NULL);
5761 [connection release];
5766 trivial_bz2_ == nil &&
5772 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5775 UIActionSheet *sheet = [[[UIActionSheet alloc]
5776 initWithTitle:UCLocalize("SOURCE_WARNING")
5777 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_ANYWAY"), UCLocalize("CANCEL"), nil]
5778 defaultButtonIndex:0
5783 [sheet setNumberOfRows:1];
5785 [sheet setBodyText:warning];
5786 [sheet popupAlertAnimated:YES];
5789 } else if (error_ != nil) {
5790 UIActionSheet *sheet = [[[UIActionSheet alloc]
5791 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5792 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5793 defaultButtonIndex:0
5798 [sheet setBodyText:[error_ localizedDescription]];
5799 [sheet popupAlertAnimated:YES];
5801 UIActionSheet *sheet = [[[UIActionSheet alloc]
5802 initWithTitle:UCLocalize("NOT_REPOSITORY")
5803 buttons:[NSArray arrayWithObjects:UCLocalize("OK"), nil]
5804 defaultButtonIndex:0
5809 [sheet setBodyText:UCLocalize("NOT_REPOSITORY_EX")];
5810 [sheet popupAlertAnimated:YES];
5813 [delegate_ setStatusBarShowsProgress:NO];
5814 [delegate_ removeProgressHUD:hud_];
5824 if (error_ != nil) {
5831 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5832 switch ([response statusCode]) {
5838 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5839 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5841 error_ = [error retain];
5842 [self _endConnection:connection];
5845 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5846 [self _endConnection:connection];
5849 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5850 NSMutableURLRequest *request = [NSMutableURLRequest
5851 requestWithURL:[NSURL URLWithString:href]
5852 cachePolicy:NSURLRequestUseProtocolCachePolicy
5853 timeoutInterval:20.0
5856 [request setHTTPMethod:method];
5858 if (Machine_ != NULL)
5859 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5860 if (UniqueID_ != nil)
5861 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5864 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5866 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5869 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5870 NSString *context([sheet context]);
5872 if ([context isEqualToString:@"source"]) {
5875 NSString *href = [[sheet textField] text];
5877 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5879 if (![href hasSuffix:@"/"])
5880 href_ = [href stringByAppendingString:@"/"];
5883 href_ = [href_ retain];
5885 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
5886 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5887 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5888 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5892 hud_ = [[delegate_ addProgressHUD] retain];
5893 [hud_ setText:UCLocalize("VERIFYING_URL")];
5903 } else if ([context isEqualToString:@"trivial"])
5905 else if ([context isEqualToString:@"urlerror"])
5907 else if ([context isEqualToString:@"warning"]) {
5926 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5927 if ((self = [super initWithBook:book]) != nil) {
5928 database_ = database;
5929 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5931 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5932 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5933 [list_ setShouldHideHeaderInShortLists:NO];
5935 [self addSubview:list_];
5936 [list_ setDataSource:self];
5938 UITableColumn *column = [[UITableColumn alloc]
5939 initWithTitle:UCLocalize("NAME")
5941 width:[self frame].size.width
5944 UITable *table = [list_ table];
5945 [table setSeparatorStyle:1];
5946 [table addTableColumn:column];
5947 [table setDelegate:self];
5951 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5952 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5956 - (void) reloadData {
5958 if (!list.ReadMainList())
5961 [sources_ removeAllObjects];
5962 [sources_ addObjectsFromArray:[database_ sources]];
5964 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5967 int count([sources_ count]);
5968 for (offset_ = 0; offset_ != count; ++offset_) {
5969 Source *source = [sources_ objectAtIndex:offset_];
5970 if ([source record] == nil)
5977 - (void) resetViewAnimated:(BOOL)animated {
5978 [list_ resetViewAnimated:animated];
5981 - (void) _leftButtonClicked {
5982 /*[book_ pushPage:[[[AddSourceView alloc]
5987 UIActionSheet *sheet = [[[UIActionSheet alloc]
5988 initWithTitle:UCLocalize("ENTER_APT_URL")
5989 buttons:[NSArray arrayWithObjects:UCLocalize("ADD_SOURCE"), UCLocalize("CANCEL"), nil]
5990 defaultButtonIndex:0
5995 [sheet setNumberOfRows:1];
5997 [sheet addTextFieldWithValue:@"http://" label:@""];
5999 UITextInputTraits *traits = [[sheet textField] textInputTraits];
6000 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6001 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6002 [traits setKeyboardType:UIKeyboardTypeURL];
6003 // XXX: UIReturnKeyDone
6004 [traits setReturnKeyType:UIReturnKeyNext];
6006 [sheet popupAlertAnimated:YES];
6009 - (void) _rightButtonClicked {
6010 UITable *table = [list_ table];
6011 BOOL editing = [table isRowDeletionEnabled];
6012 [table enableRowDeletion:!editing animated:YES];
6013 [book_ reloadButtonsForPage:self];
6016 - (NSString *) title {
6017 return UCLocalize("SOURCES");
6020 - (NSString *) leftButtonTitle {
6021 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("ADD") : nil;
6024 - (id) rightButtonTitle {
6025 return [[list_ table] isRowDeletionEnabled] ? UCLocalize("DONE") : UCLocalize("EDIT");
6028 - (UINavigationButtonStyle) rightButtonStyle {
6029 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6035 /* Installed View {{{ */
6036 @interface InstalledView : RVPage {
6037 _transient Database *database_;
6038 FilteredPackageTable *packages_;
6042 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6046 @implementation InstalledView
6049 [packages_ release];
6053 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6054 if ((self = [super initWithBook:book]) != nil) {
6055 database_ = database;
6057 packages_ = [[FilteredPackageTable alloc]
6061 filter:@selector(isInstalledAndVisible:)
6062 with:[NSNumber numberWithBool:YES]
6065 [self addSubview:packages_];
6067 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6068 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6072 - (void) resetViewAnimated:(BOOL)animated {
6073 [packages_ resetViewAnimated:animated];
6076 - (void) reloadData {
6077 [packages_ reloadData];
6080 - (void) _rightButtonClicked {
6081 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6082 [packages_ reloadData];
6084 [book_ reloadButtonsForPage:self];
6087 - (NSString *) title {
6088 return UCLocalize("INSTALLED");
6091 - (NSString *) backButtonTitle {
6092 return UCLocalize("PACKAGES");
6095 - (id) rightButtonTitle {
6096 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE");
6099 - (UINavigationButtonStyle) rightButtonStyle {
6100 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6103 - (void) setDelegate:(id)delegate {
6104 [super setDelegate:delegate];
6105 [packages_ setDelegate:delegate];
6112 @interface HomeView : CydiaBrowserView {
6117 @implementation HomeView
6119 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6120 NSString *context([sheet context]);
6122 if ([context isEqualToString:@"about"])
6125 [super alertSheet:sheet buttonClicked:button];
6128 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6129 [super _setMoreHeaders:request];
6131 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6134 - (void) _leftButtonClicked {
6135 UIActionSheet *sheet = [[[UIActionSheet alloc]
6136 initWithTitle:UCLocalize("ABOUT_CYDIA")
6137 buttons:[NSArray arrayWithObjects:UCLocalize("CLOSE"), nil]
6138 defaultButtonIndex:0
6144 @"Copyright (C) 2008-2009\n"
6145 "Jay Freeman (saurik)\n"
6146 "saurik@saurik.com\n"
6147 "http://www.saurik.com/\n"
6150 "http://www.theokorigroup.com/\n"
6152 "College of Creative Studies,\n"
6153 "University of California,\n"
6155 "http://www.ccs.ucsb.edu/"
6158 [sheet popupAlertAnimated:YES];
6161 - (NSString *) leftButtonTitle {
6162 return UCLocalize("ABOUT");
6167 /* Manage View {{{ */
6168 @interface ManageView : CydiaBrowserView {
6173 @implementation ManageView
6175 - (NSString *) title {
6176 return UCLocalize("MANAGE");
6179 - (void) _leftButtonClicked {
6180 [delegate_ askForSettings];
6181 [delegate_ updateData];
6184 - (NSString *) leftButtonTitle {
6185 return UCLocalize("SETTINGS");
6189 - (id) _rightButtonTitle {
6190 return Queuing_ ? UCLocalize("QUEUE") : nil;
6193 - (UINavigationButtonStyle) rightButtonStyle {
6194 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6197 - (void) _rightButtonClicked {
6202 - (bool) isLoading {
6209 /* Cydia Book {{{ */
6210 @interface CYBook : RVBook <
6213 _transient Database *database_;
6214 UINavigationBar *overlay_;
6215 UINavigationBar *underlay_;
6216 UIProgressIndicator *indicator_;
6217 UITextLabel *prompt_;
6218 UIProgressBar *progress_;
6219 UINavigationButton *cancel_;
6223 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
6229 @implementation CYBook
6233 [indicator_ release];
6235 [progress_ release];
6240 - (NSString *) getTitleForPage:(RVPage *)page {
6241 return [super getTitleForPage:page];
6249 [UIView beginAnimations:nil context:NULL];
6251 CGRect ovrframe = [overlay_ frame];
6252 ovrframe.origin.y = 0;
6253 [overlay_ setFrame:ovrframe];
6255 CGRect barframe = [navbar_ frame];
6256 barframe.origin.y += ovrframe.size.height;
6257 [navbar_ setFrame:barframe];
6259 CGRect trnframe = [transition_ frame];
6260 trnframe.origin.y += ovrframe.size.height;
6261 trnframe.size.height -= ovrframe.size.height;
6262 [transition_ setFrame:trnframe];
6264 [UIView endAnimations];
6266 [indicator_ startAnimation];
6267 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6268 [progress_ setProgress:0];
6271 [overlay_ addSubview:cancel_];
6274 detachNewThreadSelector:@selector(_update)
6280 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6281 NSString *context([sheet context]);
6283 if ([context isEqualToString:@"refresh"])
6290 [indicator_ stopAnimation];
6292 [UIView beginAnimations:nil context:NULL];
6294 CGRect ovrframe = [overlay_ frame];
6295 ovrframe.origin.y = -ovrframe.size.height;
6296 [overlay_ setFrame:ovrframe];
6298 CGRect barframe = [navbar_ frame];
6299 barframe.origin.y -= ovrframe.size.height;
6300 [navbar_ setFrame:barframe];
6302 CGRect trnframe = [transition_ frame];
6303 trnframe.origin.y -= ovrframe.size.height;
6304 trnframe.size.height += ovrframe.size.height;
6305 [transition_ setFrame:trnframe];
6307 [UIView commitAnimations];
6309 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6312 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6313 if ((self = [super initWithFrame:frame]) != nil) {
6314 database_ = database;
6316 CGRect ovrrect([navbar_ bounds]);
6317 ovrrect.size.height = [UINavigationBar defaultSize].height;
6318 ovrrect.origin.y = -ovrrect.size.height;
6320 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6321 [self addSubview:overlay_];
6323 ovrrect.origin.y = frame.size.height;
6324 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6325 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6326 [self addSubview:underlay_];
6328 [overlay_ setBarStyle:1];
6329 [underlay_ setBarStyle:1];
6331 int barstyle([overlay_ _barStyle:NO]);
6332 bool ugly(barstyle == 0);
6334 UIProgressIndicatorStyle style = ugly ?
6335 UIProgressIndicatorStyleMediumBrown :
6336 UIProgressIndicatorStyleMediumWhite;
6338 CGSize indsize([UIProgressIndicator defaultSizeForStyle:style]);
6339 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6340 CGRect indrect = {{indoffset, indoffset}, indsize};
6342 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6343 [indicator_ setStyle:style];
6344 [overlay_ addSubview:indicator_];
6346 CGSize prmsize = {215, indsize.height + 4};
6349 indoffset * 2 + indsize.width,
6350 unsigned(ovrrect.size.height - prmsize.height) / 2 - 1
6353 UIFont *font([UIFont systemFontOfSize:15]);
6355 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6357 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6358 [prompt_ setBackgroundColor:[UIColor clearColor]];
6359 [prompt_ setFont:font];
6361 [overlay_ addSubview:prompt_];
6363 CGSize prgsize = {75, 100};
6366 ovrrect.size.width - prgsize.width - 10,
6367 (ovrrect.size.height - prgsize.height) / 2
6370 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6371 [progress_ setStyle:0];
6372 [overlay_ addSubview:progress_];
6374 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6375 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6377 CGRect frame = [cancel_ frame];
6378 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6379 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6380 [cancel_ setFrame:frame];
6382 [cancel_ setBarStyle:barstyle];
6386 - (void) _onCancel {
6388 [cancel_ removeFromSuperview];
6391 - (void) _update { _pooled
6393 status.setDelegate(self);
6394 [database_ updateWithStatus:status];
6397 performSelectorOnMainThread:@selector(_update_)
6403 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6404 [prompt_ setText:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6408 UIActionSheet *sheet = [[[UIActionSheet alloc]
6409 initWithTitle:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), UCLocalize("REFRESH")]
6410 buttons:[NSArray arrayWithObjects:
6413 defaultButtonIndex:0
6418 [sheet setBodyText:error];
6419 [sheet popupAlertAnimated:YES];
6421 [self reloadButtons];
6424 - (void) setProgressTitle:(NSString *)title {
6426 performSelectorOnMainThread:@selector(_setProgressTitle:)
6432 - (void) setProgressPercent:(float)percent {
6434 performSelectorOnMainThread:@selector(_setProgressPercent:)
6435 withObject:[NSNumber numberWithFloat:percent]
6440 - (void) startProgress {
6443 - (void) addProgressOutput:(NSString *)output {
6445 performSelectorOnMainThread:@selector(_addProgressOutput:)
6451 - (bool) isCancelling:(size_t)received {
6455 - (void) _setProgressTitle:(NSString *)title {
6456 [prompt_ setText:title];
6459 - (void) _setProgressPercent:(NSNumber *)percent {
6460 [progress_ setProgress:[percent floatValue]];
6463 - (void) _addProgressOutput:(NSString *)output {
6468 /* Cydia:// Protocol {{{ */
6469 @interface CydiaURLProtocol : NSURLProtocol {
6474 @implementation CydiaURLProtocol
6476 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6477 NSURL *url([request URL]);
6480 NSString *scheme([[url scheme] lowercaseString]);
6481 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6486 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6490 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6491 id<NSURLProtocolClient> client([self client]);
6493 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6495 NSData *data(UIImagePNGRepresentation(icon));
6497 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6498 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6499 [client URLProtocol:self didLoadData:data];
6500 [client URLProtocolDidFinishLoading:self];
6504 - (void) startLoading {
6505 id<NSURLProtocolClient> client([self client]);
6506 NSURLRequest *request([self request]);
6508 NSURL *url([request URL]);
6509 NSString *href([url absoluteString]);
6511 NSString *path([href substringFromIndex:8]);
6512 NSRange slash([path rangeOfString:@"/"]);
6515 if (slash.location == NSNotFound) {
6519 command = [path substringToIndex:slash.location];
6520 path = [path substringFromIndex:(slash.location + 1)];
6523 Database *database([Database sharedInstance]);
6525 if ([command isEqualToString:@"package-icon"]) {
6528 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6529 Package *package([database packageWithName:path]);
6532 UIImage *icon([package icon]);
6533 [self _returnPNGWithImage:icon forRequest:request];
6534 } else if ([command isEqualToString:@"source-icon"]) {
6537 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6538 NSString *source(Simplify(path));
6539 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6541 icon = [UIImage applicationImageNamed:@"unknown.png"];
6542 [self _returnPNGWithImage:icon forRequest:request];
6543 } else if ([command isEqualToString:@"uikit-image"]) {
6546 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6547 UIImage *icon(_UIImageWithName(path));
6548 [self _returnPNGWithImage:icon forRequest:request];
6549 } else if ([command isEqualToString:@"section-icon"]) {
6552 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6553 NSString *section(Simplify(path));
6554 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6556 icon = [UIImage applicationImageNamed:@"unknown.png"];
6557 [self _returnPNGWithImage:icon forRequest:request];
6559 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6563 - (void) stopLoading {
6569 /* Sections View {{{ */
6570 @interface SectionsView : RVPage {
6571 _transient Database *database_;
6572 NSMutableArray *sections_;
6573 NSMutableArray *filtered_;
6574 UITransitionView *transition_;
6580 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6581 - (void) reloadData;
6586 @implementation SectionsView
6589 [list_ setDataSource:nil];
6590 [list_ setDelegate:nil];
6592 [sections_ release];
6593 [filtered_ release];
6594 [transition_ release];
6596 [accessory_ release];
6600 - (int) numberOfRowsInTable:(UITable *)table {
6601 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6604 - (float) table:(UITable *)table heightForRow:(int)row {
6608 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6610 reusing = [[[SectionCell alloc] init] autorelease];
6611 [(SectionCell *)reusing setSection:(editing_ ?
6612 [sections_ objectAtIndex:row] :
6613 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6614 ) editing:editing_];
6618 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6622 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6626 - (void) tableRowSelected:(NSNotification *)notification {
6627 int row = [[notification object] selectedRow];
6638 title = UCLocalize("ALL_PACKAGES");
6640 section = [filtered_ objectAtIndex:(row - 1)];
6641 name = [section name];
6644 name = [NSString stringWithString:name];
6645 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6648 title = UCLocalize("NO_SECTION");
6652 PackageTable *table = [[[FilteredPackageTable alloc]
6656 filter:@selector(isVisibleInSection:)
6660 [table setDelegate:delegate_];
6662 [book_ pushPage:table];
6665 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6666 if ((self = [super initWithBook:book]) != nil) {
6667 database_ = database;
6669 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6670 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6672 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6673 [self addSubview:transition_];
6675 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6676 [transition_ transition:0 toView:list_];
6678 UITableColumn *column = [[[UITableColumn alloc]
6679 initWithTitle:UCLocalize("NAME")
6681 width:[self frame].size.width
6684 [list_ setDataSource:self];
6685 [list_ setSeparatorStyle:1];
6686 [list_ addTableColumn:column];
6687 [list_ setDelegate:self];
6688 [list_ setReusesTableCells:YES];
6692 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6693 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6697 - (void) reloadData {
6698 NSArray *packages = [database_ packages];
6700 [sections_ removeAllObjects];
6701 [filtered_ removeAllObjects];
6704 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6705 SectionMap sections;
6706 sections.resize(64);
6708 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6712 for (Package *package in packages) {
6713 NSString *name([package section]);
6714 NSString *key(name == nil ? @"" : name);
6719 _profile(SectionsView$reloadData$Section)
6720 section = §ions[key];
6721 if (*section == nil) {
6722 _profile(SectionsView$reloadData$Section$Allocate)
6723 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6728 [*section addToCount];
6730 _profile(SectionsView$reloadData$Filter)
6731 if (![package valid] || ![package visible])
6735 [*section addToRow];
6739 _profile(SectionsView$reloadData$Section)
6740 section = [sections objectForKey:key];
6741 if (section == nil) {
6742 _profile(SectionsView$reloadData$Section$Allocate)
6743 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6744 [sections setObject:section forKey:key];
6749 [section addToCount];
6751 _profile(SectionsView$reloadData$Filter)
6752 if (![package valid] || ![package visible])
6762 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6763 [sections_ addObject:i->second];
6765 [sections_ addObjectsFromArray:[sections allValues]];
6768 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6770 for (Section *section in sections_) {
6771 size_t count([section row]);
6775 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6776 [section setCount:count];
6777 [filtered_ addObject:section];
6784 - (void) resetView {
6786 [self _rightButtonClicked];
6789 - (void) resetViewAnimated:(BOOL)animated {
6790 [list_ resetViewAnimated:animated];
6793 - (void) _rightButtonClicked {
6794 if ((editing_ = !editing_))
6797 [delegate_ updateData];
6798 [book_ reloadTitleForPage:self];
6799 [book_ reloadButtonsForPage:self];
6802 - (NSString *) title {
6803 return editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS");
6806 - (NSString *) backButtonTitle {
6807 return UCLocalize("SECTIONS");
6810 - (id) rightButtonTitle {
6811 return [sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT");
6814 - (UINavigationButtonStyle) rightButtonStyle {
6815 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6818 - (UIView *) accessoryView {
6824 /* Changes View {{{ */
6825 @interface ChangesView : RVPage {
6826 _transient Database *database_;
6827 NSMutableArray *packages_;
6828 NSMutableArray *sections_;
6833 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6834 - (void) reloadData;
6838 @implementation ChangesView
6841 [list_ setDelegate:nil];
6842 [list_ setDataSource:nil];
6844 [packages_ release];
6845 [sections_ release];
6850 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6851 NSInteger count([sections_ count]);
6852 return count == 0 ? 1 : count;
6855 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6856 if ([sections_ count] == 0)
6858 return [[sections_ objectAtIndex:section] name];
6861 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6862 if ([sections_ count] == 0)
6864 return [[sections_ objectAtIndex:section] count];
6867 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6868 Section *section([sections_ objectAtIndex:[path section]]);
6869 NSInteger row([path row]);
6870 return [packages_ objectAtIndex:([section row] + row)];
6873 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6874 PackageCell *cell([table dequeueReusableCellWithIdentifier:@"Package"]);
6876 cell = [[[PackageCell alloc] init] autorelease];
6877 [cell setPackage:[self packageAtIndexPath:path]];
6881 - (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6883 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6886 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6887 Package *package([self packageAtIndexPath:path]);
6888 PackageView *view([delegate_ packageView]);
6889 [view setDelegate:delegate_];
6890 [view setPackage:package];
6891 [book_ pushPage:view];
6895 - (void) _leftButtonClicked {
6896 [(CYBook *)book_ update];
6897 [self reloadButtons];
6900 - (void) _rightButtonClicked {
6901 [delegate_ distUpgrade];
6904 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6905 if ((self = [super initWithBook:book]) != nil) {
6906 database_ = database;
6908 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6909 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6911 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
6912 [self addSubview:list_];
6914 //XXX:[list_ setShouldHideHeaderInShortLists:NO];
6915 [list_ setDataSource:self];
6916 [list_ setDelegate:self];
6917 //[list_ setSectionListStyle:1];
6921 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6922 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6926 - (void) reloadData {
6927 NSArray *packages = [database_ packages];
6929 [packages_ removeAllObjects];
6930 [sections_ removeAllObjects];
6933 for (Package *package in packages)
6935 [package uninstalled] && [package valid] && [package visible] ||
6936 [package upgradableAndEssential:YES]
6938 [packages_ addObject:package];
6941 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6944 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6945 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6946 Section *section = nil;
6950 bool unseens = false;
6952 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6954 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6955 Package *package = [packages_ objectAtIndex:offset];
6957 BOOL uae = [package upgradableAndEssential:YES];
6963 _profile(ChangesView$reloadData$Remember)
6964 seen = [package seen];
6967 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6972 name = UCLocalize("UNKNOWN");
6974 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6978 _profile(ChangesView$reloadData$Allocate)
6979 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
6980 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6981 [sections_ addObject:section];
6985 [section addToCount];
6986 } else if ([package ignored])
6987 [ignored addToCount];
6990 [upgradable addToCount];
6995 CFRelease(formatter);
6998 Section *last = [sections_ lastObject];
6999 size_t count = [last count];
7000 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7001 [sections_ removeLastObject];
7004 if ([ignored count] != 0)
7005 [sections_ insertObject:ignored atIndex:0];
7007 [sections_ insertObject:upgradable atIndex:0];
7010 [self reloadButtons];
7013 - (void) resetViewAnimated:(BOOL)animated {
7014 [list_ resetViewAnimated:animated];
7017 - (NSString *) leftButtonTitle {
7018 return [(CYBook *)book_ updating] ? nil : UCLocalize("REFRESH");
7021 - (id) rightButtonTitle {
7022 return upgrades_ == 0 ? nil : [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
7025 - (NSString *) title {
7026 return UCLocalize("CHANGES");
7031 /* Search View {{{ */
7032 @protocol SearchViewDelegate
7033 - (void) showKeyboard:(BOOL)show;
7036 @interface SearchView : RVPage {
7038 UISearchField *field_;
7039 FilteredPackageTable *table_;
7044 - (id) initWithBook:(RVBook *)book database:(Database *)database;
7045 - (void) reloadData;
7049 @implementation SearchView
7052 [field_ setDelegate:nil];
7054 [accessory_ release];
7061 - (void) _showKeyboard:(BOOL)show {
7062 CGSize keysize = [UIKeyboard defaultSize];
7063 CGRect keydown = [book_ pageBounds];
7064 CGRect keyup = keydown;
7065 keyup.size.height -= keysize.height - ButtonBarHeight_;
7067 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
7069 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
7070 [animation setSignificantRectFields:8];
7073 [animation setStartFrame:keydown];
7074 [animation setEndFrame:keyup];
7076 [animation setStartFrame:keyup];
7077 [animation setEndFrame:keydown];
7080 UIAnimator *animator = [UIAnimator sharedAnimator];
7083 addAnimations:[NSArray arrayWithObjects:animation, nil]
7084 withDuration:(KeyboardTime_ - delay)
7089 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
7091 [delegate_ showKeyboard:show];
7094 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
7095 [self _showKeyboard:YES];
7098 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
7099 [self _showKeyboard:NO];
7102 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
7104 NSString *text([field_ text]);
7105 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
7111 - (void) textFieldClearButtonPressed:(UITextField *)field {
7115 - (void) keyboardInputShouldDelete:(id)input {
7119 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
7120 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
7124 [field_ resignFirstResponder];
7129 - (id) initWithBook:(RVBook *)book database:(Database *)database {
7130 if ((self = [super initWithBook:book]) != nil) {
7131 CGRect pageBounds = [book_ pageBounds];
7133 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
7134 CGColor dimmed(space_, 0, 0, 0, 0.5);
7135 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
7137 table_ = [[FilteredPackageTable alloc]
7141 filter:@selector(isUnfilteredAndSearchedForBy:)
7145 [table_ setShouldHideHeaderInShortLists:NO];
7146 [self addSubview:table_];
7148 CGRect cnfrect = {{7, 38}, {17, 18}};
7155 area.size.width = [self bounds].size.width - area.origin.x * 2;
7156 area.size.height = [UISearchField defaultHeight];
7158 field_ = [[UISearchField alloc] initWithFrame:area];
7160 UIFont *font = [UIFont systemFontOfSize:16];
7161 [field_ setFont:font];
7163 [field_ setPlaceholder:UCLocalize("SEARCH_EX")];
7164 [field_ setDelegate:self];
7166 [field_ setPaddingTop:5];
7168 UITextInputTraits *traits([field_ textInputTraits]);
7169 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7170 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7171 [traits setReturnKeyType:UIReturnKeySearch];
7173 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
7175 accessory_ = [[UIView alloc] initWithFrame:accrect];
7176 [accessory_ addSubview:field_];
7178 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7179 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7183 - (void) resetViewAnimated:(BOOL)animated {
7184 [table_ resetViewAnimated:animated];
7187 - (void) _reloadData {
7190 - (void) reloadData {
7191 [table_ setObject:[field_ text]];
7192 _profile(SearchView$reloadData)
7193 [table_ reloadData];
7196 [table_ resetCursor];
7199 - (UIView *) accessoryView {
7203 - (NSString *) title {
7207 - (NSString *) backButtonTitle {
7208 return UCLocalize("SEARCH");
7211 - (void) setDelegate:(id)delegate {
7212 [table_ setDelegate:delegate];
7213 [super setDelegate:delegate];
7218 /* Settings View {{{ */
7219 @interface SettingsView : RVPage {
7220 _transient Database *database_;
7223 UIPreferencesTable *table_;
7224 _UISwitchSlider *subscribedSwitch_;
7225 _UISwitchSlider *ignoredSwitch_;
7226 UIPreferencesControlTableCell *subscribedCell_;
7227 UIPreferencesControlTableCell *ignoredCell_;
7230 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7234 @implementation SettingsView
7237 [table_ setDataSource:nil];
7240 if (package_ != nil)
7243 [subscribedSwitch_ release];
7244 [ignoredSwitch_ release];
7245 [subscribedCell_ release];
7246 [ignoredCell_ release];
7250 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7251 if (package_ == nil)
7257 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7258 if (package_ == nil)
7271 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7272 if (package_ == nil)
7285 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7286 if (package_ == nil)
7299 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7300 if (package_ == nil)
7303 _UISwitchSlider *slider([cell control]);
7304 BOOL value([slider value] != 0);
7305 NSMutableDictionary *metadata([package_ metadata]);
7308 if (NSNumber *number = [metadata objectForKey:key])
7309 before = [number boolValue];
7313 if (value != before) {
7314 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7316 [delegate_ updateData];
7320 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7321 [self onSomething:cell withKey:@"IsSubscribed"];
7324 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7325 [self onSomething:cell withKey:@"IsIgnored"];
7328 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7329 if (package_ == nil)
7333 case 0: switch (row) {
7335 return subscribedCell_;
7337 return ignoredCell_;
7341 case 1: switch (row) {
7343 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7344 [cell setShowSelection:NO];
7345 [cell setTitle:UCLocalize("SHOW_ALL_CHANGES_EX")];
7358 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7359 if ((self = [super initWithBook:book])) {
7360 database_ = database;
7361 name_ = [package retain];
7363 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7364 [self addSubview:table_];
7366 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7367 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventTouchUpInside];
7369 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7370 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventTouchUpInside];
7372 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7373 [subscribedCell_ setShowSelection:NO];
7374 [subscribedCell_ setTitle:UCLocalize("SHOW_ALL_CHANGES")];
7375 [subscribedCell_ setControl:subscribedSwitch_];
7377 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7378 [ignoredCell_ setShowSelection:NO];
7379 [ignoredCell_ setTitle:UCLocalize("IGNORE_UPGRADES")];
7380 [ignoredCell_ setControl:ignoredSwitch_];
7382 [table_ setDataSource:self];
7387 - (void) resetViewAnimated:(BOOL)animated {
7388 [table_ resetViewAnimated:animated];
7391 - (void) reloadData {
7392 if (package_ != nil)
7393 [package_ autorelease];
7394 package_ = [database_ packageWithName:name_];
7395 if (package_ != nil) {
7397 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7398 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7401 [table_ reloadData];
7404 - (NSString *) title {
7405 return UCLocalize("SETTINGS");
7411 /* Signature View {{{ */
7412 @interface SignatureView : CydiaBrowserView {
7413 _transient Database *database_;
7417 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7421 @implementation SignatureView
7428 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7430 [super webView:sender didClearWindowObject:window forFrame:frame];
7433 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7434 if ((self = [super initWithBook:book]) != nil) {
7435 database_ = database;
7436 package_ = [package retain];
7441 - (void) resetViewAnimated:(BOOL)animated {
7444 - (void) reloadData {
7445 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7451 @interface Cydia : UIApplication <
7452 ConfirmationViewDelegate,
7453 ProgressViewDelegate,
7462 UIToolbar *toolbar_;
7466 NSMutableArray *essential_;
7467 NSMutableArray *broken_;
7469 Database *database_;
7470 ProgressView *progress_;
7474 UIKeyboard *keyboard_;
7475 UIProgressHUD *hud_;
7477 SectionsView *sections_;
7478 ChangesView *changes_;
7479 ManageView *manage_;
7480 SearchView *search_;
7482 #if RecyclePackageViews
7483 NSMutableArray *details_;
7487 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7488 - (void) setPage:(RVPage *)page;
7492 static _finline void _setHomePage(Cydia *self) {
7493 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeView class]]];
7496 @implementation Cydia
7499 if ([broken_ count] != 0) {
7500 int count = [broken_ count];
7502 UIActionSheet *sheet = [[[UIActionSheet alloc]
7503 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7504 buttons:[NSArray arrayWithObjects:
7505 UCLocalize("FORCIBLY_CLEAR"),
7506 UCLocalize("TEMPORARY_IGNORE"),
7508 defaultButtonIndex:0
7513 [sheet setBodyText:UCLocalize("HALFINSTALLED_PACKAGE_EX")];
7514 [sheet popupAlertAnimated:YES];
7515 } else if (!Ignored_ && [essential_ count] != 0) {
7516 int count = [essential_ count];
7518 UIActionSheet *sheet = [[[UIActionSheet alloc]
7519 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7520 buttons:[NSArray arrayWithObjects:
7521 UCLocalize("UPGRADE_ESSENTIAL"),
7522 UCLocalize("COMPLETE_UPGRADE"),
7523 UCLocalize("TEMPORARY_IGNORE"),
7525 defaultButtonIndex:0
7530 [sheet setBodyText:UCLocalize("ESSENTIAL_UPGRADE_EX")];
7531 [sheet popupAlertAnimated:YES];
7535 - (void) _saveConfig {
7538 NSString *error(nil);
7539 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7541 NSError *error(nil);
7542 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7543 NSLog(@"failure to save metadata data: %@", error);
7546 NSLog(@"failure to serialize metadata: %@", error);
7554 - (void) _updateData {
7557 /* XXX: this is just stupid */
7558 if (tag_ != 2 && sections_ != nil)
7559 [sections_ reloadData];
7560 if (tag_ != 3 && changes_ != nil)
7561 [changes_ reloadData];
7562 if (tag_ != 5 && search_ != nil)
7563 [search_ reloadData];
7568 - (void) _reloadData {
7571 static bool loaded(false);
7572 UIProgressHUD *hud([self addProgressHUD]);
7573 [hud setText:(loaded ? UCLocalize("RELOADING_DATA") : UCLocalize("LOADING_DATA"))];
7575 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7578 [self removeProgressHUD:hud];
7582 [essential_ removeAllObjects];
7583 [broken_ removeAllObjects];
7585 NSArray *packages([database_ packages]);
7586 for (Package *package in packages) {
7588 [broken_ addObject:package];
7589 if ([package upgradableAndEssential:NO]) {
7590 if ([package essential])
7591 [essential_ addObject:package];
7597 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7598 [toolbar_ setBadgeValue:badge forButton:3];
7599 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7600 [toolbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7601 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7602 [self setApplicationBadge:badge];
7604 [self setApplicationBadgeString:badge];
7606 [toolbar_ setBadgeValue:nil forButton:3];
7607 if ([toolbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7608 [toolbar_ setBadgeAnimated:NO forButton:3];
7609 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7610 [self removeApplicationBadge];
7611 else // XXX: maybe use setApplicationBadgeString also?
7612 [self setApplicationIconBadgeNumber:0];
7616 [toolbar_ setBadgeValue:nil forButton:4];
7620 if (loaded || ManualRefresh) loaded:
7625 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7626 NSTimeInterval interval([update timeIntervalSinceNow]);
7627 if (interval <= 0 && interval > -(15*60))
7635 - (void) updateData {
7636 [database_ setVisible];
7645 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
7646 _assert(file != NULL);
7648 for (NSString *key in [Sources_ allKeys]) {
7649 NSDictionary *source([Sources_ objectForKey:key]);
7651 fprintf(file, "%s %s %s\n",
7652 [[source objectForKey:@"Type"] UTF8String],
7653 [[source objectForKey:@"URI"] UTF8String],
7654 [[source objectForKey:@"Distribution"] UTF8String]
7663 detachNewThreadSelector:@selector(update_)
7666 title:UCLocalize("UPDATING_SOURCES")
7670 - (void) reloadData {
7671 @synchronized (self) {
7672 if (confirm_ == nil)
7678 pkgProblemResolver *resolver = [database_ resolver];
7680 resolver->InstallProtect();
7681 if (!resolver->Resolve(true))
7685 - (void) popUpBook:(RVBook *)book {
7686 [underlay_ popSubview:book];
7689 - (CGRect) popUpBounds {
7690 return [underlay_ bounds];
7694 if (![database_ prepare])
7697 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7698 [confirm_ setDelegate:self];
7700 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7701 [page setDelegate:self];
7703 [confirm_ setPage:page];
7704 [self popUpBook:confirm_];
7710 @synchronized (self) {
7715 - (void) clearPackage:(Package *)package {
7716 @synchronized (self) {
7723 - (void) installPackage:(Package *)package {
7724 @synchronized (self) {
7731 - (void) removePackage:(Package *)package {
7732 @synchronized (self) {
7739 - (void) distUpgrade {
7740 @synchronized (self) {
7741 if (![database_ upgrade])
7748 [self slideUp:[[[UIActionSheet alloc]
7750 buttons:[NSArray arrayWithObjects:UCLocalize("CONTINUE_QUEUING"), UCLocalize("CANCEL_CLEAR"), nil]
7751 defaultButtonIndex:1
7758 @synchronized (self) {
7761 if (confirm_ != nil) {
7769 [overlay_ removeFromSuperview];
7773 detachNewThreadSelector:@selector(perform)
7776 title:UCLocalize("RUNNING")
7780 - (void) progressViewIsComplete:(ProgressView *)progress {
7781 if (confirm_ != nil) {
7782 [underlay_ addSubview:overlay_];
7783 [confirm_ popFromSuperviewAnimated:NO];
7789 - (void) setPage:(RVPage *)page {
7790 [page resetViewAnimated:NO];
7791 [page setDelegate:self];
7792 [book_ setPage:page];
7795 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7796 CydiaBrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7797 [browser loadURL:url];
7801 - (SectionsView *) sectionsView {
7802 if (sections_ == nil)
7803 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7807 - (void) buttonBarItemTapped:(id)sender {
7808 unsigned tag = [sender tag];
7810 [book_ resetViewAnimated:YES];
7812 } else if (tag_ == 2)
7813 [[self sectionsView] resetView];
7816 case 1: _setHomePage(self); break;
7818 case 2: [self setPage:[self sectionsView]]; break;
7819 case 3: [self setPage:changes_]; break;
7820 case 4: [self setPage:manage_]; break;
7821 case 5: [self setPage:search_]; break;
7829 - (void) askForSettings {
7830 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
7832 CYActionSheet *role([[[CYActionSheet alloc]
7833 initWithTitle:UCLocalize("WHO_ARE_YOU")
7834 buttons:[NSArray arrayWithObjects:
7835 [NSString stringWithFormat:parenthetical, UCLocalize("USER"), UCLocalize("USER_EX")],
7836 [NSString stringWithFormat:parenthetical, UCLocalize("HACKER"), UCLocalize("HACKER_EX")],
7837 [NSString stringWithFormat:parenthetical, UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")],
7839 defaultButtonIndex:-1
7842 [role setBodyText:UCLocalize("ROLE_EX")];
7844 int button([role yieldToPopupAlertAnimated:YES]);
7847 case 1: Role_ = @"User"; break;
7848 case 2: Role_ = @"Hacker"; break;
7849 case 3: Role_ = @"Developer"; break;
7854 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7858 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7865 - (void) setPackageView:(PackageView *)view {
7867 [view setPackage:nil];
7868 #if RecyclePackageViews
7869 if ([details_ count] < 3)
7870 [details_ addObject:view];
7875 - (PackageView *) _packageView {
7876 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7879 - (PackageView *) packageView {
7880 #if RecyclePackageViews
7882 size_t count([details_ count]);
7885 view = [self _packageView];
7887 [details_ addObject:[self _packageView]];
7889 view = [[[details_ lastObject] retain] autorelease];
7890 [details_ removeLastObject];
7897 return [self _packageView];
7901 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7902 NSString *context([sheet context]);
7904 if ([context isEqualToString:@"missing"])
7906 else if ([context isEqualToString:@"cancel"]) {
7923 @synchronized (self) {
7928 [toolbar_ setBadgeValue:UCLocalize("Q_D") forButton:4];
7932 if (confirm_ != nil) {
7937 } else if ([context isEqualToString:@"fixhalf"]) {
7940 @synchronized (self) {
7941 for (Package *broken in broken_) {
7944 NSString *id = [broken id];
7945 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7946 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7947 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7948 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7957 [broken_ removeAllObjects];
7965 } else if ([context isEqualToString:@"upgrade"]) {
7968 @synchronized (self) {
7969 for (Package *essential in essential_)
7970 [essential install];
7992 - (void) system:(NSString *)command { _pooled
7993 system([command UTF8String]);
7996 - (void) applicationWillSuspend {
7998 [super applicationWillSuspend];
8001 - (void) applicationSuspend:(__GSEvent *)event {
8002 if (hud_ == nil && ![progress_ isRunning])
8003 [super applicationSuspend:event];
8006 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8008 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8011 - (void) _setSuspended:(BOOL)value {
8013 [super _setSuspended:value];
8016 - (UIProgressHUD *) addProgressHUD {
8017 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8018 [window_ setUserInteractionEnabled:NO];
8020 [progress_ addSubview:hud];
8024 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8026 [hud removeFromSuperview];
8027 [window_ setUserInteractionEnabled:YES];
8030 - (RVPage *) pageForPackage:(NSString *)name {
8031 if (Package *package = [database_ packageWithName:name]) {
8032 PackageView *view([self packageView]);
8033 [view setPackage:package];
8036 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8037 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8038 return [self _pageForURL:url withClass:[CydiaBrowserView class]];
8042 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8046 NSString *href([url absoluteString]);
8047 if ([href hasPrefix:@"apptapp://package/"])
8048 return [self pageForPackage:[href substringFromIndex:18]];
8050 NSString *scheme([[url scheme] lowercaseString]);
8051 if (![scheme isEqualToString:@"cydia"])
8053 NSString *path([url absoluteString]);
8054 if ([path length] < 8)
8056 path = [path substringFromIndex:8];
8057 if (![path hasPrefix:@"/"])
8058 path = [@"/" stringByAppendingString:path];
8060 if ([path isEqualToString:@"/add-source"])
8061 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8062 else if ([path isEqualToString:@"/storage"])
8063 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CydiaBrowserView class]];
8064 else if ([path isEqualToString:@"/sources"])
8065 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8066 else if ([path isEqualToString:@"/packages"])
8067 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8068 else if ([path hasPrefix:@"/url/"])
8069 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CydiaBrowserView class]];
8070 else if ([path hasPrefix:@"/launch/"])
8071 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8072 else if ([path hasPrefix:@"/package-settings/"])
8073 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8074 else if ([path hasPrefix:@"/package-signature/"])
8075 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8076 else if ([path hasPrefix:@"/package/"])
8077 return [self pageForPackage:[path substringFromIndex:9]];
8078 else if ([path hasPrefix:@"/files/"]) {
8079 NSString *name = [path substringFromIndex:7];
8081 if (Package *package = [database_ packageWithName:name]) {
8082 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8083 [files setPackage:package];
8091 - (void) applicationOpenURL:(NSURL *)url {
8092 [super applicationOpenURL:url];
8094 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8095 [self setPage:page];
8096 [toolbar_ showSelectionForButton:tag];
8101 - (void) applicationDidFinishLaunching:(id)unused {
8102 [BrowserView _initialize];
8104 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8106 Font12_ = [[UIFont systemFontOfSize:12] retain];
8107 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8108 Font14_ = [[UIFont systemFontOfSize:14] retain];
8109 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8110 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8114 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8115 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8117 window_ = [[UIWindow alloc] initWithContentRect:[UIHardware fullScreenApplicationContentRect]];
8118 [window_ orderFront:self];
8119 [window_ makeKey:self];
8120 [window_ setHidden:NO];
8122 database_ = [Database sharedInstance];
8124 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8125 [database_ setDelegate:progress_];
8126 [window_ setContentView:progress_];
8128 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8129 [progress_ setContentView:underlay_];
8131 [progress_ resetView];
8134 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8135 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8136 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8137 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8138 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8139 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8140 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8141 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8142 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8145 [self setIdleTimerDisabled:YES];
8147 hud_ = [self addProgressHUD];
8148 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8149 [self setStatusBarShowsProgress:YES];
8151 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8153 [self setStatusBarShowsProgress:NO];
8154 [self removeProgressHUD:hud_];
8157 if (ExecFork() == 0) {
8158 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8159 perror("launchctl stop");
8166 [self askForSettings];
8169 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
8171 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8172 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
8173 0, 0, screenrect.size.width, screenrect.size.height - 48
8174 ) database:database_];
8176 [book_ setDelegate:self];
8178 [overlay_ addSubview:book_];
8180 NSArray *buttonitems = [NSArray arrayWithObjects:
8181 [NSDictionary dictionaryWithObjectsAndKeys:
8182 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8183 @"home-up.png", kUIButtonBarButtonInfo,
8184 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
8185 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
8186 self, kUIButtonBarButtonTarget,
8187 @"Cydia", kUIButtonBarButtonTitle,
8188 @"0", kUIButtonBarButtonType,
8191 [NSDictionary dictionaryWithObjectsAndKeys:
8192 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8193 @"install-up.png", kUIButtonBarButtonInfo,
8194 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
8195 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
8196 self, kUIButtonBarButtonTarget,
8197 UCLocalize("SECTIONS"), kUIButtonBarButtonTitle,
8198 @"0", kUIButtonBarButtonType,
8201 [NSDictionary dictionaryWithObjectsAndKeys:
8202 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8203 @"changes-up.png", kUIButtonBarButtonInfo,
8204 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
8205 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
8206 self, kUIButtonBarButtonTarget,
8207 UCLocalize("CHANGES"), kUIButtonBarButtonTitle,
8208 @"0", kUIButtonBarButtonType,
8211 [NSDictionary dictionaryWithObjectsAndKeys:
8212 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8213 @"manage-up.png", kUIButtonBarButtonInfo,
8214 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
8215 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
8216 self, kUIButtonBarButtonTarget,
8217 UCLocalize("MANAGE"), kUIButtonBarButtonTitle,
8218 @"0", kUIButtonBarButtonType,
8221 [NSDictionary dictionaryWithObjectsAndKeys:
8222 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
8223 @"search-up.png", kUIButtonBarButtonInfo,
8224 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
8225 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
8226 self, kUIButtonBarButtonTarget,
8227 UCLocalize("SEARCH"), kUIButtonBarButtonTitle,
8228 @"0", kUIButtonBarButtonType,
8232 toolbar_ = [[UIToolbar alloc]
8234 withFrame:CGRectMake(
8235 0, screenrect.size.height - ButtonBarHeight_,
8236 screenrect.size.width, ButtonBarHeight_
8238 withItemList:buttonitems
8241 [toolbar_ setDelegate:self];
8242 [toolbar_ setBarStyle:1];
8243 [toolbar_ setButtonBarTrackingMode:2];
8245 int buttons[5] = {1, 2, 3, 4, 5};
8246 [toolbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
8247 [toolbar_ showButtonGroup:0 withDuration:0];
8249 for (int i = 0; i != 5; ++i)
8250 [[toolbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
8251 i * 64 + 2, 1, 60, ButtonBarHeight_
8254 [toolbar_ showSelectionForButton:1];
8255 [overlay_ addSubview:toolbar_];
8257 [UIKeyboard initImplementationNow];
8258 CGSize keysize = [UIKeyboard defaultSize];
8259 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
8260 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
8261 [overlay_ addSubview:keyboard_];
8263 [underlay_ addSubview:overlay_];
8267 [self sectionsView];
8268 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
8269 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
8271 manage_ = (ManageView *) [[self
8272 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8273 withClass:[ManageView class]
8276 #if RecyclePackageViews
8277 details_ = [[NSMutableArray alloc] initWithCapacity:4];
8278 [details_ addObject:[self _packageView]];
8279 [details_ addObject:[self _packageView]];
8287 - (void) showKeyboard:(BOOL)show {
8288 CGSize keysize([UIKeyboard defaultSize]);
8289 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8290 CGRect keyup(keydown);
8291 keyup.origin.y -= keysize.height;
8293 UIFrameAnimation *animation([[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease]);
8294 [animation setSignificantRectFields:2];
8297 [animation setStartFrame:keydown];
8298 [animation setEndFrame:keyup];
8299 [keyboard_ activate];
8301 [animation setStartFrame:keyup];
8302 [animation setEndFrame:keydown];
8303 [keyboard_ deactivate];
8306 [[UIAnimator sharedAnimator]
8307 addAnimations:[NSArray arrayWithObjects:animation, nil]
8308 withDuration:KeyboardTime_
8313 - (void) slideUp:(UIActionSheet *)alert {
8314 [alert presentSheetInView:overlay_];
8320 id Alloc_(id self, SEL selector) {
8321 id object = alloc_(self, selector);
8322 lprintf("[%s]A-%p\n", self->isa->name, object);
8327 id Dealloc_(id self, SEL selector) {
8328 id object = dealloc_(self, selector);
8329 lprintf("[%s]D-%p\n", self->isa->name, object);
8333 Class $WebDefaultUIKitDelegate;
8335 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8336 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8337 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8338 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8341 int main(int argc, char *argv[]) { _pooled
8344 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8346 /* Library Hacks {{{ */
8347 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8349 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8350 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8351 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8352 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8353 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8356 /* Set Locale {{{ */
8357 Locale_ = CFLocaleCopyCurrent();
8358 Languages_ = [NSLocale preferredLanguages];
8359 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8360 //NSLog(@"%@", [Languages_ description]);
8363 if (Languages_ == nil || [Languages_ count] == 0)
8364 // XXX: consider just setting to C and then falling through?
8367 lang = [[Languages_ objectAtIndex:0] UTF8String];
8368 setenv("LANG", lang, true);
8371 //std::setlocale(LC_ALL, lang);
8372 NSLog(@"Setting Language: %s", lang);
8375 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8377 /* Parse Arguments {{{ */
8378 bool substrate(false);
8384 for (int argi(1); argi != argc; ++argi)
8385 if (strcmp(argv[argi], "--") == 0) {
8387 argv[argi] = argv[0];
8393 for (int argi(1); argi != arge; ++argi)
8394 if (strcmp(args[argi], "--substrate") == 0)
8397 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8401 App_ = [[NSBundle mainBundle] bundlePath];
8402 Home_ = NSHomeDirectory();
8408 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8409 alloc_ = alloc->method_imp;
8410 alloc->method_imp = (IMP) &Alloc_;*/
8412 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8413 dealloc_ = dealloc->method_imp;
8414 dealloc->method_imp = (IMP) &Dealloc_;*/
8416 /* System Information {{{ */
8420 size = sizeof(maxproc);
8421 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8422 perror("sysctlbyname(\"kern.maxproc\", ?)");
8423 else if (maxproc < 64) {
8425 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8426 perror("sysctlbyname(\"kern.maxproc\", #)");
8429 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8430 char *osversion = new char[size];
8431 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8432 perror("sysctlbyname(\"kern.osversion\", ?)");
8434 System_ = [NSString stringWithUTF8String:osversion];
8436 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8437 char *machine = new char[size];
8438 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8439 perror("sysctlbyname(\"hw.machine\", ?)");
8443 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8444 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8445 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8446 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8450 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8451 NSData *data((NSData *) ecid);
8452 size_t length([data length]);
8453 uint8_t bytes[length];
8454 [data getBytes:bytes];
8455 char string[length * 2 + 1];
8456 for (size_t i(0); i != length; ++i)
8457 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8458 ChipID_ = [NSString stringWithUTF8String:string];
8462 IOObjectRelease(service);
8466 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8468 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8469 Build_ = [system objectForKey:@"ProductBuildVersion"];
8470 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8471 Product_ = [info objectForKey:@"SafariProductVersion"];
8472 Safari_ = [info objectForKey:@"CFBundleVersion"];
8475 /* Load Database {{{ */
8477 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8479 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8482 if (Metadata_ == NULL)
8483 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8485 Settings_ = [Metadata_ objectForKey:@"Settings"];
8487 Packages_ = [Metadata_ objectForKey:@"Packages"];
8488 Sections_ = [Metadata_ objectForKey:@"Sections"];
8489 Sources_ = [Metadata_ objectForKey:@"Sources"];
8492 if (Settings_ != nil)
8493 Role_ = [Settings_ objectForKey:@"Role"];
8495 if (Packages_ == nil) {
8496 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8497 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8500 if (Sections_ == nil) {
8501 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8502 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8505 if (Sources_ == nil) {
8506 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8507 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8512 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8515 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8517 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8518 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8519 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8520 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8522 if (access("/tmp/.cydia.fw", F_OK) == 0) {
8523 unlink("/tmp/.cydia.fw");
8525 } else if (access("/User", F_OK) != 0) {
8528 system("/usr/libexec/cydia/firmware.sh");
8532 _assert([[NSFileManager defaultManager]
8533 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8534 withIntermediateDirectories:YES
8539 if (access("/tmp/cydia.chk", F_OK) == 0) {
8540 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8541 _assert(errno == ENOENT);
8542 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8543 _assert(errno == ENOENT);
8546 /* APT Initialization {{{ */
8547 _assert(pkgInitConfig(*_config));
8548 _assert(pkgInitSystem(*_config, _system));
8551 _config->Set("APT::Acquire::Translation", lang);
8552 _config->Set("Acquire::http::Timeout", 15);
8553 _config->Set("Acquire::http::MaxParallel", 3);
8555 /* Color Choices {{{ */
8556 space_ = CGColorSpaceCreateDeviceRGB();
8558 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8559 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8560 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8561 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8562 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8563 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8564 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8565 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8566 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8568 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8569 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8571 /* UIKit Configuration {{{ */
8572 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8573 if ($GSFontSetUseLegacyFontMetrics != NULL)
8574 $GSFontSetUseLegacyFontMetrics(YES);
8576 UIKeyboardDisableAutomaticAppearance();
8579 Colon_ = UCLocalize("COLON_DELIMITED");
8580 Error_ = UCLocalize("ERROR");
8581 Warning_ = UCLocalize("WARNING");
8584 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8586 CGColorSpaceRelease(space_);