1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2009 Jay Freeman (saurik)
6 * Redistribution and use in source and binary
7 * forms, with or without modification, are permitted
8 * provided that the following conditions are met:
10 * 1. Redistributions of source code must retain the
11 * above copyright notice, this list of conditions
12 * and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the
14 * above copyright notice, this list of conditions
15 * and the following disclaimer in the documentation
16 * and/or other materials provided with the
18 * 3. The name of the author may not be used to endorse
19 * or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
23 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
24 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
28 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
30 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
33 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
35 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 // XXX: wtf/FastMalloc.h... wtf?
39 #define USE_SYSTEM_MALLOC 1
41 /* #include Directives {{{ */
42 #import "UICaboodle.h"
44 #include <objc/message.h>
45 #include <objc/objc.h>
46 #include <objc/runtime.h>
48 #include <CoreGraphics/CoreGraphics.h>
49 #include <GraphicsServices/GraphicsServices.h>
50 #include <Foundation/Foundation.h>
53 #define DEPLOYMENT_TARGET_MACOSX 1
54 #define CF_BUILDING_CF 1
55 #include <CoreFoundation/CFInternal.h>
58 #include <CoreFoundation/CFPriv.h>
59 #include <CoreFoundation/CFUniChar.h>
61 #import <QuartzCore/CALayer.h>
62 #import <UIKit/UIKit.h>
64 #include <WebCore/WebCoreThread.h>
65 #import <WebKit/WebDefaultUIKitDelegate.h>
72 #include <ext/stdio_filebuf.h>
74 #include <apt-pkg/acquire.h>
75 #include <apt-pkg/acquire-item.h>
76 #include <apt-pkg/algorithms.h>
77 #include <apt-pkg/cachefile.h>
78 #include <apt-pkg/clean.h>
79 #include <apt-pkg/configuration.h>
80 #include <apt-pkg/debindexfile.h>
81 #include <apt-pkg/debmetaindex.h>
82 #include <apt-pkg/error.h>
83 #include <apt-pkg/init.h>
84 #include <apt-pkg/mmap.h>
85 #include <apt-pkg/pkgrecords.h>
86 #include <apt-pkg/sha1.h>
87 #include <apt-pkg/sourcelist.h>
88 #include <apt-pkg/sptr.h>
89 #include <apt-pkg/strutl.h>
90 #include <apt-pkg/tagfile.h>
92 #include <apr-1/apr_pools.h>
94 #include <sys/types.h>
96 #include <sys/sysctl.h>
97 #include <sys/param.h>
98 #include <sys/mount.h>
104 #include <mach-o/nlist.h>
114 #include <ext/hash_map>
116 #import "BrowserView.h"
117 #import "ResetView.h"
119 #import "substrate.h"
122 //#define _finline __attribute__((force_inline))
123 #define _finline inline
128 #define _limit(count) do { \
129 static size_t _count(0); \
130 if (++_count == count) \
135 #define _timestamp ({ \
137 gettimeofday(&tv, NULL); \
138 tv.tv_sec * 1000000 + tv.tv_usec; \
141 typedef std::vector<class ProfileTime *> TimeList;
151 ProfileTime(const char *name) :
155 times_.push_back(this);
158 void AddTime(uint64_t time) {
165 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
177 ProfileTimer(ProfileTime &time) :
184 time_.AddTime(_timestamp - start_);
189 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
191 std::cerr << "========" << std::endl;
194 #define _profile(name) { \
195 static ProfileTime name(#name); \
196 ProfileTimer _ ## name(name);
200 /* Objective-C Handle<> {{{ */
201 template <typename Type_>
203 typedef _H<Type_> This_;
208 _finline void Retain_() {
213 _finline void Clear_() {
219 _finline _H(const This_ &rhs) :
220 value_(rhs.value_ == nil ? nil : [rhs.value_ retain])
224 _finline _H(Type_ *value = NULL, bool mended = false) :
235 _finline operator Type_ *() const {
239 _finline This_ &operator =(Type_ *value) {
240 if (value_ != value) {
251 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
253 void NSLogPoint(const char *fix, const CGPoint &point) {
254 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
257 void NSLogRect(const char *fix, const CGRect &rect) {
258 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
261 @interface NSObject (Cydia)
262 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
263 - (id) yieldToSelector:(SEL)selector;
266 @implementation NSObject (Cydia)
271 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
272 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
273 id object([[context objectAtIndex:1] nonretainedObjectValue]);
274 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
276 /* XXX: deal with exceptions */
277 id value([self performSelector:selector withObject:object]);
279 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
280 [context removeAllObjects];
281 if ([signature methodReturnLength] != 0 && value != nil)
282 [context addObject:value];
287 performSelectorOnMainThread:@selector(doNothing)
293 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
294 /*return [self performSelector:selector withObject:object];*/
296 volatile bool stopped(false);
298 NSMutableArray *context([NSMutableArray arrayWithObjects:
299 [NSValue valueWithPointer:selector],
300 [NSValue valueWithNonretainedObject:object],
301 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
304 NSThread *thread([[[NSThread alloc]
306 selector:@selector(_yieldToContext:)
312 NSRunLoop *loop([NSRunLoop currentRunLoop]);
313 NSDate *future([NSDate distantFuture]);
315 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
317 return [context count] == 0 ? nil : [context objectAtIndex:0];
320 - (id) yieldToSelector:(SEL)selector {
321 return [self yieldToSelector:selector withObject:nil];
326 /* NSForcedOrderingSearch doesn't work on the iPhone */
327 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
328 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
329 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
331 /* iPhoneOS 2.0 Compatibility {{{ */
333 @interface UITextView (iPhoneOS)
334 - (void) setTextSize:(float)size;
337 @implementation UITextView (iPhoneOS)
339 - (void) setTextSize:(float)size {
340 [self setFont:[[self font] fontWithSize:size]];
347 extern NSString * const kCAFilterNearest;
349 /* Information Dictionaries {{{ */
350 @interface NSMutableArray (Cydia)
351 - (void) addInfoDictionary:(NSDictionary *)info;
354 @implementation NSMutableArray (Cydia)
356 - (void) addInfoDictionary:(NSDictionary *)info {
357 [self addObject:info];
362 @interface NSMutableDictionary (Cydia)
363 - (void) addInfoDictionary:(NSDictionary *)info;
366 @implementation NSMutableDictionary (Cydia)
368 - (void) addInfoDictionary:(NSDictionary *)info {
369 NSString *bundle = [info objectForKey:@"CFBundleIdentifier"];
370 [self setObject:info forKey:bundle];
375 /* Pop Transitions {{{ */
376 @interface PopTransitionView : UITransitionView {
381 @implementation PopTransitionView
383 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
384 if (from != nil && to == nil)
385 [self removeFromSuperview];
390 @implementation UIView (PopUpView)
392 - (void) popFromSuperviewAnimated:(BOOL)animated {
393 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
396 - (void) popSubview:(UIView *)view {
397 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
398 [transition setDelegate:transition];
399 [self addSubview:transition];
401 UIView *blank = [[[UIView alloc] initWithFrame:[transition bounds]] autorelease];
402 [transition transition:UITransitionNone toView:blank];
403 [transition transition:UITransitionPushFromBottom toView:view];
409 #define lprintf(args...) fprintf(stderr, args)
412 #define TraceLogging (1 && !ForRelease)
413 #define HistogramInsertionSort (0 && !ForRelease)
414 #define ProfileTimes (0 && !ForRelease)
415 #define ForSaurik (0 && !ForRelease)
416 #define LogBrowser (1 && !ForRelease)
417 #define TrackResize (0 && !ForRelease)
418 #define ManualRefresh (1 && !ForRelease)
419 #define ShowInternals (0 && !ForRelease)
420 #define IgnoreInstall (0 && !ForRelease)
421 #define RecycleWebViews 0
422 #define AlwaysReload (1 && !ForRelease)
426 #define _trace(args...)
431 #define _profile(name) {
434 #define PrintTimes() do {} while (false)
438 typedef uint32_t (*SKRadixFunction)(id, void *);
440 @interface NSMutableArray (Radix)
441 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
442 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
450 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
451 struct RadixItem_ *lhs(swap), *rhs(swap + count);
453 static const size_t width = 32;
454 static const size_t bits = 11;
455 static const size_t slots = 1 << bits;
456 static const size_t passes = (width + (bits - 1)) / bits;
458 size_t *hist(new size_t[slots]);
460 for (size_t pass(0); pass != passes; ++pass) {
461 memset(hist, 0, sizeof(size_t) * slots);
463 for (size_t i(0); i != count; ++i) {
464 uint32_t key(lhs[i].key);
466 key &= _not(uint32_t) >> width - bits;
471 for (size_t i(0); i != slots; ++i) {
472 size_t local(offset);
477 for (size_t i(0); i != count; ++i) {
478 uint32_t key(lhs[i].key);
480 key &= _not(uint32_t) >> width - bits;
481 rhs[hist[key]++] = lhs[i];
484 RadixItem_ *tmp(lhs);
491 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
492 for (size_t i(0); i != count; ++i)
493 [values addObject:[self objectAtIndex:lhs[i].index]];
494 [self setArray:values];
499 @implementation NSMutableArray (Radix)
501 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
502 size_t count([self count]);
507 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
508 [invocation setSelector:selector];
509 [invocation setArgument:&object atIndex:2];
511 /* XXX: this is an unsafe optimization of doomy hell */
512 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
513 _assert(method != NULL);
514 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
515 _assert(imp != NULL);
518 struct RadixItem_ *swap(new RadixItem_[count * 2]);
520 for (size_t i(0); i != count; ++i) {
521 RadixItem_ &item(swap[i]);
524 id object([self objectAtIndex:i]);
527 [invocation setTarget:object];
529 [invocation getReturnValue:&item.key];
531 item.key = imp(object, selector, object);
535 RadixSort_(self, count, swap);
538 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
539 size_t count([self count]);
540 struct RadixItem_ *swap(new RadixItem_[count * 2]);
542 for (size_t i(0); i != count; ++i) {
543 RadixItem_ &item(swap[i]);
546 id object([self objectAtIndex:i]);
547 item.key = function(object, argument);
550 RadixSort_(self, count, swap);
555 /* Insertion Sort {{{ */
557 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
558 const char *ptr = (const char *)list;
560 CFIndex half = count / 2;
561 const char *probe = ptr + elementSize * half;
562 CFComparisonResult cr = comparator(element, probe, context);
563 if (0 == cr) return (probe - (const char *)list) / elementSize;
564 ptr = (cr < 0) ? ptr : probe + elementSize;
565 count = (cr < 0) ? half : (half + (count & 1) - 1);
567 return (ptr - (const char *)list) / elementSize;
570 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
571 const char *ptr = (const char *)list;
573 CFIndex half = count / 2;
574 const char *probe = ptr + elementSize * half;
575 CFComparisonResult cr = comparator(element, probe, context);
576 if (0 == cr) return (probe - (const char *)list) / elementSize;
577 ptr = (cr < 0) ? ptr : probe + elementSize;
578 count = (cr < 0) ? half : (half + (count & 1) - 1);
580 return (ptr - (const char *)list) / elementSize;
583 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
584 if (range.length == 0)
586 const void **values(new const void *[range.length]);
587 CFArrayGetValues(array, range, values);
589 #if HistogramInsertionSort
590 uint32_t total(0), *offsets(new uint32_t[range.length]);
593 for (CFIndex index(1); index != range.length; ++index) {
594 const void *value(values[index]);
595 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
596 CFIndex correct(index);
597 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
600 if (correct != index) {
601 size_t offset(index - correct);
602 #if HistogramInsertionSort
606 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
608 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
609 values[correct] = value;
613 CFArrayReplaceValues(array, range, values, range.length);
616 #if HistogramInsertionSort
617 for (CFIndex index(0); index != range.length; ++index)
618 if (offsets[index] != 0)
619 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
620 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
627 /* Apple Bug Fixes {{{ */
628 @implementation UIWebDocumentView (Cydia)
630 - (void) _setScrollerOffset:(CGPoint)offset {
631 UIScroller *scroller([self _scroller]);
633 CGSize size([scroller contentSize]);
634 CGSize bounds([scroller bounds].size);
637 max.x = size.width - bounds.width;
638 max.y = size.height - bounds.height;
646 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
647 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
649 [scroller setOffset:offset];
656 kUIControlEventMouseDown = 1 << 0,
657 kUIControlEventMouseMovedInside = 1 << 2, // mouse moved inside control target
658 kUIControlEventMouseMovedOutside = 1 << 3, // mouse moved outside control target
659 kUIControlEventMouseUpInside = 1 << 6, // mouse up inside control target
660 kUIControlEventMouseUpOutside = 1 << 7, // mouse up outside control target
661 kUIControlAllEvents = (kUIControlEventMouseDown | kUIControlEventMouseMovedInside | kUIControlEventMouseMovedOutside | kUIControlEventMouseUpInside | kUIControlEventMouseUpOutside)
662 } UIControlEventMasks;
664 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
665 size_t length([self length] - state->state);
668 else if (length > count)
670 for (size_t i(0); i != length; ++i)
671 objects[i] = [self item:state->state++];
672 state->itemsPtr = objects;
673 state->mutationsPtr = (unsigned long *) self;
677 @interface NSString (UIKit)
678 - (NSString *) stringByAddingPercentEscapes;
679 - (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
682 @interface NSString (Cydia)
683 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
684 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
685 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
686 - (NSComparisonResult) compareByPath:(NSString *)other;
687 - (NSString *) stringByCachingURLWithCurrentCDN;
688 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
691 @implementation NSString (Cydia)
693 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
694 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
697 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
698 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
699 memcpy(data, bytes, length);
700 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
703 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
704 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
707 - (NSComparisonResult) compareByPath:(NSString *)other {
708 NSString *prefix = [self commonPrefixWithString:other options:0];
709 size_t length = [prefix length];
711 NSRange lrange = NSMakeRange(length, [self length] - length);
712 NSRange rrange = NSMakeRange(length, [other length] - length);
714 lrange = [self rangeOfString:@"/" options:0 range:lrange];
715 rrange = [other rangeOfString:@"/" options:0 range:rrange];
717 NSComparisonResult value;
719 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
720 value = NSOrderedSame;
721 else if (lrange.location == NSNotFound)
722 value = NSOrderedAscending;
723 else if (rrange.location == NSNotFound)
724 value = NSOrderedDescending;
726 value = NSOrderedSame;
728 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
729 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
730 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
731 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
733 NSComparisonResult result = [lpath compare:rpath];
734 return result == NSOrderedSame ? value : result;
737 - (NSString *) stringByCachingURLWithCurrentCDN {
739 stringByReplacingOccurrencesOfString:@"://"
740 withString:@"://ne.edgecastcdn.net/8003A4/"
742 /* XXX: this is somewhat inaccurate */
743 range:NSMakeRange(0, 10)
747 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
748 return [(id)CFURLCreateStringByAddingPercentEscapes(
753 kCFStringEncodingUTF8
759 static inline NSString *CYLocalizeEx(NSString *key, NSString *value = nil) {
760 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:nil];
763 #define CYLocalize(key) CYLocalizeEx(@ key)
771 _finline void clear_() {
772 if (cache_ != NULL) {
779 _finline bool empty() const {
783 _finline size_t size() const {
787 _finline char *data() const {
791 _finline void clear() {
796 _finline CYString() :
803 _finline ~CYString() {
807 void operator =(const CYString &rhs) {
811 if (rhs.cache_ == nil)
814 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
817 void set(apr_pool_t *pool, const char *data, size_t size) {
823 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
824 memcpy(temp, data, size);
831 _finline void set(apr_pool_t *pool, const char *data) {
832 set(pool, data, data == NULL ? 0 : strlen(data));
835 _finline void set(apr_pool_t *pool, const std::string &rhs) {
836 set(pool, rhs.data(), rhs.size());
839 bool operator ==(const CYString &rhs) const {
840 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
843 operator CFStringRef() {
844 if (cache_ == NULL) {
847 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
851 _finline operator id() {
852 return (NSString *) static_cast<CFStringRef>(*this);
857 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
860 struct NSStringMapHash :
861 std::unary_function<NSString *, size_t>
863 _finline size_t operator ()(NSString *value) const {
864 return CFStringHashNSString((CFStringRef) value);
868 struct NSStringMapLess :
869 std::binary_function<NSString *, NSString *, bool>
871 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
872 return [lhs compare:rhs] == NSOrderedAscending;
876 struct NSStringMapEqual :
877 std::binary_function<NSString *, NSString *, bool>
879 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
880 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
881 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
882 //[lhs isEqualToString:rhs];
886 /* Perl-Compatible RegEx {{{ */
896 Pcre(const char *regex) :
901 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
904 lprintf("%d:%s\n", offset, error);
908 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
909 matches_ = new int[(capture_ + 1) * 3];
917 NSString *operator [](size_t match) {
918 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
921 bool operator ()(NSString *data) {
922 // XXX: length is for characters, not for bytes
923 return operator ()([data UTF8String], [data length]);
926 bool operator ()(const char *data, size_t size) {
928 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
932 /* Mime Addresses {{{ */
933 @interface Address : NSObject {
939 - (NSString *) address;
941 - (void) setAddress:(NSString *)address;
943 + (Address *) addressWithString:(NSString *)string;
944 - (Address *) initWithString:(NSString *)string;
947 @implementation Address
956 - (NSString *) name {
960 - (NSString *) address {
964 - (void) setAddress:(NSString *)address {
966 [address_ autorelease];
970 address_ = [address retain];
973 + (Address *) addressWithString:(NSString *)string {
974 return [[[Address alloc] initWithString:string] autorelease];
977 + (NSArray *) _attributeKeys {
978 return [NSArray arrayWithObjects:@"address", @"name", nil];
981 - (NSArray *) attributeKeys {
982 return [[self class] _attributeKeys];
985 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
986 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
989 - (Address *) initWithString:(NSString *)string {
990 if ((self = [super init]) != nil) {
991 const char *data = [string UTF8String];
992 size_t size = [string length];
994 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
996 if (address_r(data, size)) {
997 name_ = [address_r[1] retain];
998 address_ = [address_r[2] retain];
1000 name_ = [string retain];
1008 /* CoreGraphics Primitives {{{ */
1019 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
1022 Set(space, red, green, blue, alpha);
1027 CGColorRelease(color_);
1034 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1036 float color[] = {red, green, blue, alpha};
1037 color_ = CGColorCreate(space, color);
1040 operator CGColorRef() {
1046 extern "C" void UISetColor(CGColorRef color);
1048 /* Random Global Variables {{{ */
1049 static const int PulseInterval_ = 50000;
1050 static const int ButtonBarHeight_ = 48;
1051 static const float KeyboardTime_ = 0.3f;
1053 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1054 #define SandboxTemplate_ "/usr/share/sandbox/SandboxTemplate.sb"
1055 #define NotifyConfig_ "/etc/notify.conf"
1057 static bool Queuing_;
1059 static CGColor Blue_;
1060 static CGColor Blueish_;
1061 static CGColor Black_;
1062 static CGColor Off_;
1063 static CGColor White_;
1064 static CGColor Gray_;
1065 static CGColor Green_;
1066 static CGColor Purple_;
1067 static CGColor Purplish_;
1069 static UIColor *InstallingColor_;
1070 static UIColor *RemovingColor_;
1072 static NSString *App_;
1073 static NSString *Home_;
1074 static BOOL Sounds_Keyboard_;
1076 static BOOL Advanced_;
1077 static BOOL Loaded_;
1078 static BOOL Ignored_;
1080 static UIFont *Font12_;
1081 static UIFont *Font12Bold_;
1082 static UIFont *Font14_;
1083 static UIFont *Font18Bold_;
1084 static UIFont *Font22Bold_;
1086 static const char *Machine_ = NULL;
1087 static const NSString *UniqueID_ = nil;
1088 static const NSString *Build_ = nil;
1089 static const NSString *Product_ = nil;
1090 static const NSString *Safari_ = nil;
1092 CFLocaleRef Locale_;
1093 NSArray *Languages_;
1094 CGColorSpaceRef space_;
1099 static NSDictionary *SectionMap_;
1100 static NSMutableDictionary *Metadata_;
1101 static _transient NSMutableDictionary *Settings_;
1102 static _transient NSString *Role_;
1103 static _transient NSMutableDictionary *Packages_;
1104 static _transient NSMutableDictionary *Sections_;
1105 static _transient NSMutableDictionary *Sources_;
1106 static bool Changed_;
1107 static NSDate *now_;
1110 static NSMutableArray *Documents_;
1113 NSString *GetLastUpdate() {
1114 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1117 return CYLocalize("NEVER_OR_UNKNOWN");
1119 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1120 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1122 CFRelease(formatter);
1124 return [(NSString *) formatted autorelease];
1127 /* Display Helpers {{{ */
1128 inline float Interpolate(float begin, float end, float fraction) {
1129 return (end - begin) * fraction + begin;
1132 /* XXX: localize this! */
1133 NSString *SizeString(double size) {
1134 bool negative = size < 0;
1139 while (size > 1024) {
1144 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1146 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1149 static _finline CFStringRef CFCString(const char *value) {
1150 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1153 CFStringRef StripVersion(const char *version) {
1154 const char *colon(strchr(version, ':'));
1156 version = colon + 1;
1157 return CFCString(version);
1160 NSString *LocalizeSection(NSString *section) {
1161 static Pcre title_r("^(.*?) \\((.*)\\)$");
1162 if (title_r(section)) {
1163 NSString *parent(title_r[1]);
1164 NSString *child(title_r[2]);
1166 return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"),
1167 LocalizeSection(parent),
1168 LocalizeSection(child)
1172 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1175 NSString *Simplify(NSString *title) {
1176 const char *data = [title UTF8String];
1177 size_t size = [title length];
1179 static Pcre square_r("^\\[(.*)\\]$");
1180 if (square_r(data, size))
1181 return Simplify(square_r[1]);
1183 static Pcre paren_r("^\\((.*)\\)$");
1184 if (paren_r(data, size))
1185 return Simplify(paren_r[1]);
1187 static Pcre title_r("^(.*?) \\((.*)\\)$");
1188 if (title_r(data, size))
1189 return Simplify(title_r[1]);
1195 bool isSectionVisible(NSString *section) {
1196 NSDictionary *metadata([Sections_ objectForKey:section]);
1197 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1198 return hidden == nil || ![hidden boolValue];
1201 /* Delegate Prototypes {{{ */
1205 @interface NSObject (ProgressDelegate)
1208 @implementation NSObject(ProgressDelegate)
1210 - (void) _setProgressError:(NSArray *)args {
1211 [self performSelector:@selector(setProgressError:forPackage:)
1212 withObject:[args objectAtIndex:0]
1213 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1219 @protocol ProgressDelegate
1220 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1221 - (void) setProgressTitle:(NSString *)title;
1222 - (void) setProgressPercent:(float)percent;
1223 - (void) startProgress;
1224 - (void) addProgressOutput:(NSString *)output;
1225 - (bool) isCancelling:(size_t)received;
1228 @protocol ConfigurationDelegate
1229 - (void) repairWithSelector:(SEL)selector;
1230 - (void) setConfigurationData:(NSString *)data;
1235 @protocol CydiaDelegate
1236 - (void) setPackageView:(PackageView *)view;
1237 - (void) clearPackage:(Package *)package;
1238 - (void) installPackage:(Package *)package;
1239 - (void) removePackage:(Package *)package;
1240 - (void) slideUp:(UIActionSheet *)alert;
1241 - (void) distUpgrade;
1242 - (void) updateData;
1244 - (void) askForSettings;
1245 - (UIProgressHUD *) addProgressHUD;
1246 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1247 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag;
1248 - (RVPage *) pageForPackage:(NSString *)name;
1249 - (void) openMailToURL:(NSURL *)url;
1250 - (void) clearFirstResponder;
1251 - (PackageView *) packageView;
1255 /* Status Delegation {{{ */
1257 public pkgAcquireStatus
1260 _transient NSObject<ProgressDelegate> *delegate_;
1268 void setDelegate(id delegate) {
1269 delegate_ = delegate;
1272 virtual bool MediaChange(std::string media, std::string drive) {
1276 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1279 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1280 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1281 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
1284 virtual void Done(pkgAcquire::ItemDesc &item) {
1287 virtual void Fail(pkgAcquire::ItemDesc &item) {
1289 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1290 item.Owner->Status == pkgAcquire::Item::StatDone
1294 std::string &error(item.Owner->ErrorText);
1298 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1299 NSArray *fields([description componentsSeparatedByString:@" "]);
1300 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1302 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1303 withObject:[NSArray arrayWithObjects:
1304 [NSString stringWithUTF8String:error.c_str()],
1311 virtual bool Pulse(pkgAcquire *Owner) {
1312 bool value = pkgAcquireStatus::Pulse(Owner);
1315 double(CurrentBytes + CurrentItems) /
1316 double(TotalBytes + TotalItems)
1319 [delegate_ setProgressPercent:percent];
1320 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1323 virtual void Start() {
1324 [delegate_ startProgress];
1327 virtual void Stop() {
1331 /* Progress Delegation {{{ */
1336 _transient id<ProgressDelegate> delegate_;
1339 virtual void Update() {
1340 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1341 [delegate_ setProgressPercent:(Percent / 100)];*/
1350 void setDelegate(id delegate) {
1351 delegate_ = delegate;
1354 virtual void Done() {
1355 //[delegate_ setProgressPercent:1];
1360 /* Database Interface {{{ */
1361 typedef std::map< unsigned long, _H<Source> > SourceMap;
1363 @interface Database : NSObject {
1369 pkgCacheFile cache_;
1370 pkgDepCache::Policy *policy_;
1371 pkgRecords *records_;
1372 pkgProblemResolver *resolver_;
1373 pkgAcquire *fetcher_;
1375 SPtr<pkgPackageManager> manager_;
1376 pkgSourceList *list_;
1379 NSMutableArray *packages_;
1381 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1390 + (Database *) sharedInstance;
1393 - (void) _readCydia:(NSNumber *)fd;
1394 - (void) _readStatus:(NSNumber *)fd;
1395 - (void) _readOutput:(NSNumber *)fd;
1399 - (Package *) packageWithName:(NSString *)name;
1401 - (pkgCacheFile &) cache;
1402 - (pkgDepCache::Policy *) policy;
1403 - (pkgRecords *) records;
1404 - (pkgProblemResolver *) resolver;
1405 - (pkgAcquire &) fetcher;
1406 - (pkgSourceList &) list;
1407 - (NSArray *) packages;
1408 - (NSArray *) sources;
1409 - (void) reloadData;
1417 - (NSString *) updateWithStatus:(Status &)status;
1419 - (void) setDelegate:(id)delegate;
1420 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1424 /* Source Class {{{ */
1425 @interface Source : NSObject {
1426 CYString description_;
1432 CYString distribution_;
1438 CYString defaultIcon_;
1440 NSDictionary *record_;
1444 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1446 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1448 - (NSString *) supportForPackage:(NSString *)package;
1450 - (NSDictionary *) record;
1454 - (NSString *) distribution;
1455 - (NSString *) type;
1457 - (NSString *) host;
1459 - (NSString *) name;
1460 - (NSString *) description;
1461 - (NSString *) label;
1462 - (NSString *) origin;
1463 - (NSString *) version;
1465 - (NSString *) defaultIcon;
1469 @implementation Source
1473 distribution_.clear();
1476 description_.clear();
1481 defaultIcon_.clear();
1483 if (record_ != nil) {
1499 + (NSArray *) _attributeKeys {
1500 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1503 - (NSArray *) attributeKeys {
1504 return [[self class] _attributeKeys];
1507 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1508 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1511 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1514 trusted_ = index->IsTrusted();
1516 uri_.set(pool, index->GetURI());
1517 distribution_.set(pool, index->GetDist());
1518 type_.set(pool, index->GetType());
1520 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1521 if (dindex != NULL) {
1523 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1526 pkgTagFile tags(&fd);
1528 pkgTagSection section;
1535 {"default-icon", &defaultIcon_},
1536 {"description", &description_},
1538 {"origin", &origin_},
1539 {"support", &support_},
1540 {"version", &version_},
1543 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1544 const char *start, *end;
1546 if (section.Find(names[i].name_, start, end)) {
1547 CYString &value(*names[i].value_);
1548 value.set(pool, start, end - start);
1554 record_ = [Sources_ objectForKey:[self key]];
1556 record_ = [record_ retain];
1558 host_ = [[[[NSURL URLWithString:uri_] host] lowercaseString] retain];
1561 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1562 if ((self = [super init]) != nil) {
1563 [self setMetaIndex:index inPool:pool];
1567 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1568 NSDictionary *lhr = [self record];
1569 NSDictionary *rhr = [source record];
1572 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1574 NSString *lhs = [self name];
1575 NSString *rhs = [source name];
1577 if ([lhs length] != 0 && [rhs length] != 0) {
1578 unichar lhc = [lhs characterAtIndex:0];
1579 unichar rhc = [rhs characterAtIndex:0];
1581 if (isalpha(lhc) && !isalpha(rhc))
1582 return NSOrderedAscending;
1583 else if (!isalpha(lhc) && isalpha(rhc))
1584 return NSOrderedDescending;
1587 return [lhs compare:rhs options:LaxCompareOptions_];
1590 - (NSString *) supportForPackage:(NSString *)package {
1591 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1594 - (NSDictionary *) record {
1602 - (NSString *) uri {
1606 - (NSString *) distribution {
1607 return distribution_;
1610 - (NSString *) type {
1614 - (NSString *) key {
1615 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1618 - (NSString *) host {
1622 - (NSString *) name {
1623 return origin_.empty() ? host_ : origin_;
1626 - (NSString *) description {
1627 return description_;
1630 - (NSString *) label {
1631 return label_.empty() ? host_ : label_;
1634 - (NSString *) origin {
1638 - (NSString *) version {
1642 - (NSString *) defaultIcon {
1643 return defaultIcon_;
1648 /* Relationship Class {{{ */
1649 @interface Relationship : NSObject {
1654 - (NSString *) type;
1656 - (NSString *) name;
1660 @implementation Relationship
1668 - (NSString *) type {
1676 - (NSString *) name {
1683 /* Package Class {{{ */
1684 @interface Package : NSObject {
1688 pkgCache::VerIterator version_;
1689 pkgCache::PkgIterator iterator_;
1690 _transient Database *database_;
1691 pkgCache::VerFileIterator file_;
1698 NSString *section$_;
1703 NSString *installed_;
1709 CYString depiction_;
1719 NSMutableArray *tags_;
1722 NSArray *relationships_;
1724 NSMutableDictionary *metadata_;
1725 _transient NSDate *firstSeen_;
1726 _transient NSDate *lastSeen_;
1730 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1731 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1733 - (pkgCache::PkgIterator) iterator;
1736 - (NSString *) section;
1737 - (NSString *) simpleSection;
1739 - (NSString *) longSection;
1740 - (NSString *) shortSection;
1744 - (Address *) maintainer;
1746 - (NSString *) longDescription;
1747 - (NSString *) shortDescription;
1750 - (NSMutableDictionary *) metadata;
1752 - (BOOL) subscribed;
1755 - (NSString *) latest;
1756 - (NSString *) installed;
1759 - (BOOL) upgradableAndEssential:(BOOL)essential;
1762 - (BOOL) unfiltered;
1766 - (BOOL) halfConfigured;
1767 - (BOOL) halfInstalled;
1769 - (NSString *) mode;
1772 - (NSString *) name;
1774 - (NSString *) homepage;
1775 - (NSString *) depiction;
1776 - (Address *) author;
1778 - (NSString *) support;
1780 - (NSArray *) files;
1781 - (NSArray *) relationships;
1782 - (NSArray *) warnings;
1783 - (NSArray *) applications;
1785 - (Source *) source;
1786 - (NSString *) role;
1788 - (BOOL) matches:(NSString *)text;
1790 - (bool) hasSupportingRole;
1791 - (BOOL) hasTag:(NSString *)tag;
1792 - (NSString *) primaryPurpose;
1793 - (NSArray *) purposes;
1794 - (bool) isCommercial;
1796 - (CYString &) cyname;
1798 - (uint32_t) compareBySection:(NSArray *)sections;
1800 - (uint32_t) compareForChanges;
1805 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1806 - (bool) isInstalledAndVisible:(NSNumber *)number;
1807 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1808 - (bool) isVisibleInSource:(Source *)source;
1812 uint32_t PackageChangesRadix(Package *self, void *) {
1817 uint32_t timestamp : 30;
1818 uint32_t ignored : 1;
1819 uint32_t upgradable : 1;
1823 bool upgradable([self upgradableAndEssential:YES]);
1824 value.bits.upgradable = upgradable ? 1 : 0;
1827 value.bits.timestamp = 0;
1828 value.bits.ignored = [self ignored] ? 0 : 1;
1829 value.bits.upgradable = 1;
1831 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1832 value.bits.ignored = 0;
1833 value.bits.upgradable = 0;
1836 return _not(uint32_t) - value.key;
1839 _finline static void Stifle(uint8_t &value) {
1842 uint32_t PackagePrefixRadix(Package *self, void *context) {
1843 size_t offset(reinterpret_cast<size_t>(context));
1844 CYString &name([self cyname]);
1846 size_t size(name.size());
1849 char *text(name.data());
1852 if (!isdigit(text[0]))
1856 while (size != digits && isdigit(text[digits]))
1866 if (offset == 0 && zeros != 0) {
1867 memset(data, '0', zeros);
1868 memcpy(data + zeros, text, 4 - zeros);
1870 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1871 if (size <= offset - zeros)
1874 text += offset - zeros;
1875 size -= offset - zeros;
1878 memcpy(data, text, 4);
1880 memcpy(data, text, size);
1881 memset(data + size, 0, 4 - size);
1884 for (size_t i(0); i != 4; ++i)
1885 if (isalpha(data[i]))
1890 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1892 /* XXX: ntohl may be more honest */
1893 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1896 CYString &(*PackageName)(Package *self, SEL sel);
1898 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1899 _profile(PackageNameCompare)
1900 CYString &lhi(PackageName(lhs, @selector(cyname)));
1901 CYString &rhi(PackageName(rhs, @selector(cyname)));
1902 CFStringRef lhn(lhi), rhn(rhi);
1904 _profile(PackageNameCompare$NumbersLast)
1905 if (!lhi.empty() && !rhi.empty()) {
1906 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1907 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1908 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1909 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1910 return lha ? NSOrderedAscending : NSOrderedDescending;
1914 CFIndex length = CFStringGetLength(lhn);
1916 _profile(PackageNameCompare$Compare)
1917 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1922 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1923 return PackageNameCompare(*lhs, *rhs, context);
1926 struct PackageNameOrdering :
1927 std::binary_function<Package *, Package *, bool>
1929 _finline bool operator ()(Package *lhs, Package *rhs) const {
1930 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1934 @implementation Package
1936 - (NSString *) description {
1937 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1943 if (section$_ != nil)
1944 [section$_ release];
1948 if (installed_ != nil)
1949 [installed_ release];
1951 if (sponsor$_ != nil)
1952 [sponsor$_ release];
1953 if (author$_ != nil)
1960 if (relationships_ != nil)
1961 [relationships_ release];
1962 if (metadata_ != nil)
1963 [metadata_ release];
1968 + (NSString *) webScriptNameForSelector:(SEL)selector {
1969 if (selector == @selector(hasTag:))
1975 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1976 return [self webScriptNameForSelector:selector] == nil;
1979 + (NSArray *) _attributeKeys {
1980 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];
1983 - (NSArray *) attributeKeys {
1984 return [[self class] _attributeKeys];
1987 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1988 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1998 _profile(Package$parse)
1999 pkgRecords::Parser *parser;
2001 _profile(Package$parse$Lookup)
2002 parser = &[database_ records]->Lookup(file_);
2007 _profile(Package$parse$Find)
2013 {"depiction", &depiction_},
2014 {"homepage", &homepage_},
2015 {"website", &website},
2016 {"support", &support_},
2017 {"sponsor", &sponsor_},
2018 {"author", &author_},
2021 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2022 const char *start, *end;
2024 if (parser->Find(names[i].name_, start, end)) {
2025 CYString &value(*names[i].value_);
2026 _profile(Package$parse$Value)
2027 value.set(pool_, start, end - start);
2033 _profile(Package$parse$Tagline)
2034 const char *start, *end;
2035 if (parser->ShortDesc(start, end)) {
2036 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2039 while (stop != start && stop[-1] == '\r')
2041 tagline_.set(pool_, start, stop - start);
2045 _profile(Package$parse$Retain)
2046 if (!homepage_.empty())
2047 homepage_ = website;
2048 if (homepage_ == depiction_)
2054 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2055 if ((self = [super init]) != nil) {
2056 _profile(Package$initWithVersion)
2057 @synchronized (database) {
2058 era_ = [database era];
2062 iterator_ = version.ParentPkg();
2063 database_ = database;
2065 _profile(Package$initWithVersion$Latest)
2066 latest_ = (NSString *) StripVersion(version_.VerStr());
2069 pkgCache::VerIterator current;
2070 _profile(Package$initWithVersion$Versions)
2071 current = iterator_.CurrentVer();
2073 installed_ = (NSString *) StripVersion(current.VerStr());
2075 if (!version_.end())
2076 file_ = version_.FileList();
2078 pkgCache &cache([database_ cache]);
2079 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2083 _profile(Package$initWithVersion$Name)
2084 id_.set(pool_, iterator_.Name());
2085 name_.set(pool, iterator_.Display());
2089 _profile(Package$initWithVersion$Source)
2090 source_ = [database_ getSource:file_.File()];
2097 _profile(Package$initWithVersion$Tags)
2098 pkgCache::TagIterator tag(iterator_.TagList());
2100 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2102 const char *name(tag.Name());
2103 [tags_ addObject:(NSString *)CFCString(name)];
2104 if (role_ == nil && strncmp(name, "role::", 6) == 0)
2105 role_ = (NSString *) CFCString(name + 6);
2107 } while (!tag.end());
2111 bool changed(false);
2112 NSString *key([id_ lowercaseString]);
2114 _profile(Package$initWithVersion$Metadata)
2115 metadata_ = [Packages_ objectForKey:key];
2117 if (metadata_ == nil) {
2120 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2121 firstSeen_, @"FirstSeen",
2122 latest_, @"LastVersion",
2127 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2128 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2130 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2131 subscribed_ = [subscribed boolValue];
2133 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2135 if (firstSeen_ == nil) {
2136 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2137 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2141 if (version == nil) {
2142 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2144 } else if (![version isEqualToString:latest_]) {
2145 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2147 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2152 metadata_ = [metadata_ retain];
2155 [Packages_ setObject:metadata_ forKey:key];
2160 _profile(Package$initWithVersion$Section)
2161 section_.set(pool_, iterator_.Section());
2164 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2165 visible_ = [self hasSupportingRole] && [self unfiltered];
2166 } _end } return self;
2169 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2170 pkgCache::VerIterator version;
2172 _profile(Package$packageWithIterator$GetCandidateVer)
2173 version = [database policy]->GetCandidateVer(iterator);
2179 return [[[Package alloc]
2180 initWithVersion:version
2187 - (pkgCache::PkgIterator) iterator {
2191 - (NSString *) section {
2192 if (section$_ == nil) {
2193 if (section_.empty())
2196 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2197 NSString *name(section_);
2200 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2201 if (NSString *rename = [value objectForKey:@"Rename"]) {
2206 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2210 - (NSString *) simpleSection {
2211 if (NSString *section = [self section])
2212 return Simplify(section);
2217 - (NSString *) longSection {
2218 return LocalizeSection([self section]);
2221 - (NSString *) shortSection {
2222 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2225 - (NSString *) uri {
2228 pkgIndexFile *index;
2229 pkgCache::PkgFileIterator file(file_.File());
2230 if (![database_ list].FindIndex(file, index))
2232 return [NSString stringWithUTF8String:iterator_->Path];
2233 //return [NSString stringWithUTF8String:file.Site()];
2234 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2238 - (Address *) maintainer {
2241 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2242 const std::string &maintainer(parser->Maintainer());
2243 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2247 return version_.end() ? 0 : version_->InstalledSize;
2250 - (NSString *) longDescription {
2253 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2254 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2256 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2257 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2258 if ([lines count] < 2)
2261 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2262 for (size_t i(1), e([lines count]); i != e; ++i) {
2263 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2264 [trimmed addObject:trim];
2267 return [trimmed componentsJoinedByString:@"\n"];
2270 - (NSString *) shortDescription {
2275 _profile(Package$index)
2276 CFStringRef name((CFStringRef) [self name]);
2277 if (CFStringGetLength(name) == 0)
2279 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2280 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2282 return toupper(character);
2286 - (NSMutableDictionary *) metadata {
2291 if (subscribed_ && lastSeen_ != nil)
2296 - (BOOL) subscribed {
2301 NSDictionary *metadata([self metadata]);
2302 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2303 return [ignored boolValue];
2308 - (NSString *) latest {
2312 - (NSString *) installed {
2317 return !version_.end();
2320 - (BOOL) upgradableAndEssential:(BOOL)essential {
2321 _profile(Package$upgradableAndEssential)
2322 pkgCache::VerIterator current(iterator_.CurrentVer());
2324 return essential && essential_ && visible_;
2326 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2330 - (BOOL) essential {
2335 return [database_ cache][iterator_].InstBroken();
2338 - (BOOL) unfiltered {
2339 NSString *section([self section]);
2340 return section == nil || isSectionVisible(section);
2348 unsigned char current(iterator_->CurrentState);
2349 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2352 - (BOOL) halfConfigured {
2353 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2356 - (BOOL) halfInstalled {
2357 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2361 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2362 return state.Mode != pkgDepCache::ModeKeep;
2365 - (NSString *) mode {
2366 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2368 switch (state.Mode) {
2369 case pkgDepCache::ModeDelete:
2370 if ((state.iFlags & pkgDepCache::Purge) != 0)
2374 case pkgDepCache::ModeKeep:
2375 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2376 return @"REINSTALL";
2377 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2381 case pkgDepCache::ModeInstall:
2382 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2383 return @"REINSTALL";
2384 else*/ switch (state.Status) {
2386 return @"DOWNGRADE";
2392 return @"NEW_INSTALL";
2405 - (NSString *) name {
2406 return name_.empty() ? id_ : name_;
2409 - (UIImage *) icon {
2410 NSString *section = [self simpleSection];
2414 if ([icon_ hasPrefix:@"file:///"])
2415 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2416 if (icon == nil) if (section != nil)
2417 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2418 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2419 if ([dicon hasPrefix:@"file:///"])
2420 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2422 icon = [UIImage applicationImageNamed:@"unknown.png"];
2426 - (NSString *) homepage {
2430 - (NSString *) depiction {
2434 - (Address *) sponsor {
2435 if (sponsor$_ == nil) {
2436 if (sponsor_.empty())
2438 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2442 - (Address *) author {
2443 if (author$_ == nil) {
2444 if (author_.empty())
2446 author$_ = [[Address addressWithString:author_] retain];
2450 - (NSString *) support {
2451 return !support_.empty() ? support_ : [[self source] supportForPackage:id_];
2454 - (NSArray *) files {
2455 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2456 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2459 fin.open([path UTF8String]);
2464 while (std::getline(fin, line))
2465 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2470 - (NSArray *) relationships {
2471 return relationships_;
2474 - (NSArray *) warnings {
2475 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2476 const char *name(iterator_.Name());
2478 size_t length(strlen(name));
2479 if (length < 2) invalid:
2480 [warnings addObject:CYLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2481 else for (size_t i(0); i != length; ++i)
2483 /* XXX: technically this is not allowed */
2484 (name[i] < 'A' || name[i] > 'Z') &&
2485 (name[i] < 'a' || name[i] > 'z') &&
2486 (name[i] < '0' || name[i] > '9') &&
2487 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2490 if (strcmp(name, "cydia") != 0) {
2492 bool _private = false;
2495 bool repository = [[self section] isEqualToString:@"Repositories"];
2497 if (NSArray *files = [self files])
2498 for (NSString *file in files)
2499 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2501 else if (!_private && [file isEqualToString:@"/private"])
2503 else if (!stash && [file isEqualToString:@"/var/stash"])
2506 /* XXX: this is not sensitive enough. only some folders are valid. */
2507 if (cydia && !repository)
2508 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2510 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/private"]];
2512 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2515 return [warnings count] == 0 ? nil : warnings;
2518 - (NSArray *) applications {
2519 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2521 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2523 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2524 if (NSArray *files = [self files])
2525 for (NSString *file in files)
2526 if (application_r(file)) {
2527 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2528 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2529 if ([id isEqualToString:me])
2532 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2534 display = application_r[1];
2536 NSString *bundle([file stringByDeletingLastPathComponent]);
2537 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2538 if (icon == nil || [icon length] == 0)
2540 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2542 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2543 [applications addObject:application];
2545 [application addObject:id];
2546 [application addObject:display];
2547 [application addObject:url];
2550 return [applications count] == 0 ? nil : applications;
2553 - (Source *) source {
2555 @synchronized (database_) {
2556 if ([database_ era] != era_ || file_.end())
2559 source_ = [database_ getSource:file_.File()];
2571 - (NSString *) role {
2575 - (BOOL) matches:(NSString *)text {
2581 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2582 if (range.location != NSNotFound)
2585 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2586 if (range.location != NSNotFound)
2589 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2590 if (range.location != NSNotFound)
2596 - (bool) hasSupportingRole {
2599 if ([role_ isEqualToString:@"enduser"])
2601 if ([Role_ isEqualToString:@"User"])
2603 if ([role_ isEqualToString:@"hacker"])
2605 if ([Role_ isEqualToString:@"Hacker"])
2607 if ([role_ isEqualToString:@"developer"])
2609 if ([Role_ isEqualToString:@"Developer"])
2614 - (BOOL) hasTag:(NSString *)tag {
2615 return tags_ == nil ? NO : [tags_ containsObject:tag];
2618 - (NSString *) primaryPurpose {
2619 for (NSString *tag in tags_)
2620 if ([tag hasPrefix:@"purpose::"])
2621 return [tag substringFromIndex:9];
2625 - (NSArray *) purposes {
2626 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2627 for (NSString *tag in tags_)
2628 if ([tag hasPrefix:@"purpose::"])
2629 [purposes addObject:[tag substringFromIndex:9]];
2630 return [purposes count] == 0 ? nil : purposes;
2633 - (bool) isCommercial {
2634 return [self hasTag:@"cydia::commercial"];
2637 - (CYString &) cyname {
2638 return name_.empty() ? id_ : name_;
2641 - (uint32_t) compareBySection:(NSArray *)sections {
2642 NSString *section([self section]);
2643 for (size_t i(0), e([sections count]); i != e; ++i) {
2644 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2648 return _not(uint32_t);
2651 - (uint32_t) compareForChanges {
2656 uint32_t timestamp : 30;
2657 uint32_t ignored : 1;
2658 uint32_t upgradable : 1;
2662 bool upgradable([self upgradableAndEssential:YES]);
2663 value.bits.upgradable = upgradable ? 1 : 0;
2666 value.bits.timestamp = 0;
2667 value.bits.ignored = [self ignored] ? 0 : 1;
2668 value.bits.upgradable = 1;
2670 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2671 value.bits.ignored = 0;
2672 value.bits.upgradable = 0;
2675 return _not(uint32_t) - value.key;
2679 pkgProblemResolver *resolver = [database_ resolver];
2680 resolver->Clear(iterator_);
2681 resolver->Protect(iterator_);
2685 pkgProblemResolver *resolver = [database_ resolver];
2686 resolver->Clear(iterator_);
2687 resolver->Protect(iterator_);
2688 pkgCacheFile &cache([database_ cache]);
2689 cache->MarkInstall(iterator_, false);
2690 pkgDepCache::StateCache &state((*cache)[iterator_]);
2691 if (!state.Install())
2692 cache->SetReInstall(iterator_, true);
2696 pkgProblemResolver *resolver = [database_ resolver];
2697 resolver->Clear(iterator_);
2698 resolver->Protect(iterator_);
2699 resolver->Remove(iterator_);
2700 [database_ cache]->MarkDelete(iterator_, true);
2703 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2704 _profile(Package$isUnfilteredAndSearchedForBy)
2707 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2708 value &= [self unfiltered];
2711 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2712 value &= [self matches:search];
2719 - (bool) isInstalledAndVisible:(NSNumber *)number {
2720 return (![number boolValue] || [self visible]) && [self installed] != nil;
2723 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2724 NSString *section = [self section];
2728 [self installed] == nil && (
2730 section == nil && [name length] == 0 ||
2731 [name isEqualToString:section]
2735 - (bool) isVisibleInSource:(Source *)source {
2736 return [self source] == source && [self visible];
2741 /* Section Class {{{ */
2742 @interface Section : NSObject {
2747 NSString *localized_;
2750 - (NSComparisonResult) compareByLocalized:(Section *)section;
2751 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2752 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2753 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2754 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2755 - (NSString *) name;
2762 - (void) addToCount;
2764 - (void) setCount:(size_t)count;
2765 - (NSString *) localized;
2769 @implementation Section
2773 if (localized_ != nil)
2774 [localized_ release];
2778 - (NSComparisonResult) compareByLocalized:(Section *)section {
2779 NSString *lhs(localized_);
2780 NSString *rhs([section localized]);
2782 /*if ([lhs length] != 0 && [rhs length] != 0) {
2783 unichar lhc = [lhs characterAtIndex:0];
2784 unichar rhc = [rhs characterAtIndex:0];
2786 if (isalpha(lhc) && !isalpha(rhc))
2787 return NSOrderedAscending;
2788 else if (!isalpha(lhc) && isalpha(rhc))
2789 return NSOrderedDescending;
2792 return [lhs compare:rhs options:LaxCompareOptions_];
2795 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2796 if ((self = [self initWithName:name localize:NO]) != nil) {
2797 if (localized != nil)
2798 localized_ = [localized retain];
2802 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2803 return [self initWithName:name row:0 localize:localize];
2806 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2807 if ((self = [super init]) != nil) {
2808 name_ = [name retain];
2812 localized_ = [LocalizeSection(name_) retain];
2816 /* XXX: localize the index thingees */
2817 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2818 if ((self = [super init]) != nil) {
2819 name_ = [(index == '#' ? @"123" : [NSString stringWithCharacters:&index length:1]) retain];
2825 - (NSString *) name {
2845 - (void) addToCount {
2849 - (void) setCount:(size_t)count {
2853 - (NSString *) localized {
2861 static NSArray *Finishes_;
2863 /* Database Implementation {{{ */
2864 @implementation Database
2866 + (Database *) sharedInstance {
2867 static Database *instance;
2868 if (instance == nil)
2869 instance = [[Database alloc] init];
2879 NSRecycleZone(zone_);
2880 // XXX: malloc_destroy_zone(zone_);
2881 apr_pool_destroy(pool_);
2885 - (void) _readCydia:(NSNumber *)fd { _pooled
2886 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2887 std::istream is(&ib);
2890 static Pcre finish_r("^finish:([^:]*)$");
2892 while (std::getline(is, line)) {
2893 const char *data(line.c_str());
2894 size_t size = line.size();
2895 lprintf("C:%s\n", data);
2897 if (finish_r(data, size)) {
2898 NSString *finish = finish_r[1];
2899 int index = [Finishes_ indexOfObject:finish];
2900 if (index != INT_MAX && index > Finish_)
2908 - (void) _readStatus:(NSNumber *)fd { _pooled
2909 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2910 std::istream is(&ib);
2913 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2914 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2916 while (std::getline(is, line)) {
2917 const char *data(line.c_str());
2918 size_t size = line.size();
2919 lprintf("S:%s\n", data);
2921 if (conffile_r(data, size)) {
2922 [delegate_ setConfigurationData:conffile_r[1]];
2923 } else if (strncmp(data, "status: ", 8) == 0) {
2924 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2925 [delegate_ setProgressTitle:string];
2926 } else if (pmstatus_r(data, size)) {
2927 std::string type([pmstatus_r[1] UTF8String]);
2928 NSString *id = pmstatus_r[2];
2930 float percent([pmstatus_r[3] floatValue]);
2931 [delegate_ setProgressPercent:(percent / 100)];
2933 NSString *string = pmstatus_r[4];
2935 if (type == "pmerror")
2936 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2937 withObject:[NSArray arrayWithObjects:string, id, nil]
2940 else if (type == "pmstatus") {
2941 [delegate_ setProgressTitle:string];
2942 } else if (type == "pmconffile")
2943 [delegate_ setConfigurationData:string];
2944 else _assert(false);
2945 } else _assert(false);
2951 - (void) _readOutput:(NSNumber *)fd { _pooled
2952 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2953 std::istream is(&ib);
2956 while (std::getline(is, line)) {
2957 lprintf("O:%s\n", line.c_str());
2958 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2968 - (Package *) packageWithName:(NSString *)name {
2969 if (static_cast<pkgDepCache *>(cache_) == NULL)
2971 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
2972 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
2975 - (Database *) init {
2976 if ((self = [super init]) != nil) {
2983 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
2984 apr_pool_create(&pool_, NULL);
2986 packages_ = [[NSMutableArray alloc] init];
2990 _assert(pipe(fds) != -1);
2993 _config->Set("APT::Keep-Fds::", cydiafd_);
2994 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
2997 detachNewThreadSelector:@selector(_readCydia:)
2999 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3002 _assert(pipe(fds) != -1);
3006 detachNewThreadSelector:@selector(_readStatus:)
3008 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3011 _assert(pipe(fds) != -1);
3012 _assert(dup2(fds[0], 0) != -1);
3013 _assert(close(fds[0]) != -1);
3015 input_ = fdopen(fds[1], "a");
3017 _assert(pipe(fds) != -1);
3018 _assert(dup2(fds[1], 1) != -1);
3019 _assert(close(fds[1]) != -1);
3022 detachNewThreadSelector:@selector(_readOutput:)
3024 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3029 - (pkgCacheFile &) cache {
3033 - (pkgDepCache::Policy *) policy {
3037 - (pkgRecords *) records {
3041 - (pkgProblemResolver *) resolver {
3045 - (pkgAcquire &) fetcher {
3049 - (pkgSourceList &) list {
3053 - (NSArray *) packages {
3057 - (NSArray *) sources {
3058 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3059 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3060 [sources addObject:i->second];
3064 - (NSArray *) issues {
3065 if (cache_->BrokenCount() == 0)
3068 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3070 for (Package *package in packages_) {
3071 if (![package broken])
3073 pkgCache::PkgIterator pkg([package iterator]);
3075 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3076 [entry addObject:[package name]];
3077 [issues addObject:entry];
3079 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3083 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3084 pkgCache::DepIterator start;
3085 pkgCache::DepIterator end;
3086 dep.GlobOr(start, end); // ++dep
3088 if (!cache_->IsImportantDep(end))
3090 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3093 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3094 [entry addObject:failure];
3095 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3097 Package *package([self packageWithName:[NSString stringWithUTF8String:start.TargetPkg().Name()]]);
3098 [failure addObject:[package name]];
3100 pkgCache::PkgIterator target(start.TargetPkg());
3101 if (target->ProvidesList != 0)
3102 [failure addObject:@"?"];
3104 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3106 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3107 else if (!cache_[target].CandidateVerIter(cache_).end())
3108 [failure addObject:@"-"];
3109 else if (target->ProvidesList == 0)
3110 [failure addObject:@"!"];
3112 [failure addObject:@"%"];
3116 if (start.TargetVer() != 0)
3117 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3128 - (void) reloadData { _pooled
3129 @synchronized (self) {
3133 [packages_ removeAllObjects];
3159 apr_pool_clear(pool_);
3160 NSRecycleZone(zone_);
3162 int chk(creat("/tmp/cydia.chk", 0644));
3167 if (!cache_.Open(progress_, true)) {
3169 if (!_error->PopMessage(error))
3172 lprintf("cache_.Open():[%s]\n", error.c_str());
3174 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3175 [delegate_ repairWithSelector:@selector(configure)];
3176 else if (error == "The package lists or status file could not be parsed or opened.")
3177 [delegate_ repairWithSelector:@selector(update)];
3178 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3179 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3180 // else if (error == "The list of sources could not be read.")
3181 else _assert(false);
3187 unlink("/tmp/cydia.chk");
3189 now_ = [[NSDate date] retain];
3191 policy_ = new pkgDepCache::Policy();
3192 records_ = new pkgRecords(cache_);
3193 resolver_ = new pkgProblemResolver(cache_);
3194 fetcher_ = new pkgAcquire(&status_);
3197 list_ = new pkgSourceList();
3198 _assert(list_->ReadMainList());
3200 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3201 _assert(pkgApplyStatus(cache_));
3203 if (cache_->BrokenCount() != 0) {
3204 _assert(pkgFixBroken(cache_));
3205 _assert(cache_->BrokenCount() == 0);
3206 _assert(pkgMinimizeUpgrade(cache_));
3211 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3212 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3213 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3214 // XXX: this could be more intelligent
3215 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3216 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3218 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3225 /*std::vector<Package *> packages;
3226 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3227 [packages_ release];
3232 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3233 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3234 //packages.push_back(package);
3235 [packages_ addObject:package];
3239 /*if (packages.empty())
3240 packages_ = [[NSArray alloc] init];
3242 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3245 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3246 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3247 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3255 /*if (!packages.empty())
3256 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3257 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3259 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3261 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3263 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3269 - (void) configure {
3270 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3271 system([dpkg UTF8String]);
3279 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3280 _assert(!_error->PendingError());
3283 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3286 public pkgArchiveCleaner
3289 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3294 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3296 while (_error->PopMessage(error))
3297 lprintf("ArchiveCleaner: %s\n", error.c_str());
3302 pkgRecords records(cache_);
3304 lock_ = new FileFd();
3305 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3306 _assert(!_error->PendingError());
3309 // XXX: explain this with an error message
3310 _assert(list.ReadMainList());
3312 manager_ = (_system->CreatePM(cache_));
3313 _assert(manager_->GetArchives(fetcher_, &list, &records));
3314 _assert(!_error->PendingError());
3318 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3320 _assert(list.ReadMainList());
3321 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3322 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3325 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3330 bool failed = false;
3331 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3332 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3335 std::string uri = (*item)->DescURI();
3336 std::string error = (*item)->ErrorText;
3338 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3341 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3342 withObject:[NSArray arrayWithObjects:
3343 [NSString stringWithUTF8String:error.c_str()],
3355 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3357 if (_error->PendingError()) {
3362 if (result == pkgPackageManager::Failed) {
3367 if (result != pkgPackageManager::Completed) {
3372 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3374 _assert(list.ReadMainList());
3375 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3376 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3379 if (![before isEqualToArray:after])
3384 _assert(pkgDistUpgrade(cache_));
3388 [self updateWithStatus:status_];
3391 - (NSString *) updateWithStatus:(Status &)status {
3393 _assert(list.ReadMainList());
3396 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3398 if (_error->PendingError()) {
3400 if (!_error->PopMessage(error))
3403 return [NSString stringWithUTF8String:error.c_str()];
3406 pkgAcquire fetcher(&status);
3407 _assert(list.GetIndexes(&fetcher));
3409 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3410 bool failed = false;
3411 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3412 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3413 (*item)->Finished();
3417 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3418 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3419 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3422 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3429 - (void) setDelegate:(id)delegate {
3430 delegate_ = delegate;
3431 status_.setDelegate(delegate);
3432 progress_.setDelegate(delegate);
3435 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3436 SourceMap::const_iterator i(sources_.find(file->ID));
3437 return i == sources_.end() ? nil : i->second;
3443 /* PopUp Windows {{{ */
3444 @interface PopUpView : UIView {
3445 _transient id delegate_;
3446 UITransitionView *transition_;
3451 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3455 @implementation PopUpView
3458 [transition_ setDelegate:nil];
3459 [transition_ release];
3465 [transition_ transition:UITransitionPushFromTop toView:nil];
3468 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3469 if (from != nil && to == nil)
3470 [self removeFromSuperview];
3473 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3474 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3475 delegate_ = delegate;
3477 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3478 [self addSubview:transition_];
3480 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3482 [view addSubview:self];
3484 [transition_ setDelegate:self];
3486 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3487 [transition_ transition:UITransitionNone toView:blank];
3488 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3496 /* Mail Composition {{{ */
3497 @interface MailToView : PopUpView {
3498 MailComposeController *controller_;
3501 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
3505 @implementation MailToView
3508 [controller_ release];
3512 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
3516 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
3517 NSLog(@"did:%@", delivery);
3518 // [UIApp setStatusBarShowsProgress:NO];
3519 if ([controller error]){
3520 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3521 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3522 [mailAlertSheet setBodyText:[controller error]];
3523 [mailAlertSheet popupAlertAnimated:YES];
3527 - (void) showError {
3528 NSLog(@"%@", [controller_ error]);
3529 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3530 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3531 [mailAlertSheet setBodyText:[controller_ error]];
3532 [mailAlertSheet popupAlertAnimated:YES];
3535 - (void) deliverMessage { _pooled
3539 if (![controller_ deliverMessage])
3540 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
3543 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
3544 if ([controller_ needsDelivery])
3545 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
3550 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
3551 if ((self = [super initWithView:view delegate:delegate]) != nil) {
3552 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
3553 [controller_ setDelegate:self];
3554 [controller_ initializeUI];
3555 [controller_ setupForURL:url];
3557 UIView *view([controller_ view]);
3558 [overlay_ addSubview:view];
3566 /* Confirmation View {{{ */
3567 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3568 if (!iterator.end())
3569 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3570 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3572 pkgCache::PkgIterator package(dep.TargetPkg());
3575 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3582 @protocol ConfirmationViewDelegate
3588 @interface ConfirmationView : BrowserView {
3589 _transient Database *database_;
3590 UIActionSheet *essential_;
3597 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3601 @implementation ConfirmationView
3608 if (essential_ != nil)
3609 [essential_ release];
3615 [book_ popFromSuperviewAnimated:YES];
3618 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3619 NSString *context([sheet context]);
3621 if ([context isEqualToString:@"remove"]) {
3629 [delegate_ confirm];
3636 } else if ([context isEqualToString:@"unable"]) {
3640 [super alertSheet:sheet buttonClicked:button];
3643 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3644 [super webView:sender didClearWindowObject:window forFrame:frame];
3645 [window setValue:changes_ forKey:@"changes"];
3646 [window setValue:issues_ forKey:@"issues"];
3647 [window setValue:sizes_ forKey:@"sizes"];
3650 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3651 if ((self = [super initWithBook:book]) != nil) {
3652 database_ = database;
3654 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3655 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3656 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3657 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3658 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3662 pkgDepCache::Policy *policy([database_ policy]);
3664 pkgCacheFile &cache([database_ cache]);
3665 NSArray *packages = [database_ packages];
3666 for (Package *package in packages) {
3667 pkgCache::PkgIterator iterator = [package iterator];
3668 pkgDepCache::StateCache &state(cache[iterator]);
3670 NSString *name([package name]);
3672 if (state.NewInstall())
3673 [installing addObject:name];
3674 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3675 [reinstalling addObject:name];
3676 else if (state.Upgrade())
3677 [upgrading addObject:name];
3678 else if (state.Downgrade())
3679 [downgrading addObject:name];
3680 else if (state.Delete()) {
3681 if ([package essential])
3683 [removing addObject:name];
3686 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3687 substrate_ |= DepSubstrate(iterator.CurrentVer());
3692 else if (Advanced_ || true) {
3693 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
3695 essential_ = [[UIActionSheet alloc]
3696 initWithTitle:CYLocalize("REMOVING_ESSENTIALS")
3697 buttons:[NSArray arrayWithObjects:
3698 [NSString stringWithFormat:parenthetical, CYLocalize("CANCEL_OPERATION"), CYLocalize("SAFE")],
3699 [NSString stringWithFormat:parenthetical, CYLocalize("FORCE_REMOVAL"), CYLocalize("UNSAFE")],
3701 defaultButtonIndex:0
3707 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3709 [essential_ setBodyText:CYLocalize("REMOVING_ESSENTIALS_EX")];
3711 essential_ = [[UIActionSheet alloc]
3712 initWithTitle:CYLocalize("UNABLE_TO_COMPLY")
3713 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3714 defaultButtonIndex:0
3719 [essential_ setBodyText:CYLocalize("UNABLE_TO_COMPLY_EX")];
3722 changes_ = [[NSArray alloc] initWithObjects:
3730 issues_ = [database_ issues];
3732 issues_ = [issues_ retain];
3734 sizes_ = [[NSArray alloc] initWithObjects:
3735 SizeString([database_ fetcher].FetchNeeded()),
3736 SizeString([database_ fetcher].PartialPresent()),
3737 SizeString([database_ cache]->UsrSize()),
3740 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3744 - (NSString *) backButtonTitle {
3745 return CYLocalize("CONFIRM");
3748 - (NSString *) leftButtonTitle {
3749 return [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("CANCEL"), CYLocalize("QUEUE")];
3752 - (id) rightButtonTitle {
3753 return issues_ != nil ? nil : [super rightButtonTitle];
3756 - (id) _rightButtonTitle {
3757 #if AlwaysReload || IgnoreInstall
3758 return [super _rightButtonTitle];
3760 return CYLocalize("CONFIRM");
3764 - (void) _leftButtonClicked {
3769 - (void) _rightButtonClicked {
3771 return [super _rightButtonClicked];
3773 if (essential_ != nil)
3774 [essential_ popupAlertAnimated:YES];
3778 [delegate_ confirm];
3786 /* Progress Data {{{ */
3787 @interface ProgressData : NSObject {
3793 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3800 @implementation ProgressData
3802 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3803 if ((self = [super init]) != nil) {
3804 selector_ = selector;
3824 /* Progress View {{{ */
3825 @interface ProgressView : UIView <
3826 ConfigurationDelegate,
3829 _transient Database *database_;
3831 UIView *background_;
3832 UITransitionView *transition_;
3834 UINavigationBar *navbar_;
3835 UIProgressBar *progress_;
3836 UITextView *output_;
3837 UITextLabel *status_;
3838 UIPushButton *close_;
3841 SHA1SumValue springlist_;
3842 SHA1SumValue notifyconf_;
3843 SHA1SumValue sandplate_;
3846 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
3848 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
3849 - (void) setContentView:(UIView *)view;
3852 - (void) _retachThread;
3853 - (void) _detachNewThreadData:(ProgressData *)data;
3854 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
3860 @protocol ProgressViewDelegate
3861 - (void) progressViewIsComplete:(ProgressView *)sender;
3864 @implementation ProgressView
3867 [transition_ setDelegate:nil];
3868 [navbar_ setDelegate:nil];
3871 if (background_ != nil)
3872 [background_ release];
3873 [transition_ release];
3876 [progress_ release];
3883 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3884 if (bootstrap_ && from == overlay_ && to == view_)
3888 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
3889 if ((self = [super initWithFrame:frame]) != nil) {
3890 database_ = database;
3891 delegate_ = delegate;
3893 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3894 [transition_ setDelegate:self];
3896 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3899 [overlay_ setBackgroundColor:[UIColor blackColor]];
3901 background_ = [[UIView alloc] initWithFrame:[self bounds]];
3902 [background_ setBackgroundColor:[UIColor blackColor]];
3903 [self addSubview:background_];
3906 [self addSubview:transition_];
3908 CGSize navsize = [UINavigationBar defaultSize];
3909 CGRect navrect = {{0, 0}, navsize};
3911 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
3912 [overlay_ addSubview:navbar_];
3914 [navbar_ setBarStyle:1];
3915 [navbar_ setDelegate:self];
3917 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
3918 [navbar_ pushNavigationItem:navitem];
3920 CGRect bounds = [overlay_ bounds];
3921 CGSize prgsize = [UIProgressBar defaultSize];
3924 (bounds.size.width - prgsize.width) / 2,
3925 bounds.size.height - prgsize.height - 20
3928 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3929 [progress_ setStyle:0];
3931 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3933 bounds.size.height - prgsize.height - 50,
3934 bounds.size.width - 20,
3938 [status_ setColor:[UIColor whiteColor]];
3939 [status_ setBackgroundColor:[UIColor clearColor]];
3941 [status_ setCentersHorizontally:YES];
3942 //[status_ setFont:font];
3945 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3947 navrect.size.height + 20,
3948 bounds.size.width - 20,
3949 bounds.size.height - navsize.height - 62 - navrect.size.height
3953 //[output_ setTextFont:@"Courier New"];
3954 [output_ setTextSize:12];
3956 [output_ setTextColor:[UIColor whiteColor]];
3957 [output_ setBackgroundColor:[UIColor clearColor]];
3959 [output_ setMarginTop:0];
3960 [output_ setAllowsRubberBanding:YES];
3961 [output_ setEditable:NO];
3963 [overlay_ addSubview:output_];
3965 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3967 bounds.size.height - prgsize.height - 50,
3968 bounds.size.width - 20,
3972 [close_ setAutosizesToFit:NO];
3973 [close_ setDrawsShadow:YES];
3974 [close_ setStretchBackground:YES];
3975 [close_ setEnabled:YES];
3977 UIFont *bold = [UIFont boldSystemFontOfSize:22];
3978 [close_ setTitleFont:bold];
3980 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
3981 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
3982 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
3986 - (void) setContentView:(UIView *)view {
3987 view_ = [view retain];
3990 - (void) resetView {
3991 [transition_ transition:6 toView:view_];
3994 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3995 NSString *context([sheet context]);
3997 if ([context isEqualToString:@"error"])
3999 else if ([context isEqualToString:@"conffile"]) {
4000 FILE *input = [database_ input];
4004 fprintf(input, "N\n");
4008 fprintf(input, "Y\n");
4019 - (void) closeButtonPushed {
4028 [delegate_ suspendWithAnimation:YES];
4032 system("launchctl stop com.apple.SpringBoard");
4036 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4045 - (void) _retachThread {
4046 UINavigationItem *item = [navbar_ topItem];
4047 [item setTitle:CYLocalize("COMPLETE")];
4049 [overlay_ addSubview:close_];
4050 [progress_ removeFromSuperview];
4051 [status_ removeFromSuperview];
4053 [delegate_ progressViewIsComplete:self];
4056 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4057 MMap mmap(file, MMap::ReadOnly);
4059 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4060 if (!(sandplate_ == sha1.Result()))
4065 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4066 MMap mmap(file, MMap::ReadOnly);
4068 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4069 if (!(notifyconf_ == sha1.Result()))
4074 FileFd file(SpringBoard_, FileFd::ReadOnly);
4075 MMap mmap(file, MMap::ReadOnly);
4077 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4078 if (!(springlist_ == sha1.Result()))
4083 case 0: [close_ setTitle:CYLocalize("RETURN_TO_CYDIA")]; break;
4084 case 1: [close_ setTitle:CYLocalize("CLOSE_CYDIA")]; break;
4085 case 2: [close_ setTitle:CYLocalize("RESTART_SPRINGBOARD")]; break;
4086 case 3: [close_ setTitle:CYLocalize("RELOAD_SPRINGBOARD")]; break;
4087 case 4: [close_ setTitle:CYLocalize("REBOOT_DEVICE")]; break;
4090 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4092 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
4093 [cache autorelease];
4095 NSFileManager *manager = [NSFileManager defaultManager];
4096 NSError *error = nil;
4098 id system = [cache objectForKey:@"System"];
4103 if (stat(Cache_, &info) == -1)
4106 [system removeAllObjects];
4108 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4109 for (NSString *app in apps)
4110 if ([app hasSuffix:@".app"]) {
4111 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4112 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4113 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4115 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4116 [info setObject:path forKey:@"Path"];
4117 [info setObject:@"System" forKey:@"ApplicationType"];
4118 [system addInfoDictionary:info];
4124 [cache writeToFile:@Cache_ atomically:YES];
4126 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
4128 if (chmod(Cache_, info.st_mode) == -1)
4132 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4135 notify_post("com.apple.mobile.application_installed");
4137 [delegate_ setStatusBarShowsProgress:NO];
4140 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4141 [[data target] performSelector:[data selector] withObject:[data object]];
4144 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4147 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4148 UINavigationItem *item = [navbar_ topItem];
4149 [item setTitle:title];
4151 [status_ setText:nil];
4152 [output_ setText:@""];
4153 [progress_ setProgress:0];
4155 [close_ removeFromSuperview];
4156 [overlay_ addSubview:progress_];
4157 [overlay_ addSubview:status_];
4159 [delegate_ setStatusBarShowsProgress:YES];
4163 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4164 MMap mmap(file, MMap::ReadOnly);
4166 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4167 sandplate_ = sha1.Result();
4171 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4172 MMap mmap(file, MMap::ReadOnly);
4174 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4175 notifyconf_ = sha1.Result();
4179 FileFd file(SpringBoard_, FileFd::ReadOnly);
4180 MMap mmap(file, MMap::ReadOnly);
4182 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4183 springlist_ = sha1.Result();
4186 [transition_ transition:6 toView:overlay_];
4189 detachNewThreadSelector:@selector(_detachNewThreadData:)
4191 withObject:[[ProgressData alloc]
4192 initWithSelector:selector
4199 - (void) repairWithSelector:(SEL)selector {
4201 detachNewThreadSelector:selector
4204 title:CYLocalize("REPAIRING")
4208 - (void) setConfigurationData:(NSString *)data {
4210 performSelectorOnMainThread:@selector(_setConfigurationData:)
4216 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4217 Package *package = id == nil ? nil : [database_ packageWithName:id];
4219 UIActionSheet *sheet = [[[UIActionSheet alloc]
4220 initWithTitle:(package == nil ? id : [package name])
4221 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
4222 defaultButtonIndex:0
4227 [sheet setBodyText:error];
4228 [sheet popupAlertAnimated:YES];
4231 - (void) setProgressTitle:(NSString *)title {
4233 performSelectorOnMainThread:@selector(_setProgressTitle:)
4239 - (void) setProgressPercent:(float)percent {
4241 performSelectorOnMainThread:@selector(_setProgressPercent:)
4242 withObject:[NSNumber numberWithFloat:percent]
4247 - (void) startProgress {
4250 - (void) addProgressOutput:(NSString *)output {
4252 performSelectorOnMainThread:@selector(_addProgressOutput:)
4258 - (bool) isCancelling:(size_t)received {
4262 - (void) _setConfigurationData:(NSString *)data {
4263 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4265 _assert(conffile_r(data));
4267 NSString *ofile = conffile_r[1];
4268 //NSString *nfile = conffile_r[2];
4270 UIActionSheet *sheet = [[[UIActionSheet alloc]
4271 initWithTitle:CYLocalize("CONFIGURATION_UPGRADE")
4272 buttons:[NSArray arrayWithObjects:
4273 CYLocalize("KEEP_OLD_COPY"),
4274 CYLocalize("ACCEPT_NEW_COPY"),
4275 // XXX: CYLocalize("SEE_WHAT_CHANGED"),
4277 defaultButtonIndex:0
4282 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", CYLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4283 [sheet popupAlertAnimated:YES];
4286 - (void) _setProgressTitle:(NSString *)title {
4287 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4288 for (size_t i(0), e([words count]); i != e; ++i) {
4289 NSString *word([words objectAtIndex:i]);
4290 if (Package *package = [database_ packageWithName:word])
4291 [words replaceObjectAtIndex:i withObject:[package name]];
4294 [status_ setText:[words componentsJoinedByString:@" "]];
4297 - (void) _setProgressPercent:(NSNumber *)percent {
4298 [progress_ setProgress:[percent floatValue]];
4301 - (void) _addProgressOutput:(NSString *)output {
4302 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4303 CGSize size = [output_ contentSize];
4304 CGRect rect = {{0, size.height}, {size.width, 0}};
4305 [output_ scrollRectToVisible:rect animated:YES];
4308 - (BOOL) isRunning {
4315 /* Package Cell {{{ */
4316 @interface PackageCell : UITableCell {
4319 NSString *description_;
4326 UITextLabel *status_;
4330 - (PackageCell *) init;
4331 - (void) setPackage:(Package *)package;
4333 + (int) heightForPackage:(Package *)package;
4337 @implementation PackageCell
4339 - (void) clearPackage {
4350 if (description_ != nil) {
4351 [description_ release];
4355 if (source_ != nil) {
4360 if (badge_ != nil) {
4370 [self clearPackage];
4377 - (PackageCell *) init {
4378 if ((self = [super init]) != nil) {
4380 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4381 [status_ setBackgroundColor:[UIColor clearColor]];
4382 [status_ setFont:small];
4387 - (void) setPackage:(Package *)package {
4388 [self clearPackage];
4391 Source *source = [package source];
4393 icon_ = [[package icon] retain];
4394 name_ = [[package name] retain];
4395 description_ = [[package shortDescription] retain];
4396 commercial_ = [package isCommercial];
4398 package_ = [package retain];
4400 NSString *label = nil;
4401 bool trusted = false;
4403 if (source != nil) {
4404 label = [source label];
4405 trusted = [source trusted];
4406 } else if ([[package id] isEqualToString:@"firmware"])
4407 label = CYLocalize("APPLE");
4409 label = [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("UNKNOWN"), CYLocalize("LOCAL")];
4411 NSString *from(label);
4413 NSString *section = [package simpleSection];
4414 if (section != nil && ![section isEqualToString:label]) {
4415 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4416 from = [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), from, section];
4419 from = [NSString stringWithFormat:CYLocalize("FROM"), from];
4420 source_ = [from retain];
4422 if (NSString *purpose = [package primaryPurpose])
4423 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4424 badge_ = [badge_ retain];
4427 if (NSString *mode = [package mode]) {
4428 [badge_ setImage:[UIImage applicationImageNamed:
4429 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4432 [status_ setText:[NSString stringWithFormat:CYLocalize("QUEUED_FOR"), CYLocalize(mode)]];
4433 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4434 } else if ([package half]) {
4435 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4436 [status_ setText:CYLocalize("PACKAGE_DAMAGED")];
4437 [status_ setColor:[UIColor redColor]];
4439 [badge_ setImage:nil];
4440 [status_ setText:nil];
4447 - (void) drawRect:(CGRect)rect {
4451 if (NSString *mode = [package_ mode]) {
4452 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4453 color = remove ? RemovingColor_ : InstallingColor_;
4455 color = [UIColor whiteColor];
4457 [self setBackgroundColor:color];
4461 [super drawRect:rect];
4464 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4466 CGContextRef context(UIGraphicsGetCurrentContext());
4467 [[self backgroundColor] set];
4469 back.size.height -= 1;
4470 CGContextFillRect(context, back);
4473 [super drawBackgroundInRect:rect withFade:fade];
4476 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4479 rect.size = [icon_ size];
4481 rect.size.width /= 2;
4482 rect.size.height /= 2;
4484 rect.origin.x = 25 - rect.size.width / 2;
4485 rect.origin.y = 25 - rect.size.height / 2;
4487 [icon_ drawInRect:rect];
4490 if (badge_ != nil) {
4491 CGSize size = [badge_ size];
4493 [badge_ drawAtPoint:CGPointMake(
4494 36 - size.width / 2,
4495 36 - size.height / 2
4503 UISetColor(commercial_ ? Purple_ : Black_);
4504 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4505 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4508 UISetColor(commercial_ ? Purplish_ : Gray_);
4509 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4511 [super drawContentInRect:rect selected:selected];
4514 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4516 [super setSelected:selected withFade:fade];
4519 + (int) heightForPackage:(Package *)package {
4525 /* Section Cell {{{ */
4526 @interface SectionCell : UISimpleTableCell {
4531 _UISwitchSlider *switch_;
4536 - (void) setSection:(Section *)section editing:(BOOL)editing;
4540 @implementation SectionCell
4542 - (void) clearSection {
4543 if (section_ != nil) {
4553 if (count_ != nil) {
4560 [self clearSection];
4567 if ((self = [super init]) != nil) {
4568 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4570 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4571 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4575 - (void) onSwitch:(id)sender {
4576 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4577 if (metadata == nil) {
4578 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4579 [Sections_ setObject:metadata forKey:section_];
4583 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4586 - (void) setSection:(Section *)section editing:(BOOL)editing {
4587 if (editing != editing_) {
4589 [switch_ removeFromSuperview];
4591 [self addSubview:switch_];
4595 [self clearSection];
4597 if (section == nil) {
4598 name_ = [CYLocalize("ALL_PACKAGES") retain];
4601 section_ = [section localized];
4602 if (section_ != nil)
4603 section_ = [section_ retain];
4604 name_ = [(section_ == nil ? CYLocalize("NO_SECTION") : section_) retain];
4605 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4608 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4612 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4613 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4620 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4622 CGSize size = [count_ sizeWithFont:Font14_];
4626 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4628 [super drawContentInRect:rect selected:selected];
4634 /* File Table {{{ */
4635 @interface FileTable : RVPage {
4636 _transient Database *database_;
4639 NSMutableArray *files_;
4643 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4644 - (void) setPackage:(Package *)package;
4648 @implementation FileTable
4651 if (package_ != nil)
4660 - (int) numberOfRowsInTable:(UITable *)table {
4661 return files_ == nil ? 0 : [files_ count];
4664 - (float) table:(UITable *)table heightForRow:(int)row {
4668 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4669 if (reusing == nil) {
4670 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4671 UIFont *font = [UIFont systemFontOfSize:16];
4672 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4674 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4678 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4682 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4683 if ((self = [super initWithBook:book]) != nil) {
4684 database_ = database;
4686 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4688 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4689 [self addSubview:list_];
4691 UITableColumn *column = [[[UITableColumn alloc]
4692 initWithTitle:CYLocalize("NAME")
4694 width:[self frame].size.width
4697 [list_ setDataSource:self];
4698 [list_ setSeparatorStyle:1];
4699 [list_ addTableColumn:column];
4700 [list_ setDelegate:self];
4701 [list_ setReusesTableCells:YES];
4705 - (void) setPackage:(Package *)package {
4706 if (package_ != nil) {
4707 [package_ autorelease];
4716 [files_ removeAllObjects];
4718 if (package != nil) {
4719 package_ = [package retain];
4720 name_ = [[package id] retain];
4722 if (NSArray *files = [package files])
4723 [files_ addObjectsFromArray:files];
4725 if ([files_ count] != 0) {
4726 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4727 [files_ removeObjectAtIndex:0];
4728 [files_ sortUsingSelector:@selector(compareByPath:)];
4730 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4731 [stack addObject:@"/"];
4733 for (int i(0), e([files_ count]); i != e; ++i) {
4734 NSString *file = [files_ objectAtIndex:i];
4735 while (![file hasPrefix:[stack lastObject]])
4736 [stack removeLastObject];
4737 NSString *directory = [stack lastObject];
4738 [stack addObject:[file stringByAppendingString:@"/"]];
4739 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4740 ([stack count] - 2) * 3, "",
4741 [file substringFromIndex:[directory length]]
4750 - (void) resetViewAnimated:(BOOL)animated {
4751 [list_ resetViewAnimated:animated];
4754 - (void) reloadData {
4755 [self setPackage:[database_ packageWithName:name_]];
4756 [self reloadButtons];
4759 - (NSString *) title {
4760 return CYLocalize("INSTALLED_FILES");
4763 - (NSString *) backButtonTitle {
4764 return CYLocalize("FILES");
4769 /* Package View {{{ */
4770 @interface PackageView : BrowserView {
4771 _transient Database *database_;
4775 NSMutableArray *buttons_;
4778 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4779 - (void) setPackage:(Package *)package;
4783 @implementation PackageView
4786 if (package_ != nil)
4795 if ([self retainCount] == 1)
4796 [delegate_ setPackageView:self];
4800 /* XXX: this is not safe at all... localization of /fail/ */
4801 - (void) _clickButtonWithName:(NSString *)name {
4802 if ([name isEqualToString:CYLocalize("CLEAR")])
4803 [delegate_ clearPackage:package_];
4804 else if ([name isEqualToString:CYLocalize("INSTALL")])
4805 [delegate_ installPackage:package_];
4806 else if ([name isEqualToString:CYLocalize("REINSTALL")])
4807 [delegate_ installPackage:package_];
4808 else if ([name isEqualToString:CYLocalize("REMOVE")])
4809 [delegate_ removePackage:package_];
4810 else if ([name isEqualToString:CYLocalize("UPGRADE")])
4811 [delegate_ installPackage:package_];
4812 else _assert(false);
4815 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4816 NSString *context([sheet context]);
4818 if ([context isEqualToString:@"modify"]) {
4819 int count = [buttons_ count];
4820 _assert(count != 0);
4821 _assert(button <= count + 1);
4823 if (count != button - 1)
4824 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
4828 [super alertSheet:sheet buttonClicked:button];
4831 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
4832 return [super webView:sender didFinishLoadForFrame:frame];
4835 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4836 [super webView:sender didClearWindowObject:window forFrame:frame];
4837 [window setValue:package_ forKey:@"package"];
4840 - (bool) _allowJavaScriptPanel {
4845 - (void) __rightButtonClicked {
4846 int count = [buttons_ count];
4847 _assert(count != 0);
4850 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
4852 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
4853 [buttons addObjectsFromArray:buttons_];
4854 [buttons addObject:CYLocalize("CANCEL")];
4856 [delegate_ slideUp:[[[UIActionSheet alloc]
4859 defaultButtonIndex:([buttons count] - 1)
4866 - (void) _rightButtonClicked {
4868 [super _rightButtonClicked];
4870 [self __rightButtonClicked];
4874 - (id) _rightButtonTitle {
4875 int count = [buttons_ count];
4876 return count == 0 ? nil : count != 1 ? CYLocalize("MODIFY") : [buttons_ objectAtIndex:0];
4879 - (NSString *) backButtonTitle {
4883 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4884 if ((self = [super initWithBook:book]) != nil) {
4885 database_ = database;
4886 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
4887 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
4891 - (void) setPackage:(Package *)package {
4892 if (package_ != nil) {
4893 [package_ autorelease];
4902 [buttons_ removeAllObjects];
4904 if (package != nil) {
4907 package_ = [package retain];
4908 name_ = [[package id] retain];
4909 commercial_ = [package isCommercial];
4911 if ([package_ mode] != nil)
4912 [buttons_ addObject:CYLocalize("CLEAR")];
4913 if ([package_ source] == nil);
4914 else if ([package_ upgradableAndEssential:NO])
4915 [buttons_ addObject:CYLocalize("UPGRADE")];
4916 else if ([package_ installed] == nil)
4917 [buttons_ addObject:CYLocalize("INSTALL")];
4919 [buttons_ addObject:CYLocalize("REINSTALL")];
4920 if ([package_ installed] != nil)
4921 [buttons_ addObject:CYLocalize("REMOVE")];
4923 if (special_ != NULL) {
4924 CGRect frame([webview_ frame]);
4925 frame.size.width = 320;
4926 frame.size.height = 0;
4927 [webview_ setFrame:frame];
4929 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
4932 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
4934 [self setButtonTitle:nil withStyle:nil toFunction:nil];
4936 [self setFinishHook:nil];
4937 [self setPopupHook:nil];
4940 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
4941 [super callFunction:special_];
4945 [self reloadButtons];
4948 - (bool) isLoading {
4949 return commercial_ ? [super isLoading] : false;
4952 - (void) reloadData {
4953 [self setPackage:[database_ packageWithName:name_]];
4958 /* Package Table {{{ */
4959 @interface PackageTable : RVPage {
4960 _transient Database *database_;
4962 NSMutableArray *packages_;
4963 NSMutableArray *sections_;
4964 UISectionList *list_;
4967 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
4969 - (void) setDelegate:(id)delegate;
4971 - (void) reloadData;
4972 - (void) resetCursor;
4974 - (UISectionList *) list;
4976 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
4980 @implementation PackageTable
4983 [list_ setDataSource:nil];
4986 [packages_ release];
4987 [sections_ release];
4992 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
4993 return [sections_ count];
4996 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
4997 return [[sections_ objectAtIndex:section] name];
5000 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5001 return [[sections_ objectAtIndex:section] row];
5004 - (int) numberOfRowsInTable:(UITable *)table {
5005 return [packages_ count];
5008 - (float) table:(UITable *)table heightForRow:(int)row {
5009 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
5012 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
5014 reusing = [[[PackageCell alloc] init] autorelease];
5015 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
5019 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5023 - (void) tableRowSelected:(NSNotification *)notification {
5024 int row = [[notification object] selectedRow];
5028 Package *package = [packages_ objectAtIndex:row];
5029 package = [database_ packageWithName:[package id]];
5030 PackageView *view([delegate_ packageView]);
5031 [view setPackage:package];
5032 [view setDelegate:delegate_];
5033 [book_ pushPage:view];
5036 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5037 if ((self = [super initWithBook:book]) != nil) {
5038 database_ = database;
5039 title_ = [title retain];
5041 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5042 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5044 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
5045 [list_ setDataSource:self];
5047 UITableColumn *column = [[[UITableColumn alloc]
5048 initWithTitle:CYLocalize("NAME")
5050 width:[self frame].size.width
5053 UITable *table = [list_ table];
5054 [table setSeparatorStyle:1];
5055 [table addTableColumn:column];
5056 [table setDelegate:self];
5057 [table setReusesTableCells:YES];
5059 [self addSubview:list_];
5061 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5062 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5066 - (void) setDelegate:(id)delegate {
5067 delegate_ = delegate;
5070 - (bool) hasPackage:(Package *)package {
5074 - (void) reloadData {
5075 NSArray *packages = [database_ packages];
5077 [packages_ removeAllObjects];
5078 [sections_ removeAllObjects];
5080 _profile(PackageTable$reloadData$Filter)
5081 for (Package *package in packages)
5082 if ([self hasPackage:package])
5083 [packages_ addObject:package];
5086 Section *section = nil;
5088 _profile(PackageTable$reloadData$Section)
5089 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5093 _profile(PackageTable$reloadData$Section$Package)
5094 package = [packages_ objectAtIndex:offset];
5095 index = [package index];
5098 if (section == nil || [section index] != index) {
5099 _profile(PackageTable$reloadData$Section$Allocate)
5100 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5103 _profile(PackageTable$reloadData$Section$Add)
5104 [sections_ addObject:section];
5108 [section addToCount];
5112 _profile(PackageTable$reloadData$List)
5117 - (NSString *) title {
5121 - (void) resetViewAnimated:(BOOL)animated {
5122 [list_ resetViewAnimated:animated];
5125 - (void) resetCursor {
5126 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
5129 - (UISectionList *) list {
5133 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5134 [list_ setShouldHideHeaderInShortLists:hide];
5139 /* Filtered Package Table {{{ */
5140 @interface FilteredPackageTable : PackageTable {
5146 - (void) setObject:(id)object;
5148 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5152 @implementation FilteredPackageTable
5160 - (void) setObject:(id)object {
5166 object_ = [object retain];
5169 - (bool) hasPackage:(Package *)package {
5170 _profile(FilteredPackageTable$hasPackage)
5171 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5175 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5176 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5178 object_ = object == nil ? nil : [object retain];
5180 /* XXX: this is an unsafe optimization of doomy hell */
5181 Method method = class_getInstanceMethod([Package class], filter);
5182 _assert(method != NULL);
5183 imp_ = method_getImplementation(method);
5184 _assert(imp_ != NULL);
5193 /* Add Source View {{{ */
5194 @interface AddSourceView : RVPage {
5195 _transient Database *database_;
5198 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5202 @implementation AddSourceView
5204 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5205 if ((self = [super initWithBook:book]) != nil) {
5206 database_ = database;
5212 /* Source Cell {{{ */
5213 @interface SourceCell : UITableCell {
5216 NSString *description_;
5222 - (SourceCell *) initWithSource:(Source *)source;
5226 @implementation SourceCell
5231 [description_ release];
5236 - (SourceCell *) initWithSource:(Source *)source {
5237 if ((self = [super init]) != nil) {
5239 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5241 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5242 icon_ = [icon_ retain];
5244 origin_ = [[source name] retain];
5245 label_ = [[source uri] retain];
5246 description_ = [[source description] retain];
5250 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5252 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5259 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5263 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5267 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5269 [super drawContentInRect:rect selected:selected];
5274 /* Source Table {{{ */
5275 @interface SourceTable : RVPage {
5276 _transient Database *database_;
5277 UISectionList *list_;
5278 NSMutableArray *sources_;
5279 UIActionSheet *alert_;
5283 UIProgressHUD *hud_;
5286 //NSURLConnection *installer_;
5287 NSURLConnection *trivial_bz2_;
5288 NSURLConnection *trivial_gz_;
5289 //NSURLConnection *automatic_;
5294 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5298 @implementation SourceTable
5300 - (void) _deallocConnection:(NSURLConnection *)connection {
5301 if (connection != nil) {
5302 [connection cancel];
5303 //[connection setDelegate:nil];
5304 [connection release];
5309 [[list_ table] setDelegate:nil];
5310 [list_ setDataSource:nil];
5319 //[self _deallocConnection:installer_];
5320 [self _deallocConnection:trivial_gz_];
5321 [self _deallocConnection:trivial_bz2_];
5322 //[self _deallocConnection:automatic_];
5329 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5330 return offset_ == 0 ? 1 : 2;
5333 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5334 switch (section + (offset_ == 0 ? 1 : 0)) {
5335 case 0: return CYLocalize("ENTERED_BY_USER");
5336 case 1: return CYLocalize("INSTALLED_BY_PACKAGE");
5344 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5345 switch (section + (offset_ == 0 ? 1 : 0)) {
5347 case 1: return offset_;
5355 - (int) numberOfRowsInTable:(UITable *)table {
5356 return [sources_ count];
5359 - (float) table:(UITable *)table heightForRow:(int)row {
5360 Source *source = [sources_ objectAtIndex:row];
5361 return [source description] == nil ? 56 : 73;
5364 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5365 Source *source = [sources_ objectAtIndex:row];
5366 // XXX: weird warning, stupid selectors ;P
5367 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5370 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5374 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5378 - (void) tableRowSelected:(NSNotification*)notification {
5379 UITable *table([list_ table]);
5380 int row([table selectedRow]);
5384 Source *source = [sources_ objectAtIndex:row];
5386 PackageTable *packages = [[[FilteredPackageTable alloc]
5389 title:[source label]
5390 filter:@selector(isVisibleInSource:)
5394 [packages setDelegate:delegate_];
5396 [book_ pushPage:packages];
5399 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5400 Source *source = [sources_ objectAtIndex:row];
5401 return [source record] != nil;
5404 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5405 [[list_ table] setDeleteConfirmationRow:row];
5408 - (void) table:(UITable *)table deleteRow:(int)row {
5409 Source *source = [sources_ objectAtIndex:row];
5410 [Sources_ removeObjectForKey:[source key]];
5411 [delegate_ syncData];
5415 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5418 @"./", @"Distribution",
5419 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5421 [delegate_ syncData];
5424 - (NSString *) getWarning {
5425 NSString *href(href_);
5426 NSRange colon([href rangeOfString:@"://"]);
5427 if (colon.location != NSNotFound)
5428 href = [href substringFromIndex:(colon.location + 3)];
5429 href = [href stringByAddingPercentEscapes];
5430 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5431 href = [href stringByCachingURLWithCurrentCDN];
5433 NSURL *url([NSURL URLWithString:href]);
5435 NSStringEncoding encoding;
5436 NSError *error(nil);
5438 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5439 return [warning length] == 0 ? nil : warning;
5443 - (void) _endConnection:(NSURLConnection *)connection {
5444 NSURLConnection **field = NULL;
5445 if (connection == trivial_bz2_)
5446 field = &trivial_bz2_;
5447 else if (connection == trivial_gz_)
5448 field = &trivial_gz_;
5449 _assert(field != NULL);
5450 [connection release];
5454 trivial_bz2_ == nil &&
5460 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5463 UIActionSheet *sheet = [[[UIActionSheet alloc]
5464 initWithTitle:CYLocalize("SOURCE_WARNING")
5465 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_ANYWAY"), CYLocalize("CANCEL"), nil]
5466 defaultButtonIndex:0
5471 [sheet setNumberOfRows:1];
5473 [sheet setBodyText:warning];
5474 [sheet popupAlertAnimated:YES];
5477 } else if (error_ != nil) {
5478 UIActionSheet *sheet = [[[UIActionSheet alloc]
5479 initWithTitle:CYLocalize("VERIFICATION_ERROR")
5480 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5481 defaultButtonIndex:0
5486 [sheet setBodyText:[error_ localizedDescription]];
5487 [sheet popupAlertAnimated:YES];
5489 UIActionSheet *sheet = [[[UIActionSheet alloc]
5490 initWithTitle:CYLocalize("NOT_REPOSITORY")
5491 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5492 defaultButtonIndex:0
5497 [sheet setBodyText:CYLocalize("NOT_REPOSITORY_EX")];
5498 [sheet popupAlertAnimated:YES];
5501 [delegate_ setStatusBarShowsProgress:NO];
5502 [delegate_ removeProgressHUD:hud_];
5512 if (error_ != nil) {
5519 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5520 switch ([response statusCode]) {
5526 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5527 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5529 error_ = [error retain];
5530 [self _endConnection:connection];
5533 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5534 [self _endConnection:connection];
5537 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5538 NSMutableURLRequest *request = [NSMutableURLRequest
5539 requestWithURL:[NSURL URLWithString:href]
5540 cachePolicy:NSURLRequestUseProtocolCachePolicy
5541 timeoutInterval:20.0
5544 [request setHTTPMethod:method];
5546 if (Machine_ != NULL)
5547 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5548 if (UniqueID_ != nil)
5549 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5552 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5554 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5557 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5558 NSString *context([sheet context]);
5560 if ([context isEqualToString:@"source"]) {
5563 NSString *href = [[sheet textField] text];
5565 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5567 if (![href hasSuffix:@"/"])
5568 href_ = [href stringByAppendingString:@"/"];
5571 href_ = [href_ retain];
5573 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5574 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5575 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5579 hud_ = [[delegate_ addProgressHUD] retain];
5580 [hud_ setText:CYLocalize("VERIFYING_URL")];
5591 } else if ([context isEqualToString:@"trivial"])
5593 else if ([context isEqualToString:@"urlerror"])
5595 else if ([context isEqualToString:@"warning"]) {
5615 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5616 if ((self = [super initWithBook:book]) != nil) {
5617 database_ = database;
5618 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5620 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5621 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5622 [list_ setShouldHideHeaderInShortLists:NO];
5624 [self addSubview:list_];
5625 [list_ setDataSource:self];
5627 UITableColumn *column = [[UITableColumn alloc]
5628 initWithTitle:CYLocalize("NAME")
5630 width:[self frame].size.width
5633 UITable *table = [list_ table];
5634 [table setSeparatorStyle:1];
5635 [table addTableColumn:column];
5636 [table setDelegate:self];
5640 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5641 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5645 - (void) reloadData {
5647 _assert(list.ReadMainList());
5649 [sources_ removeAllObjects];
5650 [sources_ addObjectsFromArray:[database_ sources]];
5652 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5655 int count = [sources_ count];
5656 for (offset_ = 0; offset_ != count; ++offset_) {
5657 Source *source = [sources_ objectAtIndex:offset_];
5658 if ([source record] == nil)
5665 - (void) resetViewAnimated:(BOOL)animated {
5666 [list_ resetViewAnimated:animated];
5669 - (void) _leftButtonClicked {
5670 /*[book_ pushPage:[[[AddSourceView alloc]
5675 UIActionSheet *sheet = [[[UIActionSheet alloc]
5676 initWithTitle:CYLocalize("ENTER_APT_URL")
5677 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_SOURCE"), CYLocalize("CANCEL"), nil]
5678 defaultButtonIndex:0
5683 [sheet setNumberOfRows:1];
5685 [sheet addTextFieldWithValue:@"http://" label:@""];
5687 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5688 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5689 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5690 [traits setKeyboardType:UIKeyboardTypeURL];
5691 // XXX: UIReturnKeyDone
5692 [traits setReturnKeyType:UIReturnKeyNext];
5694 [sheet popupAlertAnimated:YES];
5697 - (void) _rightButtonClicked {
5698 UITable *table = [list_ table];
5699 BOOL editing = [table isRowDeletionEnabled];
5700 [table enableRowDeletion:!editing animated:YES];
5701 [book_ reloadButtonsForPage:self];
5704 - (NSString *) title {
5705 return CYLocalize("SOURCES");
5708 - (NSString *) leftButtonTitle {
5709 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("ADD") : nil;
5712 - (id) rightButtonTitle {
5713 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("DONE") : CYLocalize("EDIT");
5716 - (UINavigationButtonStyle) rightButtonStyle {
5717 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5723 /* Installed View {{{ */
5724 @interface InstalledView : RVPage {
5725 _transient Database *database_;
5726 FilteredPackageTable *packages_;
5730 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5734 @implementation InstalledView
5737 [packages_ release];
5741 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5742 if ((self = [super initWithBook:book]) != nil) {
5743 database_ = database;
5745 packages_ = [[FilteredPackageTable alloc]
5749 filter:@selector(isInstalledAndVisible:)
5750 with:[NSNumber numberWithBool:YES]
5753 [self addSubview:packages_];
5755 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5756 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5760 - (void) resetViewAnimated:(BOOL)animated {
5761 [packages_ resetViewAnimated:animated];
5764 - (void) reloadData {
5765 [packages_ reloadData];
5768 - (void) _rightButtonClicked {
5769 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5770 [packages_ reloadData];
5772 [book_ reloadButtonsForPage:self];
5775 - (NSString *) title {
5776 return CYLocalize("INSTALLED");
5779 - (NSString *) backButtonTitle {
5780 return CYLocalize("PACKAGES");
5783 - (id) rightButtonTitle {
5784 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? CYLocalize("EXPERT") : CYLocalize("SIMPLE");
5787 - (UINavigationButtonStyle) rightButtonStyle {
5788 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5791 - (void) setDelegate:(id)delegate {
5792 [super setDelegate:delegate];
5793 [packages_ setDelegate:delegate];
5800 @interface HomeView : BrowserView {
5805 @implementation HomeView
5807 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5808 NSString *context([sheet context]);
5810 if ([context isEqualToString:@"about"])
5813 [super alertSheet:sheet buttonClicked:button];
5816 - (void) _leftButtonClicked {
5817 UIActionSheet *sheet = [[[UIActionSheet alloc]
5818 initWithTitle:CYLocalize("ABOUT_CYDIA")
5819 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
5820 defaultButtonIndex:0
5826 @"Copyright (C) 2008-2009\n"
5827 "Jay Freeman (saurik)\n"
5828 "saurik@saurik.com\n"
5829 "http://www.saurik.com/\n"
5832 "http://www.theokorigroup.com/\n"
5834 "College of Creative Studies,\n"
5835 "University of California,\n"
5837 "http://www.ccs.ucsb.edu/"
5840 [sheet popupAlertAnimated:YES];
5843 - (NSString *) leftButtonTitle {
5844 return CYLocalize("ABOUT");
5849 /* Manage View {{{ */
5850 @interface ManageView : BrowserView {
5855 @implementation ManageView
5857 - (NSString *) title {
5858 return CYLocalize("MANAGE");
5861 - (void) _leftButtonClicked {
5862 [delegate_ askForSettings];
5865 - (NSString *) leftButtonTitle {
5866 return CYLocalize("SETTINGS");
5870 - (id) _rightButtonTitle {
5871 return Queuing_ ? CYLocalize("QUEUE") : nil;
5874 - (UINavigationButtonStyle) rightButtonStyle {
5875 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5878 - (void) _rightButtonClicked {
5883 - (bool) isLoading {
5890 #include <BrowserView.m>
5892 /* Cydia Book {{{ */
5893 @interface CYBook : RVBook <
5896 _transient Database *database_;
5897 UINavigationBar *overlay_;
5898 UINavigationBar *underlay_;
5899 UIProgressIndicator *indicator_;
5900 UITextLabel *prompt_;
5901 UIProgressBar *progress_;
5902 UINavigationButton *cancel_;
5906 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
5912 @implementation CYBook
5916 [indicator_ release];
5918 [progress_ release];
5923 - (NSString *) getTitleForPage:(RVPage *)page {
5924 return [super getTitleForPage:page];
5932 [UIView beginAnimations:nil context:NULL];
5934 CGRect ovrframe = [overlay_ frame];
5935 ovrframe.origin.y = 0;
5936 [overlay_ setFrame:ovrframe];
5938 CGRect barframe = [navbar_ frame];
5939 barframe.origin.y += ovrframe.size.height;
5940 [navbar_ setFrame:barframe];
5942 CGRect trnframe = [transition_ frame];
5943 trnframe.origin.y += ovrframe.size.height;
5944 trnframe.size.height -= ovrframe.size.height;
5945 [transition_ setFrame:trnframe];
5947 [UIView endAnimations];
5949 [indicator_ startAnimation];
5950 [prompt_ setText:CYLocalize("UPDATING_DATABASE")];
5951 [progress_ setProgress:0];
5954 [overlay_ addSubview:cancel_];
5957 detachNewThreadSelector:@selector(_update)
5963 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5964 NSString *context([sheet context]);
5966 if ([context isEqualToString:@"refresh"])
5970 - (void) _update_:(NSString *)error {
5973 [indicator_ stopAnimation];
5975 [UIView beginAnimations:nil context:NULL];
5977 CGRect ovrframe = [overlay_ frame];
5978 ovrframe.origin.y = -ovrframe.size.height;
5979 [overlay_ setFrame:ovrframe];
5981 CGRect barframe = [navbar_ frame];
5982 barframe.origin.y -= ovrframe.size.height;
5983 [navbar_ setFrame:barframe];
5985 CGRect trnframe = [transition_ frame];
5986 trnframe.origin.y -= ovrframe.size.height;
5987 trnframe.size.height += ovrframe.size.height;
5988 [transition_ setFrame:trnframe];
5990 [UIView commitAnimations];
5993 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
5995 UIActionSheet *sheet = [[[UIActionSheet alloc]
5996 initWithTitle:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), CYLocalize("REFRESH")]
5997 buttons:[NSArray arrayWithObjects:
6000 defaultButtonIndex:0
6005 [sheet setBodyText:error];
6006 [sheet popupAlertAnimated:YES];
6008 [self reloadButtons];
6012 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6013 if ((self = [super initWithFrame:frame]) != nil) {
6014 database_ = database;
6016 CGRect ovrrect = [navbar_ bounds];
6017 ovrrect.size.height = [UINavigationBar defaultSize].height;
6018 ovrrect.origin.y = -ovrrect.size.height;
6020 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6021 [self addSubview:overlay_];
6023 ovrrect.origin.y = frame.size.height;
6024 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6025 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6026 [self addSubview:underlay_];
6028 [overlay_ setBarStyle:1];
6029 [underlay_ setBarStyle:1];
6031 int barstyle = [overlay_ _barStyle:NO];
6032 bool ugly = barstyle == 0;
6034 UIProgressIndicatorStyle style = ugly ?
6035 UIProgressIndicatorStyleMediumBrown :
6036 UIProgressIndicatorStyleMediumWhite;
6038 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
6039 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6040 CGRect indrect = {{indoffset, indoffset}, indsize};
6042 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6043 [indicator_ setStyle:style];
6044 [overlay_ addSubview:indicator_];
6046 CGSize prmsize = {215, indsize.height + 4};
6049 indoffset * 2 + indsize.width,
6053 unsigned(ovrrect.size.height - prmsize.height) / 2
6056 UIFont *font = [UIFont systemFontOfSize:15];
6058 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6060 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6061 [prompt_ setBackgroundColor:[UIColor clearColor]];
6062 [prompt_ setFont:font];
6064 [overlay_ addSubview:prompt_];
6066 CGSize prgsize = {75, 100};
6069 ovrrect.size.width - prgsize.width - 10,
6070 (ovrrect.size.height - prgsize.height) / 2
6073 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6074 [progress_ setStyle:0];
6075 [overlay_ addSubview:progress_];
6077 cancel_ = [[UINavigationButton alloc] initWithTitle:CYLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6078 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6080 CGRect frame = [cancel_ frame];
6081 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6082 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6083 [cancel_ setFrame:frame];
6085 [cancel_ setBarStyle:barstyle];
6089 - (void) _onCancel {
6091 [cancel_ removeFromSuperview];
6094 - (void) _update { _pooled
6096 status.setDelegate(self);
6098 NSString *error([database_ updateWithStatus:status]);
6101 performSelectorOnMainThread:@selector(_update_:)
6107 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
6108 [prompt_ setText:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), error]];
6111 - (void) setProgressTitle:(NSString *)title {
6113 performSelectorOnMainThread:@selector(_setProgressTitle:)
6119 - (void) setProgressPercent:(float)percent {
6121 performSelectorOnMainThread:@selector(_setProgressPercent:)
6122 withObject:[NSNumber numberWithFloat:percent]
6127 - (void) startProgress {
6130 - (void) addProgressOutput:(NSString *)output {
6132 performSelectorOnMainThread:@selector(_addProgressOutput:)
6138 - (bool) isCancelling:(size_t)received {
6142 - (void) _setProgressTitle:(NSString *)title {
6143 [prompt_ setText:title];
6146 - (void) _setProgressPercent:(NSNumber *)percent {
6147 [progress_ setProgress:[percent floatValue]];
6150 - (void) _addProgressOutput:(NSString *)output {
6155 /* Cydia:// Protocol {{{ */
6156 @interface CydiaURLProtocol : NSURLProtocol {
6161 @implementation CydiaURLProtocol
6163 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6164 NSURL *url([request URL]);
6167 NSString *scheme([[url scheme] lowercaseString]);
6168 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6173 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6177 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6178 id<NSURLProtocolClient> client([self client]);
6180 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6182 NSData *data(UIImagePNGRepresentation(icon));
6184 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6185 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6186 [client URLProtocol:self didLoadData:data];
6187 [client URLProtocolDidFinishLoading:self];
6191 - (void) startLoading {
6192 id<NSURLProtocolClient> client([self client]);
6193 NSURLRequest *request([self request]);
6195 NSURL *url([request URL]);
6196 NSString *href([url absoluteString]);
6198 NSString *path([href substringFromIndex:8]);
6199 NSRange slash([path rangeOfString:@"/"]);
6202 if (slash.location == NSNotFound) {
6206 command = [path substringToIndex:slash.location];
6207 path = [path substringFromIndex:(slash.location + 1)];
6210 Database *database([Database sharedInstance]);
6212 if ([command isEqualToString:@"package-icon"]) {
6215 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6216 Package *package([database packageWithName:path]);
6219 UIImage *icon([package icon]);
6220 [self _returnPNGWithImage:icon forRequest:request];
6221 } else if ([command isEqualToString:@"source-icon"]) {
6224 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6225 NSString *source(Simplify(path));
6226 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6228 icon = [UIImage applicationImageNamed:@"unknown.png"];
6229 [self _returnPNGWithImage:icon forRequest:request];
6230 } else if ([command isEqualToString:@"uikit-image"]) {
6233 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6234 UIImage *icon(_UIImageWithName(path));
6235 [self _returnPNGWithImage:icon forRequest:request];
6236 } else if ([command isEqualToString:@"section-icon"]) {
6239 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6240 NSString *section(Simplify(path));
6241 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6243 icon = [UIImage applicationImageNamed:@"unknown.png"];
6244 [self _returnPNGWithImage:icon forRequest:request];
6246 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6250 - (void) stopLoading {
6256 /* Sections View {{{ */
6257 @interface SectionsView : RVPage {
6258 _transient Database *database_;
6259 NSMutableArray *sections_;
6260 NSMutableArray *filtered_;
6261 UITransitionView *transition_;
6267 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6268 - (void) reloadData;
6273 @implementation SectionsView
6276 [list_ setDataSource:nil];
6277 [list_ setDelegate:nil];
6279 [sections_ release];
6280 [filtered_ release];
6281 [transition_ release];
6283 [accessory_ release];
6287 - (int) numberOfRowsInTable:(UITable *)table {
6288 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6291 - (float) table:(UITable *)table heightForRow:(int)row {
6295 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6297 reusing = [[[SectionCell alloc] init] autorelease];
6298 [(SectionCell *)reusing setSection:(editing_ ?
6299 [sections_ objectAtIndex:row] :
6300 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6301 ) editing:editing_];
6305 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6309 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6313 - (void) tableRowSelected:(NSNotification *)notification {
6314 int row = [[notification object] selectedRow];
6325 title = CYLocalize("ALL_PACKAGES");
6327 section = [filtered_ objectAtIndex:(row - 1)];
6328 name = [section name];
6331 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6334 title = CYLocalize("NO_SECTION");
6338 PackageTable *table = [[[FilteredPackageTable alloc]
6342 filter:@selector(isVisiblyUninstalledInSection:)
6346 [table setDelegate:delegate_];
6348 [book_ pushPage:table];
6351 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6352 if ((self = [super initWithBook:book]) != nil) {
6353 database_ = database;
6355 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6356 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6358 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6359 [self addSubview:transition_];
6361 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6362 [transition_ transition:0 toView:list_];
6364 UITableColumn *column = [[[UITableColumn alloc]
6365 initWithTitle:CYLocalize("NAME")
6367 width:[self frame].size.width
6370 [list_ setDataSource:self];
6371 [list_ setSeparatorStyle:1];
6372 [list_ addTableColumn:column];
6373 [list_ setDelegate:self];
6374 [list_ setReusesTableCells:YES];
6378 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6379 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6383 - (void) reloadData {
6384 NSArray *packages = [database_ packages];
6386 [sections_ removeAllObjects];
6387 [filtered_ removeAllObjects];
6390 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6391 SectionMap sections;
6392 sections.resize(64);
6394 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6398 for (Package *package in packages) {
6399 NSString *name([package section]);
6400 NSString *key(name == nil ? @"" : name);
6405 _profile(SectionsView$reloadData$Section)
6406 section = §ions[key];
6407 if (*section == nil) {
6408 _profile(SectionsView$reloadData$Section$Allocate)
6409 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6414 [*section addToCount];
6416 _profile(SectionsView$reloadData$Filter)
6417 if (![package valid] || [package installed] != nil || ![package visible])
6421 [*section addToRow];
6425 _profile(SectionsView$reloadData$Section)
6426 section = [sections objectForKey:key];
6427 if (section == nil) {
6428 _profile(SectionsView$reloadData$Section$Allocate)
6429 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6430 [sections setObject:section forKey:key];
6435 [section addToCount];
6437 _profile(SectionsView$reloadData$Filter)
6438 if (![package valid] || [package installed] != nil || ![package visible])
6448 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6449 [sections_ addObject:i->second];
6451 [sections_ addObjectsFromArray:[sections allValues]];
6454 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6456 for (Section *section in sections_) {
6457 size_t count([section row]);
6461 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6462 [section setCount:count];
6463 [filtered_ addObject:section];
6470 - (void) resetView {
6472 [self _rightButtonClicked];
6475 - (void) resetViewAnimated:(BOOL)animated {
6476 [list_ resetViewAnimated:animated];
6479 - (void) _rightButtonClicked {
6480 if ((editing_ = !editing_))
6483 [delegate_ updateData];
6484 [book_ reloadTitleForPage:self];
6485 [book_ reloadButtonsForPage:self];
6488 - (NSString *) title {
6489 return editing_ ? CYLocalize("SECTION_VISIBILITY") : CYLocalize("INSTALL_BY_SECTION");
6492 - (NSString *) backButtonTitle {
6493 return CYLocalize("SECTIONS");
6496 - (id) rightButtonTitle {
6497 return [sections_ count] == 0 ? nil : editing_ ? CYLocalize("DONE") : CYLocalize("EDIT");
6500 - (UINavigationButtonStyle) rightButtonStyle {
6501 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6504 - (UIView *) accessoryView {
6510 /* Changes View {{{ */
6511 @interface ChangesView : RVPage {
6512 _transient Database *database_;
6513 NSMutableArray *packages_;
6514 NSMutableArray *sections_;
6515 UISectionList *list_;
6519 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6520 - (void) reloadData;
6524 @implementation ChangesView
6527 [[list_ table] setDelegate:nil];
6528 [list_ setDataSource:nil];
6530 [packages_ release];
6531 [sections_ release];
6536 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6537 return [sections_ count];
6540 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6541 return [[sections_ objectAtIndex:section] name];
6544 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6545 return [[sections_ objectAtIndex:section] row];
6548 - (int) numberOfRowsInTable:(UITable *)table {
6549 return [packages_ count];
6552 - (float) table:(UITable *)table heightForRow:(int)row {
6553 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6556 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6558 reusing = [[[PackageCell alloc] init] autorelease];
6559 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6563 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6567 - (void) tableRowSelected:(NSNotification *)notification {
6568 int row = [[notification object] selectedRow];
6571 Package *package = [packages_ objectAtIndex:row];
6572 PackageView *view([delegate_ packageView]);
6573 [view setDelegate:delegate_];
6574 [view setPackage:package];
6575 [book_ pushPage:view];
6578 - (void) _leftButtonClicked {
6579 [(CYBook *)book_ update];
6580 [self reloadButtons];
6583 - (void) _rightButtonClicked {
6584 [delegate_ distUpgrade];
6587 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6588 if ((self = [super initWithBook:book]) != nil) {
6589 database_ = database;
6591 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6592 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6594 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6595 [self addSubview:list_];
6597 [list_ setShouldHideHeaderInShortLists:NO];
6598 [list_ setDataSource:self];
6599 //[list_ setSectionListStyle:1];
6601 UITableColumn *column = [[[UITableColumn alloc]
6602 initWithTitle:CYLocalize("NAME")
6604 width:[self frame].size.width
6607 UITable *table = [list_ table];
6608 [table setSeparatorStyle:1];
6609 [table addTableColumn:column];
6610 [table setDelegate:self];
6611 [table setReusesTableCells:YES];
6615 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6616 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6620 - (void) reloadData {
6621 NSArray *packages = [database_ packages];
6623 [packages_ removeAllObjects];
6624 [sections_ removeAllObjects];
6627 for (Package *package in packages)
6629 [package installed] == nil && [package valid] && [package visible] ||
6630 [package upgradableAndEssential:YES]
6632 [packages_ addObject:package];
6635 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6638 Section *upgradable = [[[Section alloc] initWithName:CYLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6639 Section *ignored = [[[Section alloc] initWithName:CYLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6640 Section *section = nil;
6644 bool unseens = false;
6646 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6648 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6649 Package *package = [packages_ objectAtIndex:offset];
6651 BOOL uae = [package upgradableAndEssential:YES];
6657 _profile(ChangesView$reloadData$Remember)
6658 seen = [package seen];
6661 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6666 name = CYLocalize("UNKNOWN");
6668 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6672 _profile(ChangesView$reloadData$Allocate)
6673 name = [NSString stringWithFormat:CYLocalize("NEW_AT"), name];
6674 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6675 [sections_ addObject:section];
6679 [section addToCount];
6680 } else if ([package ignored])
6681 [ignored addToCount];
6684 [upgradable addToCount];
6689 CFRelease(formatter);
6692 Section *last = [sections_ lastObject];
6693 size_t count = [last count];
6694 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6695 [sections_ removeLastObject];
6698 if ([ignored count] != 0)
6699 [sections_ insertObject:ignored atIndex:0];
6701 [sections_ insertObject:upgradable atIndex:0];
6704 [self reloadButtons];
6707 - (void) resetViewAnimated:(BOOL)animated {
6708 [list_ resetViewAnimated:animated];
6711 - (NSString *) leftButtonTitle {
6712 return [(CYBook *)book_ updating] ? nil : CYLocalize("REFRESH");
6715 - (id) rightButtonTitle {
6716 return upgrades_ == 0 ? nil : [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6719 - (NSString *) title {
6720 return CYLocalize("CHANGES");
6725 /* Search View {{{ */
6726 @protocol SearchViewDelegate
6727 - (void) showKeyboard:(BOOL)show;
6730 @interface SearchView : RVPage {
6732 UISearchField *field_;
6733 UITransitionView *transition_;
6734 FilteredPackageTable *table_;
6735 UIPreferencesTable *advanced_;
6741 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6742 - (void) reloadData;
6746 @implementation SearchView
6749 [field_ setDelegate:nil];
6751 [accessory_ release];
6753 [transition_ release];
6755 [advanced_ release];
6760 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6764 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6766 case 0: return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("ADVANCED_SEARCH"), CYLocalize("COMING_SOON")];
6768 default: _assert(false);
6772 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6776 default: _assert(false);
6780 - (void) _showKeyboard:(BOOL)show {
6781 CGSize keysize = [UIKeyboard defaultSize];
6782 CGRect keydown = [book_ pageBounds];
6783 CGRect keyup = keydown;
6784 keyup.size.height -= keysize.height - ButtonBarHeight_;
6786 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6788 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6789 [animation setSignificantRectFields:8];
6792 [animation setStartFrame:keydown];
6793 [animation setEndFrame:keyup];
6795 [animation setStartFrame:keyup];
6796 [animation setEndFrame:keydown];
6799 UIAnimator *animator = [UIAnimator sharedAnimator];
6802 addAnimations:[NSArray arrayWithObjects:animation, nil]
6803 withDuration:(KeyboardTime_ - delay)
6808 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6810 [delegate_ showKeyboard:show];
6813 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6814 [self _showKeyboard:YES];
6817 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
6818 [self _showKeyboard:NO];
6821 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
6823 NSString *text([field_ text]);
6824 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6830 - (void) textFieldClearButtonPressed:(UITextField *)field {
6834 - (void) keyboardInputShouldDelete:(id)input {
6838 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
6839 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6843 [field_ resignFirstResponder];
6848 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6849 if ((self = [super initWithBook:book]) != nil) {
6850 CGRect pageBounds = [book_ pageBounds];
6852 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6853 [self addSubview:transition_];
6855 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6857 [advanced_ setReusesTableCells:YES];
6858 [advanced_ setDataSource:self];
6859 [advanced_ reloadData];
6861 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6862 CGColor dimmed(space_, 0, 0, 0, 0.5);
6863 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
6865 table_ = [[FilteredPackageTable alloc]
6869 filter:@selector(isUnfilteredAndSearchedForBy:)
6873 [table_ setShouldHideHeaderInShortLists:NO];
6874 [transition_ transition:0 toView:table_];
6883 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
6890 [self bounds].size.width - area.origin.x - 18;
6892 area.size.height = [UISearchField defaultHeight];
6894 field_ = [[UISearchField alloc] initWithFrame:area];
6896 UIFont *font = [UIFont systemFontOfSize:16];
6897 [field_ setFont:font];
6899 [field_ setPlaceholder:CYLocalize("SEARCH_EX")];
6900 [field_ setDelegate:self];
6902 [field_ setPaddingTop:5];
6904 UITextInputTraits *traits([field_ textInputTraits]);
6905 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6906 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6907 [traits setReturnKeyType:UIReturnKeySearch];
6909 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
6911 accessory_ = [[UIView alloc] initWithFrame:accrect];
6912 [accessory_ addSubview:field_];
6914 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
6915 [configure setShowPressFeedback:YES];
6916 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
6917 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
6918 [accessory_ addSubview:configure];*/
6920 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6921 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6927 LKAnimation *animation = [LKTransition animation];
6928 [animation setType:@"oglFlip"];
6929 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
6930 [animation setFillMode:@"extended"];
6931 [animation setTransitionFlags:3];
6932 [animation setDuration:10];
6933 [animation setSpeed:0.35];
6934 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
6935 [[transition_ _layer] addAnimation:animation forKey:0];
6936 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
6937 flipped_ = !flipped_;
6941 - (void) configurePushed {
6942 [field_ resignFirstResponder];
6946 - (void) resetViewAnimated:(BOOL)animated {
6949 [table_ resetViewAnimated:animated];
6952 - (void) _reloadData {
6955 - (void) reloadData {
6958 [table_ setObject:[field_ text]];
6959 _profile(SearchView$reloadData)
6960 [table_ reloadData];
6963 [table_ resetCursor];
6966 - (UIView *) accessoryView {
6970 - (NSString *) title {
6974 - (NSString *) backButtonTitle {
6975 return CYLocalize("SEARCH");
6978 - (void) setDelegate:(id)delegate {
6979 [table_ setDelegate:delegate];
6980 [super setDelegate:delegate];
6986 @interface SettingsView : RVPage {
6987 _transient Database *database_;
6990 UIPreferencesTable *table_;
6991 _UISwitchSlider *subscribedSwitch_;
6992 _UISwitchSlider *ignoredSwitch_;
6993 UIPreferencesControlTableCell *subscribedCell_;
6994 UIPreferencesControlTableCell *ignoredCell_;
6997 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7001 @implementation SettingsView
7004 [table_ setDataSource:nil];
7007 if (package_ != nil)
7010 [subscribedSwitch_ release];
7011 [ignoredSwitch_ release];
7012 [subscribedCell_ release];
7013 [ignoredCell_ release];
7017 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7018 if (package_ == nil)
7024 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7025 if (package_ == nil)
7032 default: _assert(false);
7038 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7039 if (package_ == nil)
7046 default: _assert(false);
7052 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7053 if (package_ == nil)
7060 default: _assert(false);
7066 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7067 if (package_ == nil)
7070 _UISwitchSlider *slider([cell control]);
7071 BOOL value([slider value] != 0);
7072 NSMutableDictionary *metadata([package_ metadata]);
7075 if (NSNumber *number = [metadata objectForKey:key])
7076 before = [number boolValue];
7080 if (value != before) {
7081 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7083 [delegate_ updateData];
7087 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7088 [self onSomething:cell withKey:@"IsSubscribed"];
7091 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7092 [self onSomething:cell withKey:@"IsIgnored"];
7095 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7096 if (package_ == nil)
7100 case 0: switch (row) {
7102 return subscribedCell_;
7104 return ignoredCell_;
7105 default: _assert(false);
7108 case 1: switch (row) {
7110 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7111 [cell setShowSelection:NO];
7112 [cell setTitle:CYLocalize("SHOW_ALL_CHANGES_EX")];
7116 default: _assert(false);
7119 default: _assert(false);
7125 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7126 if ((self = [super initWithBook:book])) {
7127 database_ = database;
7128 name_ = [package retain];
7130 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7131 [self addSubview:table_];
7133 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7134 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
7136 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7137 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
7139 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7140 [subscribedCell_ setShowSelection:NO];
7141 [subscribedCell_ setTitle:CYLocalize("SHOW_ALL_CHANGES")];
7142 [subscribedCell_ setControl:subscribedSwitch_];
7144 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7145 [ignoredCell_ setShowSelection:NO];
7146 [ignoredCell_ setTitle:CYLocalize("IGNORE_UPGRADES")];
7147 [ignoredCell_ setControl:ignoredSwitch_];
7149 [table_ setDataSource:self];
7154 - (void) resetViewAnimated:(BOOL)animated {
7155 [table_ resetViewAnimated:animated];
7158 - (void) reloadData {
7159 if (package_ != nil)
7160 [package_ autorelease];
7161 package_ = [database_ packageWithName:name_];
7162 if (package_ != nil) {
7164 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7165 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7168 [table_ reloadData];
7171 - (NSString *) title {
7172 return CYLocalize("SETTINGS");
7177 /* Signature View {{{ */
7178 @interface SignatureView : BrowserView {
7179 _transient Database *database_;
7183 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7187 @implementation SignatureView
7194 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7196 [super webView:sender didClearWindowObject:window forFrame:frame];
7199 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7200 if ((self = [super initWithBook:book]) != nil) {
7201 database_ = database;
7202 package_ = [package retain];
7207 - (void) resetViewAnimated:(BOOL)animated {
7210 - (void) reloadData {
7211 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7217 @interface Cydia : UIApplication <
7218 ConfirmationViewDelegate,
7219 ProgressViewDelegate,
7228 UIToolbar *buttonbar_;
7232 NSMutableArray *essential_;
7233 NSMutableArray *broken_;
7235 Database *database_;
7236 ProgressView *progress_;
7240 UIKeyboard *keyboard_;
7241 UIProgressHUD *hud_;
7243 SectionsView *sections_;
7244 ChangesView *changes_;
7245 ManageView *manage_;
7246 SearchView *search_;
7248 NSMutableArray *details_;
7253 @implementation Cydia
7256 if ([broken_ count] != 0) {
7257 int count = [broken_ count];
7259 UIActionSheet *sheet = [[[UIActionSheet alloc]
7260 initWithTitle:(count == 1 ? CYLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:CYLocalize("HALFINSTALLED_PACKAGES"), count])
7261 buttons:[NSArray arrayWithObjects:
7262 CYLocalize("FORCIBLY_CLEAR"),
7263 CYLocalize("TEMPORARY_IGNORE"),
7265 defaultButtonIndex:0
7270 [sheet setBodyText:CYLocalize("HALFINSTALLED_PACKAGE_EX")];
7271 [sheet popupAlertAnimated:YES];
7272 } else if (!Ignored_ && [essential_ count] != 0) {
7273 int count = [essential_ count];
7275 UIActionSheet *sheet = [[[UIActionSheet alloc]
7276 initWithTitle:(count == 1 ? CYLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:CYLocalize("ESSENTIAL_UPGRADES"), count])
7277 buttons:[NSArray arrayWithObjects:
7278 CYLocalize("UPGRADE_ESSENTIAL"),
7279 CYLocalize("COMPLETE_UPGRADE"),
7280 CYLocalize("TEMPORARY_IGNORE"),
7282 defaultButtonIndex:0
7287 [sheet setBodyText:CYLocalize("ESSENTIAL_UPGRADE_EX")];
7288 [sheet popupAlertAnimated:YES];
7292 - (void) _reloadData {
7295 static bool loaded(false);
7296 UIProgressHUD *hud([self addProgressHUD]);
7297 [hud setText:(loaded ? CYLocalize("RELOADING_DATA") : CYLocalize("LOADING_DATA"))];
7300 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7303 [self removeProgressHUD:hud];
7307 [essential_ removeAllObjects];
7308 [broken_ removeAllObjects];
7310 NSArray *packages = [database_ packages];
7311 for (Package *package in packages) {
7313 [broken_ addObject:package];
7314 if ([package upgradableAndEssential:NO]) {
7315 if ([package essential])
7316 [essential_ addObject:package];
7322 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7323 [buttonbar_ setBadgeValue:badge forButton:3];
7324 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7325 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7326 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7327 [self setApplicationBadge:badge];
7329 [self setApplicationBadgeString:badge];
7331 [buttonbar_ setBadgeValue:nil forButton:3];
7332 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7333 [buttonbar_ setBadgeAnimated:NO forButton:3];
7334 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7335 [self removeApplicationBadge];
7336 else // XXX: maybe use setApplicationBadgeString also?
7337 [self setApplicationIconBadgeNumber:0];
7341 [buttonbar_ setBadgeValue:nil forButton:4];
7345 // XXX: what is this line of code for?
7346 if ([packages count] == 0);
7347 else if (Loaded_ || ManualRefresh) loaded:
7352 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7353 NSTimeInterval interval([update timeIntervalSinceNow]);
7354 if (interval <= 0 && interval > -600)
7362 - (void) _saveConfig {
7365 NSString *error(nil);
7366 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7368 NSError *error(nil);
7369 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7370 NSLog(@"failure to save metadata data: %@", error);
7373 NSLog(@"failure to serialize metadata: %@", error);
7381 - (void) updateData {
7384 /* XXX: this is just stupid */
7385 if (tag_ != 2 && sections_ != nil)
7386 [sections_ reloadData];
7387 if (tag_ != 3 && changes_ != nil)
7388 [changes_ reloadData];
7389 if (tag_ != 5 && search_ != nil)
7390 [search_ reloadData];
7400 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7401 _assert(file != NULL);
7403 NSArray *keys = [Sources_ allKeys];
7405 for (NSString *key in keys) {
7406 NSDictionary *source = [Sources_ objectForKey:key];
7408 fprintf(file, "%s %s %s\n",
7409 [[source objectForKey:@"Type"] UTF8String],
7410 [[source objectForKey:@"URI"] UTF8String],
7411 [[source objectForKey:@"Distribution"] UTF8String]
7420 detachNewThreadSelector:@selector(update_)
7423 title:CYLocalize("UPDATING_SOURCES")
7427 - (void) reloadData {
7428 @synchronized (self) {
7429 if (confirm_ == nil)
7435 pkgProblemResolver *resolver = [database_ resolver];
7437 resolver->InstallProtect();
7438 if (!resolver->Resolve(true))
7442 - (void) popUpBook:(RVBook *)book {
7443 [underlay_ popSubview:book];
7446 - (CGRect) popUpBounds {
7447 return [underlay_ bounds];
7451 [database_ prepare];
7453 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7454 [confirm_ setDelegate:self];
7456 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7457 [page setDelegate:self];
7459 [confirm_ setPage:page];
7460 [self popUpBook:confirm_];
7464 @synchronized (self) {
7469 - (void) clearPackage:(Package *)package {
7470 @synchronized (self) {
7477 - (void) installPackage:(Package *)package {
7478 @synchronized (self) {
7485 - (void) removePackage:(Package *)package {
7486 @synchronized (self) {
7493 - (void) distUpgrade {
7494 @synchronized (self) {
7495 [database_ upgrade];
7501 [self slideUp:[[[UIActionSheet alloc]
7503 buttons:[NSArray arrayWithObjects:CYLocalize("CONTINUE_QUEUING"), CYLocalize("CANCEL_CLEAR"), nil]
7504 defaultButtonIndex:1
7511 @synchronized (self) {
7514 if (confirm_ != nil) {
7522 [overlay_ removeFromSuperview];
7526 detachNewThreadSelector:@selector(perform)
7529 title:CYLocalize("RUNNING")
7533 - (void) bootstrap_ {
7535 [database_ upgrade];
7536 [database_ prepare];
7537 [database_ perform];
7540 /* XXX: replace and localize */
7541 - (void) bootstrap {
7543 detachNewThreadSelector:@selector(bootstrap_)
7546 title:@"Bootstrap Install"
7550 - (void) progressViewIsComplete:(ProgressView *)progress {
7551 if (confirm_ != nil) {
7552 [underlay_ addSubview:overlay_];
7553 [confirm_ popFromSuperviewAnimated:NO];
7559 - (void) setPage:(RVPage *)page {
7560 [page resetViewAnimated:NO];
7561 [page setDelegate:self];
7562 [book_ setPage:page];
7565 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7566 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7567 [browser loadURL:url];
7571 - (void) _setHomePage {
7572 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7575 - (SectionsView *) sectionsView {
7576 if (sections_ == nil)
7577 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7581 - (void) buttonBarItemTapped:(id)sender {
7582 unsigned tag = [sender tag];
7584 [book_ resetViewAnimated:YES];
7586 } else if (tag_ == 2 && tag != 2)
7587 [[self sectionsView] resetView];
7590 case 1: [self _setHomePage]; break;
7592 case 2: [self setPage:[self sectionsView]]; break;
7593 case 3: [self setPage:changes_]; break;
7594 case 4: [self setPage:manage_]; break;
7595 case 5: [self setPage:search_]; break;
7597 default: _assert(false);
7603 - (void) applicationWillSuspend {
7605 [super applicationWillSuspend];
7608 - (void) askForSettings {
7609 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
7611 UIActionSheet *role = [[[UIActionSheet alloc]
7612 initWithTitle:CYLocalize("WHO_ARE_YOU")
7613 buttons:[NSArray arrayWithObjects:
7614 [NSString stringWithFormat:parenthetical, CYLocalize("USER"), CYLocalize("USER_EX")],
7615 [NSString stringWithFormat:parenthetical, CYLocalize("HACKER"), CYLocalize("HACKER_EX")],
7616 [NSString stringWithFormat:parenthetical, CYLocalize("DEVELOPER"), CYLocalize("DEVELOPER_EX")],
7618 defaultButtonIndex:-1
7623 [role setBodyText:CYLocalize("ROLE_EX")];
7624 [role popupAlertAnimated:YES];
7627 - (void) setPackageView:(PackageView *)view {
7629 [view setPackage:nil];
7630 if ([details_ count] < 3)
7631 [details_ addObject:view];
7635 - (PackageView *) _packageView {
7636 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7639 - (PackageView *) packageView {
7641 size_t count([details_ count]);
7644 view = [self _packageView];
7646 [details_ addObject:[self _packageView]];
7648 view = [[[details_ lastObject] retain] autorelease];
7649 [details_ removeLastObject];
7659 [self setStatusBarShowsProgress:NO];
7660 [self removeProgressHUD:hud_];
7665 pid_t pid = ExecFork();
7667 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7668 perror("launchctl stop");
7675 [self askForSettings];
7680 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7682 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7683 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7684 0, 0, screenrect.size.width, screenrect.size.height - 48
7685 ) database:database_];
7687 [book_ setDelegate:self];
7689 [overlay_ addSubview:book_];
7691 NSArray *buttonitems = [NSArray arrayWithObjects:
7692 [NSDictionary dictionaryWithObjectsAndKeys:
7693 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7694 @"home-up.png", kUIButtonBarButtonInfo,
7695 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7696 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7697 self, kUIButtonBarButtonTarget,
7698 @"Cydia", kUIButtonBarButtonTitle,
7699 @"0", kUIButtonBarButtonType,
7702 [NSDictionary dictionaryWithObjectsAndKeys:
7703 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7704 @"install-up.png", kUIButtonBarButtonInfo,
7705 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7706 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7707 self, kUIButtonBarButtonTarget,
7708 CYLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7709 @"0", kUIButtonBarButtonType,
7712 [NSDictionary dictionaryWithObjectsAndKeys:
7713 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7714 @"changes-up.png", kUIButtonBarButtonInfo,
7715 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7716 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7717 self, kUIButtonBarButtonTarget,
7718 CYLocalize("CHANGES"), kUIButtonBarButtonTitle,
7719 @"0", kUIButtonBarButtonType,
7722 [NSDictionary dictionaryWithObjectsAndKeys:
7723 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7724 @"manage-up.png", kUIButtonBarButtonInfo,
7725 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7726 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7727 self, kUIButtonBarButtonTarget,
7728 CYLocalize("MANAGE"), kUIButtonBarButtonTitle,
7729 @"0", kUIButtonBarButtonType,
7732 [NSDictionary dictionaryWithObjectsAndKeys:
7733 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7734 @"search-up.png", kUIButtonBarButtonInfo,
7735 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7736 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7737 self, kUIButtonBarButtonTarget,
7738 CYLocalize("SEARCH"), kUIButtonBarButtonTitle,
7739 @"0", kUIButtonBarButtonType,
7743 buttonbar_ = [[UIToolbar alloc]
7745 withFrame:CGRectMake(
7746 0, screenrect.size.height - ButtonBarHeight_,
7747 screenrect.size.width, ButtonBarHeight_
7749 withItemList:buttonitems
7752 [buttonbar_ setDelegate:self];
7753 [buttonbar_ setBarStyle:1];
7754 [buttonbar_ setButtonBarTrackingMode:2];
7756 int buttons[5] = {1, 2, 3, 4, 5};
7757 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7758 [buttonbar_ showButtonGroup:0 withDuration:0];
7760 for (int i = 0; i != 5; ++i)
7761 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7762 i * 64 + 2, 1, 60, ButtonBarHeight_
7765 [buttonbar_ showSelectionForButton:1];
7766 [overlay_ addSubview:buttonbar_];
7768 [UIKeyboard initImplementationNow];
7769 CGSize keysize = [UIKeyboard defaultSize];
7770 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7771 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7772 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
7773 [overlay_ addSubview:keyboard_];
7776 [underlay_ addSubview:overlay_];
7780 [self sectionsView];
7781 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7782 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7784 manage_ = (ManageView *) [[self
7785 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7786 withClass:[ManageView class]
7789 details_ = [[NSMutableArray alloc] initWithCapacity:4];
7790 [details_ addObject:[self _packageView]];
7791 [details_ addObject:[self _packageView]];
7798 [self _setHomePage];
7801 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7802 NSString *context([sheet context]);
7804 if ([context isEqualToString:@"missing"])
7806 else if ([context isEqualToString:@"cancel"]) {
7824 @synchronized (self) {
7829 [buttonbar_ setBadgeValue:CYLocalize("Q_D") forButton:4];
7833 if (confirm_ != nil) {
7838 } else if ([context isEqualToString:@"fixhalf"]) {
7841 @synchronized (self) {
7842 for (Package *broken in broken_) {
7845 NSString *id = [broken id];
7846 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7847 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7848 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7849 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7858 [broken_ removeAllObjects];
7867 } else if ([context isEqualToString:@"role"]) {
7869 case 1: Role_ = @"User"; break;
7870 case 2: Role_ = @"Hacker"; break;
7871 case 3: Role_ = @"Developer"; break;
7878 bool reset = Settings_ != nil;
7880 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7884 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7894 } else if ([context isEqualToString:@"upgrade"]) {
7897 @synchronized (self) {
7898 for (Package *essential in essential_)
7899 [essential install];
7922 - (void) reorganize { _pooled
7923 system("/usr/libexec/cydia/free.sh");
7924 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
7927 - (void) applicationSuspend:(__GSEvent *)event {
7928 if (hud_ == nil && ![progress_ isRunning])
7929 [super applicationSuspend:event];
7932 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7934 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7937 - (void) _setSuspended:(BOOL)value {
7939 [super _setSuspended:value];
7942 - (UIProgressHUD *) addProgressHUD {
7943 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
7944 [window_ setUserInteractionEnabled:NO];
7946 [progress_ addSubview:hud];
7950 - (void) removeProgressHUD:(UIProgressHUD *)hud {
7952 [hud removeFromSuperview];
7953 [window_ setUserInteractionEnabled:YES];
7956 - (void) openMailToURL:(NSURL *)url {
7957 // XXX: this makes me sad
7959 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
7961 [UIApp openURL:url];// asPanel:YES];
7965 - (void) clearFirstResponder {
7966 if (id responder = [window_ firstResponder])
7967 [responder resignFirstResponder];
7970 - (RVPage *) pageForPackage:(NSString *)name {
7971 if (Package *package = [database_ packageWithName:name]) {
7972 PackageView *view([self packageView]);
7973 [view setPackage:package];
7976 UIActionSheet *sheet = [[[UIActionSheet alloc]
7977 initWithTitle:CYLocalize("CANNOT_LOCATE_PACKAGE")
7978 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
7979 defaultButtonIndex:0
7984 [sheet setBodyText:[NSString stringWithFormat:CYLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
7986 [sheet popupAlertAnimated:YES];
7991 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
7995 NSString *scheme([[url scheme] lowercaseString]);
7996 if (![scheme isEqualToString:@"cydia"])
7998 NSString *path([url absoluteString]);
7999 if ([path length] < 8)
8001 path = [path substringFromIndex:8];
8002 if (![path hasPrefix:@"/"])
8003 path = [@"/" stringByAppendingString:path];
8005 if ([path isEqualToString:@"/add-source"])
8006 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8007 else if ([path isEqualToString:@"/storage"])
8008 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[BrowserView class]];
8009 else if ([path isEqualToString:@"/sources"])
8010 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8011 else if ([path isEqualToString:@"/packages"])
8012 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8013 else if ([path hasPrefix:@"/url/"])
8014 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[BrowserView class]];
8015 else if ([path hasPrefix:@"/launch/"])
8016 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8017 else if ([path hasPrefix:@"/package-settings/"])
8018 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8019 else if ([path hasPrefix:@"/package-signature/"])
8020 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8021 else if ([path hasPrefix:@"/package/"])
8022 return [self pageForPackage:[path substringFromIndex:9]];
8023 else if ([path hasPrefix:@"/files/"]) {
8024 NSString *name = [path substringFromIndex:7];
8026 if (Package *package = [database_ packageWithName:name]) {
8027 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8028 [files setPackage:package];
8036 - (void) applicationOpenURL:(NSURL *)url {
8037 [super applicationOpenURL:url];
8039 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8040 [self setPage:page];
8041 [buttonbar_ showSelectionForButton:tag];
8046 - (void) applicationDidFinishLaunching:(id)unused {
8048 Font12_ = [[UIFont systemFontOfSize:12] retain];
8049 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8050 Font14_ = [[UIFont systemFontOfSize:14] retain];
8051 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8052 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8056 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8057 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8059 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8061 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8062 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
8064 [window_ orderFront:self];
8065 [window_ makeKey:self];
8066 [window_ setHidden:NO];
8068 database_ = [Database sharedInstance];
8069 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8070 [database_ setDelegate:progress_];
8071 [window_ setContentView:progress_];
8073 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8074 [progress_ setContentView:underlay_];
8076 [progress_ resetView];
8079 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8080 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8081 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8082 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8083 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8084 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
8085 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
8087 [self setIdleTimerDisabled:YES];
8089 hud_ = [[self addProgressHUD] retain];
8090 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8092 [self setStatusBarShowsProgress:YES];
8095 detachNewThreadSelector:@selector(reorganize)
8103 - (void) showKeyboard:(BOOL)show {
8104 CGSize keysize = [UIKeyboard defaultSize];
8105 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8106 CGRect keyup = keydown;
8107 keyup.origin.y -= keysize.height;
8109 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
8110 [animation setSignificantRectFields:2];
8113 [animation setStartFrame:keydown];
8114 [animation setEndFrame:keyup];
8115 [keyboard_ activate];
8117 [animation setStartFrame:keyup];
8118 [animation setEndFrame:keydown];
8119 [keyboard_ deactivate];
8122 [[UIAnimator sharedAnimator]
8123 addAnimations:[NSArray arrayWithObjects:animation, nil]
8124 withDuration:KeyboardTime_
8129 - (void) slideUp:(UIActionSheet *)alert {
8131 [alert presentSheetFromButtonBar:buttonbar_];
8133 [alert presentSheetInView:overlay_];
8138 void AddPreferences(NSString *plist) { _pooled
8139 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
8140 _assert(settings != NULL);
8141 NSMutableArray *items = [settings objectForKey:@"items"];
8145 for (NSMutableDictionary *item in items) {
8146 NSString *label = [item objectForKey:@"label"];
8147 if (label != nil && [label isEqualToString:@"Cydia"]) {
8154 for (size_t i(0); i != [items count]; ++i) {
8155 NSDictionary *item([items objectAtIndex:i]);
8156 NSString *label = [item objectForKey:@"label"];
8157 if (label != nil && [label isEqualToString:@"General"]) {
8158 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
8159 @"CydiaSettings", @"bundle",
8160 @"PSLinkCell", @"cell",
8161 [NSNumber numberWithBool:YES], @"hasIcon",
8162 [NSNumber numberWithBool:YES], @"isController",
8164 nil] atIndex:(i + 1)];
8170 _assert([settings writeToFile:plist atomically:YES] == YES);
8175 id Alloc_(id self, SEL selector) {
8176 id object = alloc_(self, selector);
8177 lprintf("[%s]A-%p\n", self->isa->name, object);
8182 id Dealloc_(id self, SEL selector) {
8183 id object = dealloc_(self, selector);
8184 lprintf("[%s]D-%p\n", self->isa->name, object);
8188 Class $WebDefaultUIKitDelegate;
8190 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
8192 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
8193 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8194 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8195 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
8198 int main(int argc, char *argv[]) { _pooled
8201 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8203 /* Library Hacks {{{ */
8204 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8206 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8207 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8208 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8209 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8210 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8213 /* Set Locale {{{ */
8214 Locale_ = CFLocaleCopyCurrent();
8215 Languages_ = [NSLocale preferredLanguages];
8216 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8217 //NSLog(@"%@", [Languages_ description]);
8219 if (Languages_ == nil || [Languages_ count] == 0)
8222 lang = [[Languages_ objectAtIndex:0] UTF8String];
8223 setenv("LANG", lang, true);
8224 //std::setlocale(LC_ALL, lang);
8225 NSLog(@"Setting Language: %s", lang);
8228 // XXX: apr_app_initialize?
8231 /* Parse Arguments {{{ */
8232 bool substrate(false);
8238 for (int argi(1); argi != argc; ++argi)
8239 if (strcmp(argv[argi], "--") == 0) {
8241 argv[argi] = argv[0];
8247 for (int argi(1); argi != arge; ++argi)
8248 if (strcmp(args[argi], "--bootstrap") == 0)
8250 else if (strcmp(args[argi], "--substrate") == 0)
8253 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8258 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
8259 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
8260 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
8261 Sounds_Keyboard_ = [keyboard boolValue];
8264 App_ = [[NSBundle mainBundle] bundlePath];
8265 Home_ = NSHomeDirectory();
8270 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8271 alloc_ = alloc->method_imp;
8272 alloc->method_imp = (IMP) &Alloc_;*/
8274 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8275 dealloc_ = dealloc->method_imp;
8276 dealloc->method_imp = (IMP) &Dealloc_;*/
8281 size = sizeof(maxproc);
8282 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8283 perror("sysctlbyname(\"kern.maxproc\", ?)");
8284 else if (maxproc < 64) {
8286 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8287 perror("sysctlbyname(\"kern.maxproc\", #)");
8290 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8291 char *machine = new char[size];
8292 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8293 perror("sysctlbyname(\"hw.machine\", ?)");
8297 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8299 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8300 Build_ = [system objectForKey:@"ProductBuildVersion"];
8301 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8302 Product_ = [info objectForKey:@"SafariProductVersion"];
8303 Safari_ = [info objectForKey:@"CFBundleVersion"];
8306 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8307 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
8309 /* Load Database {{{ */
8311 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8313 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8316 if (Metadata_ == NULL)
8317 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8319 Settings_ = [Metadata_ objectForKey:@"Settings"];
8321 Packages_ = [Metadata_ objectForKey:@"Packages"];
8322 Sections_ = [Metadata_ objectForKey:@"Sections"];
8323 Sources_ = [Metadata_ objectForKey:@"Sources"];
8326 if (Settings_ != nil)
8327 Role_ = [Settings_ objectForKey:@"Role"];
8329 if (Packages_ == nil) {
8330 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8331 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8334 if (Sections_ == nil) {
8335 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8336 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8339 if (Sources_ == nil) {
8340 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8341 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8346 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8349 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8350 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8351 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8352 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8354 if (access("/User", F_OK) != 0) {
8356 system("/usr/libexec/cydia/firmware.sh");
8360 _assert([[NSFileManager defaultManager]
8361 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8362 withIntermediateDirectories:YES
8367 if (access("/tmp/cydia.chk", F_OK) == 0) {
8368 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8369 _assert(errno == ENOENT);
8370 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8371 _assert(errno == ENOENT);
8374 _assert(pkgInitConfig(*_config));
8375 _assert(pkgInitSystem(*_config, _system));
8378 _config->Set("APT::Acquire::Translation", lang);
8379 _config->Set("Acquire::http::Timeout", 15);
8380 _config->Set("Acquire::http::MaxParallel", 4);
8382 /* Color Choices {{{ */
8383 space_ = CGColorSpaceCreateDeviceRGB();
8385 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8386 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8387 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8388 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8389 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8390 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8391 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8392 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8393 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8394 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8395 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8396 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8397 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8398 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8399 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8402 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8403 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8406 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8408 /* UIKit Configuration {{{ */
8409 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8410 if ($GSFontSetUseLegacyFontMetrics != NULL)
8411 $GSFontSetUseLegacyFontMetrics(YES);
8413 UIKeyboardDisableAutomaticAppearance();
8417 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8419 CGColorSpaceRelease(space_);