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 depiction_;
1427 CYString description_;
1433 CYString distribution_;
1439 CYString defaultIcon_;
1441 NSDictionary *record_;
1445 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1447 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1449 - (NSString *) depictionForPackage:(NSString *)package;
1450 - (NSString *) supportForPackage:(NSString *)package;
1452 - (NSDictionary *) record;
1456 - (NSString *) distribution;
1457 - (NSString *) type;
1459 - (NSString *) host;
1461 - (NSString *) name;
1462 - (NSString *) description;
1463 - (NSString *) label;
1464 - (NSString *) origin;
1465 - (NSString *) version;
1467 - (NSString *) defaultIcon;
1471 @implementation Source
1475 distribution_.clear();
1478 description_.clear();
1484 defaultIcon_.clear();
1486 if (record_ != nil) {
1502 + (NSArray *) _attributeKeys {
1503 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1506 - (NSArray *) attributeKeys {
1507 return [[self class] _attributeKeys];
1510 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1511 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1514 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1517 trusted_ = index->IsTrusted();
1519 uri_.set(pool, index->GetURI());
1520 distribution_.set(pool, index->GetDist());
1521 type_.set(pool, index->GetType());
1523 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1524 if (dindex != NULL) {
1526 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1529 pkgTagFile tags(&fd);
1531 pkgTagSection section;
1538 {"default-icon", &defaultIcon_},
1539 {"depiction", &depiction_},
1540 {"description", &description_},
1542 {"origin", &origin_},
1543 {"support", &support_},
1544 {"version", &version_},
1547 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1548 const char *start, *end;
1550 if (section.Find(names[i].name_, start, end)) {
1551 CYString &value(*names[i].value_);
1552 value.set(pool, start, end - start);
1558 record_ = [Sources_ objectForKey:[self key]];
1560 record_ = [record_ retain];
1562 host_ = [[[[NSURL URLWithString:uri_] host] lowercaseString] retain];
1565 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1566 if ((self = [super init]) != nil) {
1567 [self setMetaIndex:index inPool:pool];
1571 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1572 NSDictionary *lhr = [self record];
1573 NSDictionary *rhr = [source record];
1576 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1578 NSString *lhs = [self name];
1579 NSString *rhs = [source name];
1581 if ([lhs length] != 0 && [rhs length] != 0) {
1582 unichar lhc = [lhs characterAtIndex:0];
1583 unichar rhc = [rhs characterAtIndex:0];
1585 if (isalpha(lhc) && !isalpha(rhc))
1586 return NSOrderedAscending;
1587 else if (!isalpha(lhc) && isalpha(rhc))
1588 return NSOrderedDescending;
1591 return [lhs compare:rhs options:LaxCompareOptions_];
1594 - (NSString *) depictionForPackage:(NSString *)package {
1595 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1598 - (NSString *) supportForPackage:(NSString *)package {
1599 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1602 - (NSDictionary *) record {
1610 - (NSString *) uri {
1614 - (NSString *) distribution {
1615 return distribution_;
1618 - (NSString *) type {
1622 - (NSString *) key {
1623 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1626 - (NSString *) host {
1630 - (NSString *) name {
1631 return origin_.empty() ? host_ : origin_;
1634 - (NSString *) description {
1635 return description_;
1638 - (NSString *) label {
1639 return label_.empty() ? host_ : label_;
1642 - (NSString *) origin {
1646 - (NSString *) version {
1650 - (NSString *) defaultIcon {
1651 return defaultIcon_;
1656 /* Relationship Class {{{ */
1657 @interface Relationship : NSObject {
1662 - (NSString *) type;
1664 - (NSString *) name;
1668 @implementation Relationship
1676 - (NSString *) type {
1684 - (NSString *) name {
1691 /* Package Class {{{ */
1692 @interface Package : NSObject {
1696 pkgCache::VerIterator version_;
1697 pkgCache::PkgIterator iterator_;
1698 _transient Database *database_;
1699 pkgCache::VerFileIterator file_;
1706 NSString *section$_;
1711 NSString *installed_;
1717 CYString depiction_;
1727 NSMutableArray *tags_;
1730 NSArray *relationships_;
1732 NSMutableDictionary *metadata_;
1733 _transient NSDate *firstSeen_;
1734 _transient NSDate *lastSeen_;
1738 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1739 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1741 - (pkgCache::PkgIterator) iterator;
1744 - (NSString *) section;
1745 - (NSString *) simpleSection;
1747 - (NSString *) longSection;
1748 - (NSString *) shortSection;
1752 - (Address *) maintainer;
1754 - (NSString *) longDescription;
1755 - (NSString *) shortDescription;
1758 - (NSMutableDictionary *) metadata;
1760 - (BOOL) subscribed;
1763 - (NSString *) latest;
1764 - (NSString *) installed;
1767 - (BOOL) upgradableAndEssential:(BOOL)essential;
1770 - (BOOL) unfiltered;
1774 - (BOOL) halfConfigured;
1775 - (BOOL) halfInstalled;
1777 - (NSString *) mode;
1780 - (NSString *) name;
1782 - (NSString *) homepage;
1783 - (NSString *) depiction;
1784 - (Address *) author;
1786 - (NSString *) support;
1788 - (NSArray *) files;
1789 - (NSArray *) relationships;
1790 - (NSArray *) warnings;
1791 - (NSArray *) applications;
1793 - (Source *) source;
1794 - (NSString *) role;
1796 - (BOOL) matches:(NSString *)text;
1798 - (bool) hasSupportingRole;
1799 - (BOOL) hasTag:(NSString *)tag;
1800 - (NSString *) primaryPurpose;
1801 - (NSArray *) purposes;
1802 - (bool) isCommercial;
1804 - (CYString &) cyname;
1806 - (uint32_t) compareBySection:(NSArray *)sections;
1808 - (uint32_t) compareForChanges;
1813 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1814 - (bool) isInstalledAndVisible:(NSNumber *)number;
1815 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1816 - (bool) isVisibleInSource:(Source *)source;
1820 uint32_t PackageChangesRadix(Package *self, void *) {
1825 uint32_t timestamp : 30;
1826 uint32_t ignored : 1;
1827 uint32_t upgradable : 1;
1831 bool upgradable([self upgradableAndEssential:YES]);
1832 value.bits.upgradable = upgradable ? 1 : 0;
1835 value.bits.timestamp = 0;
1836 value.bits.ignored = [self ignored] ? 0 : 1;
1837 value.bits.upgradable = 1;
1839 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1840 value.bits.ignored = 0;
1841 value.bits.upgradable = 0;
1844 return _not(uint32_t) - value.key;
1847 _finline static void Stifle(uint8_t &value) {
1850 uint32_t PackagePrefixRadix(Package *self, void *context) {
1851 size_t offset(reinterpret_cast<size_t>(context));
1852 CYString &name([self cyname]);
1854 size_t size(name.size());
1857 char *text(name.data());
1860 if (!isdigit(text[0]))
1864 while (size != digits && isdigit(text[digits]))
1874 if (offset == 0 && zeros != 0) {
1875 memset(data, '0', zeros);
1876 memcpy(data + zeros, text, 4 - zeros);
1878 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1879 if (size <= offset - zeros)
1882 text += offset - zeros;
1883 size -= offset - zeros;
1886 memcpy(data, text, 4);
1888 memcpy(data, text, size);
1889 memset(data + size, 0, 4 - size);
1892 for (size_t i(0); i != 4; ++i)
1893 if (isalpha(data[i]))
1898 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1900 /* XXX: ntohl may be more honest */
1901 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1904 CYString &(*PackageName)(Package *self, SEL sel);
1906 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1907 _profile(PackageNameCompare)
1908 CYString &lhi(PackageName(lhs, @selector(cyname)));
1909 CYString &rhi(PackageName(rhs, @selector(cyname)));
1910 CFStringRef lhn(lhi), rhn(rhi);
1912 _profile(PackageNameCompare$NumbersLast)
1913 if (!lhi.empty() && !rhi.empty()) {
1914 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1915 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1916 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1917 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1918 return lha ? NSOrderedAscending : NSOrderedDescending;
1922 CFIndex length = CFStringGetLength(lhn);
1924 _profile(PackageNameCompare$Compare)
1925 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1930 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1931 return PackageNameCompare(*lhs, *rhs, context);
1934 struct PackageNameOrdering :
1935 std::binary_function<Package *, Package *, bool>
1937 _finline bool operator ()(Package *lhs, Package *rhs) const {
1938 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1942 @implementation Package
1944 - (NSString *) description {
1945 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1951 if (section$_ != nil)
1952 [section$_ release];
1956 if (installed_ != nil)
1957 [installed_ release];
1959 if (sponsor$_ != nil)
1960 [sponsor$_ release];
1961 if (author$_ != nil)
1968 if (relationships_ != nil)
1969 [relationships_ release];
1970 if (metadata_ != nil)
1971 [metadata_ release];
1976 + (NSString *) webScriptNameForSelector:(SEL)selector {
1977 if (selector == @selector(hasTag:))
1983 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1984 return [self webScriptNameForSelector:selector] == nil;
1987 + (NSArray *) _attributeKeys {
1988 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];
1991 - (NSArray *) attributeKeys {
1992 return [[self class] _attributeKeys];
1995 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1996 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2006 _profile(Package$parse)
2007 pkgRecords::Parser *parser;
2009 _profile(Package$parse$Lookup)
2010 parser = &[database_ records]->Lookup(file_);
2015 _profile(Package$parse$Find)
2021 {"depiction", &depiction_},
2022 {"homepage", &homepage_},
2023 {"website", &website},
2024 {"support", &support_},
2025 {"sponsor", &sponsor_},
2026 {"author", &author_},
2029 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2030 const char *start, *end;
2032 if (parser->Find(names[i].name_, start, end)) {
2033 CYString &value(*names[i].value_);
2034 _profile(Package$parse$Value)
2035 value.set(pool_, start, end - start);
2041 _profile(Package$parse$Tagline)
2042 const char *start, *end;
2043 if (parser->ShortDesc(start, end)) {
2044 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2047 while (stop != start && stop[-1] == '\r')
2049 tagline_.set(pool_, start, stop - start);
2053 _profile(Package$parse$Retain)
2054 if (!homepage_.empty())
2055 homepage_ = website;
2056 if (homepage_ == depiction_)
2062 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2063 if ((self = [super init]) != nil) {
2064 _profile(Package$initWithVersion)
2065 @synchronized (database) {
2066 era_ = [database era];
2070 iterator_ = version.ParentPkg();
2071 database_ = database;
2073 _profile(Package$initWithVersion$Latest)
2074 latest_ = (NSString *) StripVersion(version_.VerStr());
2077 pkgCache::VerIterator current;
2078 _profile(Package$initWithVersion$Versions)
2079 current = iterator_.CurrentVer();
2081 installed_ = (NSString *) StripVersion(current.VerStr());
2083 if (!version_.end())
2084 file_ = version_.FileList();
2086 pkgCache &cache([database_ cache]);
2087 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2091 _profile(Package$initWithVersion$Name)
2092 id_.set(pool_, iterator_.Name());
2093 name_.set(pool, iterator_.Display());
2097 _profile(Package$initWithVersion$Source)
2098 source_ = [database_ getSource:file_.File()];
2107 _profile(Package$initWithVersion$Tags)
2108 pkgCache::TagIterator tag(iterator_.TagList());
2110 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2112 const char *name(tag.Name());
2113 [tags_ addObject:(NSString *)CFCString(name)];
2114 if (role_ == nil && strncmp(name, "role::", 6) == 0 && strcmp(name, "role::leaper") != 0)
2115 role_ = (NSString *) CFCString(name + 6);
2116 if (visible_ && strncmp(name, "require::", 9) == 0 && (
2121 } while (!tag.end());
2125 bool changed(false);
2126 NSString *key([id_ lowercaseString]);
2128 _profile(Package$initWithVersion$Metadata)
2129 metadata_ = [Packages_ objectForKey:key];
2131 if (metadata_ == nil) {
2134 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2135 firstSeen_, @"FirstSeen",
2136 latest_, @"LastVersion",
2141 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2142 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2144 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2145 subscribed_ = [subscribed boolValue];
2147 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2149 if (firstSeen_ == nil) {
2150 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2151 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2155 if (version == nil) {
2156 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2158 } else if (![version isEqualToString:latest_]) {
2159 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2161 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2166 metadata_ = [metadata_ retain];
2169 [Packages_ setObject:metadata_ forKey:key];
2174 _profile(Package$initWithVersion$Section)
2175 section_.set(pool_, iterator_.Section());
2178 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2179 visible_ &&= [self hasSupportingRole] && [self unfiltered];
2180 } _end } return self;
2183 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2184 pkgCache::VerIterator version;
2186 _profile(Package$packageWithIterator$GetCandidateVer)
2187 version = [database policy]->GetCandidateVer(iterator);
2193 return [[[Package alloc]
2194 initWithVersion:version
2201 - (pkgCache::PkgIterator) iterator {
2205 - (NSString *) section {
2206 if (section$_ == nil) {
2207 if (section_.empty())
2210 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2211 NSString *name(section_);
2214 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2215 if (NSString *rename = [value objectForKey:@"Rename"]) {
2220 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2224 - (NSString *) simpleSection {
2225 if (NSString *section = [self section])
2226 return Simplify(section);
2231 - (NSString *) longSection {
2232 return LocalizeSection([self section]);
2235 - (NSString *) shortSection {
2236 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2239 - (NSString *) uri {
2242 pkgIndexFile *index;
2243 pkgCache::PkgFileIterator file(file_.File());
2244 if (![database_ list].FindIndex(file, index))
2246 return [NSString stringWithUTF8String:iterator_->Path];
2247 //return [NSString stringWithUTF8String:file.Site()];
2248 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2252 - (Address *) maintainer {
2255 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2256 const std::string &maintainer(parser->Maintainer());
2257 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2261 return version_.end() ? 0 : version_->InstalledSize;
2264 - (NSString *) longDescription {
2267 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2268 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2270 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2271 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2272 if ([lines count] < 2)
2275 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2276 for (size_t i(1), e([lines count]); i != e; ++i) {
2277 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2278 [trimmed addObject:trim];
2281 return [trimmed componentsJoinedByString:@"\n"];
2284 - (NSString *) shortDescription {
2289 _profile(Package$index)
2290 CFStringRef name((CFStringRef) [self name]);
2291 if (CFStringGetLength(name) == 0)
2293 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2294 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2296 return toupper(character);
2300 - (NSMutableDictionary *) metadata {
2305 if (subscribed_ && lastSeen_ != nil)
2310 - (BOOL) subscribed {
2315 NSDictionary *metadata([self metadata]);
2316 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2317 return [ignored boolValue];
2322 - (NSString *) latest {
2326 - (NSString *) installed {
2331 return !version_.end();
2334 - (BOOL) upgradableAndEssential:(BOOL)essential {
2335 _profile(Package$upgradableAndEssential)
2336 pkgCache::VerIterator current(iterator_.CurrentVer());
2338 return essential && essential_ && visible_;
2340 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2344 - (BOOL) essential {
2349 return [database_ cache][iterator_].InstBroken();
2352 - (BOOL) unfiltered {
2353 NSString *section([self section]);
2354 return section == nil || isSectionVisible(section);
2362 unsigned char current(iterator_->CurrentState);
2363 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2366 - (BOOL) halfConfigured {
2367 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2370 - (BOOL) halfInstalled {
2371 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2375 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2376 return state.Mode != pkgDepCache::ModeKeep;
2379 - (NSString *) mode {
2380 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2382 switch (state.Mode) {
2383 case pkgDepCache::ModeDelete:
2384 if ((state.iFlags & pkgDepCache::Purge) != 0)
2388 case pkgDepCache::ModeKeep:
2389 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2390 return @"REINSTALL";
2391 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2395 case pkgDepCache::ModeInstall:
2396 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2397 return @"REINSTALL";
2398 else*/ switch (state.Status) {
2400 return @"DOWNGRADE";
2406 return @"NEW_INSTALL";
2419 - (NSString *) name {
2420 return name_.empty() ? id_ : name_;
2423 - (UIImage *) icon {
2424 NSString *section = [self simpleSection];
2428 if ([icon_ hasPrefix:@"file:///"])
2429 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2430 if (icon == nil) if (section != nil)
2431 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2432 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2433 if ([dicon hasPrefix:@"file:///"])
2434 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2436 icon = [UIImage applicationImageNamed:@"unknown.png"];
2440 - (NSString *) homepage {
2444 - (NSString *) depiction {
2445 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2448 - (Address *) sponsor {
2449 if (sponsor$_ == nil) {
2450 if (sponsor_.empty())
2452 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2456 - (Address *) author {
2457 if (author$_ == nil) {
2458 if (author_.empty())
2460 author$_ = [[Address addressWithString:author_] retain];
2464 - (NSString *) support {
2465 return !support_.empty() ? support_ : [[self source] supportForPackage:id_];
2468 - (NSArray *) files {
2469 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2470 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2473 fin.open([path UTF8String]);
2478 while (std::getline(fin, line))
2479 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2484 - (NSArray *) relationships {
2485 return relationships_;
2488 - (NSArray *) warnings {
2489 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2490 const char *name(iterator_.Name());
2492 size_t length(strlen(name));
2493 if (length < 2) invalid:
2494 [warnings addObject:CYLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2495 else for (size_t i(0); i != length; ++i)
2497 /* XXX: technically this is not allowed */
2498 (name[i] < 'A' || name[i] > 'Z') &&
2499 (name[i] < 'a' || name[i] > 'z') &&
2500 (name[i] < '0' || name[i] > '9') &&
2501 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2504 if (strcmp(name, "cydia") != 0) {
2506 bool _private = false;
2509 bool repository = [[self section] isEqualToString:@"Repositories"];
2511 if (NSArray *files = [self files])
2512 for (NSString *file in files)
2513 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2515 else if (!_private && [file isEqualToString:@"/private"])
2517 else if (!stash && [file isEqualToString:@"/var/stash"])
2520 /* XXX: this is not sensitive enough. only some folders are valid. */
2521 if (cydia && !repository)
2522 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2524 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/private"]];
2526 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2529 return [warnings count] == 0 ? nil : warnings;
2532 - (NSArray *) applications {
2533 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2535 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2537 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2538 if (NSArray *files = [self files])
2539 for (NSString *file in files)
2540 if (application_r(file)) {
2541 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2542 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2543 if ([id isEqualToString:me])
2546 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2548 display = application_r[1];
2550 NSString *bundle([file stringByDeletingLastPathComponent]);
2551 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2552 if (icon == nil || [icon length] == 0)
2554 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2556 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2557 [applications addObject:application];
2559 [application addObject:id];
2560 [application addObject:display];
2561 [application addObject:url];
2564 return [applications count] == 0 ? nil : applications;
2567 - (Source *) source {
2569 @synchronized (database_) {
2570 if ([database_ era] != era_ || file_.end())
2573 source_ = [database_ getSource:file_.File()];
2585 - (NSString *) role {
2589 - (BOOL) matches:(NSString *)text {
2595 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2596 if (range.location != NSNotFound)
2599 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2600 if (range.location != NSNotFound)
2603 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2604 if (range.location != NSNotFound)
2610 - (bool) hasSupportingRole {
2613 if ([role_ isEqualToString:@"enduser"])
2615 if ([Role_ isEqualToString:@"User"])
2617 if ([role_ isEqualToString:@"hacker"])
2619 if ([Role_ isEqualToString:@"Hacker"])
2621 if ([role_ isEqualToString:@"developer"])
2623 if ([Role_ isEqualToString:@"Developer"])
2628 - (BOOL) hasTag:(NSString *)tag {
2629 return tags_ == nil ? NO : [tags_ containsObject:tag];
2632 - (NSString *) primaryPurpose {
2633 for (NSString *tag in tags_)
2634 if ([tag hasPrefix:@"purpose::"])
2635 return [tag substringFromIndex:9];
2639 - (NSArray *) purposes {
2640 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2641 for (NSString *tag in tags_)
2642 if ([tag hasPrefix:@"purpose::"])
2643 [purposes addObject:[tag substringFromIndex:9]];
2644 return [purposes count] == 0 ? nil : purposes;
2647 - (bool) isCommercial {
2648 return [self hasTag:@"cydia::commercial"];
2651 - (CYString &) cyname {
2652 return name_.empty() ? id_ : name_;
2655 - (uint32_t) compareBySection:(NSArray *)sections {
2656 NSString *section([self section]);
2657 for (size_t i(0), e([sections count]); i != e; ++i) {
2658 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2662 return _not(uint32_t);
2665 - (uint32_t) compareForChanges {
2670 uint32_t timestamp : 30;
2671 uint32_t ignored : 1;
2672 uint32_t upgradable : 1;
2676 bool upgradable([self upgradableAndEssential:YES]);
2677 value.bits.upgradable = upgradable ? 1 : 0;
2680 value.bits.timestamp = 0;
2681 value.bits.ignored = [self ignored] ? 0 : 1;
2682 value.bits.upgradable = 1;
2684 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2685 value.bits.ignored = 0;
2686 value.bits.upgradable = 0;
2689 return _not(uint32_t) - value.key;
2693 pkgProblemResolver *resolver = [database_ resolver];
2694 resolver->Clear(iterator_);
2695 resolver->Protect(iterator_);
2699 pkgProblemResolver *resolver = [database_ resolver];
2700 resolver->Clear(iterator_);
2701 resolver->Protect(iterator_);
2702 pkgCacheFile &cache([database_ cache]);
2703 cache->MarkInstall(iterator_, false);
2704 pkgDepCache::StateCache &state((*cache)[iterator_]);
2705 if (!state.Install())
2706 cache->SetReInstall(iterator_, true);
2710 pkgProblemResolver *resolver = [database_ resolver];
2711 resolver->Clear(iterator_);
2712 resolver->Protect(iterator_);
2713 resolver->Remove(iterator_);
2714 [database_ cache]->MarkDelete(iterator_, true);
2717 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2718 _profile(Package$isUnfilteredAndSearchedForBy)
2721 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2722 value &= [self unfiltered];
2725 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2726 value &= [self matches:search];
2733 - (bool) isInstalledAndVisible:(NSNumber *)number {
2734 return (![number boolValue] || [self visible]) && [self installed] != nil;
2737 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2738 NSString *section = [self section];
2742 [self installed] == nil && (
2744 section == nil && [name length] == 0 ||
2745 [name isEqualToString:section]
2749 - (bool) isVisibleInSource:(Source *)source {
2750 return [self source] == source && [self visible];
2755 /* Section Class {{{ */
2756 @interface Section : NSObject {
2761 NSString *localized_;
2764 - (NSComparisonResult) compareByLocalized:(Section *)section;
2765 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2766 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2767 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2768 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2769 - (NSString *) name;
2776 - (void) addToCount;
2778 - (void) setCount:(size_t)count;
2779 - (NSString *) localized;
2783 @implementation Section
2787 if (localized_ != nil)
2788 [localized_ release];
2792 - (NSComparisonResult) compareByLocalized:(Section *)section {
2793 NSString *lhs(localized_);
2794 NSString *rhs([section localized]);
2796 /*if ([lhs length] != 0 && [rhs length] != 0) {
2797 unichar lhc = [lhs characterAtIndex:0];
2798 unichar rhc = [rhs characterAtIndex:0];
2800 if (isalpha(lhc) && !isalpha(rhc))
2801 return NSOrderedAscending;
2802 else if (!isalpha(lhc) && isalpha(rhc))
2803 return NSOrderedDescending;
2806 return [lhs compare:rhs options:LaxCompareOptions_];
2809 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2810 if ((self = [self initWithName:name localize:NO]) != nil) {
2811 if (localized != nil)
2812 localized_ = [localized retain];
2816 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2817 return [self initWithName:name row:0 localize:localize];
2820 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2821 if ((self = [super init]) != nil) {
2822 name_ = [name retain];
2826 localized_ = [LocalizeSection(name_) retain];
2830 /* XXX: localize the index thingees */
2831 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2832 if ((self = [super init]) != nil) {
2833 name_ = [(index == '#' ? @"123" : [NSString stringWithCharacters:&index length:1]) retain];
2839 - (NSString *) name {
2859 - (void) addToCount {
2863 - (void) setCount:(size_t)count {
2867 - (NSString *) localized {
2875 static NSArray *Finishes_;
2877 /* Database Implementation {{{ */
2878 @implementation Database
2880 + (Database *) sharedInstance {
2881 static Database *instance;
2882 if (instance == nil)
2883 instance = [[Database alloc] init];
2893 NSRecycleZone(zone_);
2894 // XXX: malloc_destroy_zone(zone_);
2895 apr_pool_destroy(pool_);
2899 - (void) _readCydia:(NSNumber *)fd { _pooled
2900 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2901 std::istream is(&ib);
2904 static Pcre finish_r("^finish:([^:]*)$");
2906 while (std::getline(is, line)) {
2907 const char *data(line.c_str());
2908 size_t size = line.size();
2909 lprintf("C:%s\n", data);
2911 if (finish_r(data, size)) {
2912 NSString *finish = finish_r[1];
2913 int index = [Finishes_ indexOfObject:finish];
2914 if (index != INT_MAX && index > Finish_)
2922 - (void) _readStatus:(NSNumber *)fd { _pooled
2923 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2924 std::istream is(&ib);
2927 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2928 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2930 while (std::getline(is, line)) {
2931 const char *data(line.c_str());
2932 size_t size = line.size();
2933 lprintf("S:%s\n", data);
2935 if (conffile_r(data, size)) {
2936 [delegate_ setConfigurationData:conffile_r[1]];
2937 } else if (strncmp(data, "status: ", 8) == 0) {
2938 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2939 [delegate_ setProgressTitle:string];
2940 } else if (pmstatus_r(data, size)) {
2941 std::string type([pmstatus_r[1] UTF8String]);
2942 NSString *id = pmstatus_r[2];
2944 float percent([pmstatus_r[3] floatValue]);
2945 [delegate_ setProgressPercent:(percent / 100)];
2947 NSString *string = pmstatus_r[4];
2949 if (type == "pmerror")
2950 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2951 withObject:[NSArray arrayWithObjects:string, id, nil]
2954 else if (type == "pmstatus") {
2955 [delegate_ setProgressTitle:string];
2956 } else if (type == "pmconffile")
2957 [delegate_ setConfigurationData:string];
2958 else _assert(false);
2959 } else _assert(false);
2965 - (void) _readOutput:(NSNumber *)fd { _pooled
2966 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2967 std::istream is(&ib);
2970 while (std::getline(is, line)) {
2971 lprintf("O:%s\n", line.c_str());
2972 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2982 - (Package *) packageWithName:(NSString *)name {
2983 if (static_cast<pkgDepCache *>(cache_) == NULL)
2985 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
2986 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
2989 - (Database *) init {
2990 if ((self = [super init]) != nil) {
2997 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
2998 apr_pool_create(&pool_, NULL);
3000 packages_ = [[NSMutableArray alloc] init];
3004 _assert(pipe(fds) != -1);
3007 _config->Set("APT::Keep-Fds::", cydiafd_);
3008 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3011 detachNewThreadSelector:@selector(_readCydia:)
3013 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3016 _assert(pipe(fds) != -1);
3020 detachNewThreadSelector:@selector(_readStatus:)
3022 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3025 _assert(pipe(fds) != -1);
3026 _assert(dup2(fds[0], 0) != -1);
3027 _assert(close(fds[0]) != -1);
3029 input_ = fdopen(fds[1], "a");
3031 _assert(pipe(fds) != -1);
3032 _assert(dup2(fds[1], 1) != -1);
3033 _assert(close(fds[1]) != -1);
3036 detachNewThreadSelector:@selector(_readOutput:)
3038 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3043 - (pkgCacheFile &) cache {
3047 - (pkgDepCache::Policy *) policy {
3051 - (pkgRecords *) records {
3055 - (pkgProblemResolver *) resolver {
3059 - (pkgAcquire &) fetcher {
3063 - (pkgSourceList &) list {
3067 - (NSArray *) packages {
3071 - (NSArray *) sources {
3072 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3073 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3074 [sources addObject:i->second];
3078 - (NSArray *) issues {
3079 if (cache_->BrokenCount() == 0)
3082 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3084 for (Package *package in packages_) {
3085 if (![package broken])
3087 pkgCache::PkgIterator pkg([package iterator]);
3089 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3090 [entry addObject:[package name]];
3091 [issues addObject:entry];
3093 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3097 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3098 pkgCache::DepIterator start;
3099 pkgCache::DepIterator end;
3100 dep.GlobOr(start, end); // ++dep
3102 if (!cache_->IsImportantDep(end))
3104 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3107 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3108 [entry addObject:failure];
3109 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3111 Package *package([self packageWithName:[NSString stringWithUTF8String:start.TargetPkg().Name()]]);
3112 [failure addObject:[package name]];
3114 pkgCache::PkgIterator target(start.TargetPkg());
3115 if (target->ProvidesList != 0)
3116 [failure addObject:@"?"];
3118 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3120 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3121 else if (!cache_[target].CandidateVerIter(cache_).end())
3122 [failure addObject:@"-"];
3123 else if (target->ProvidesList == 0)
3124 [failure addObject:@"!"];
3126 [failure addObject:@"%"];
3130 if (start.TargetVer() != 0)
3131 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3142 - (void) reloadData { _pooled
3143 @synchronized (self) {
3147 [packages_ removeAllObjects];
3173 apr_pool_clear(pool_);
3174 NSRecycleZone(zone_);
3176 int chk(creat("/tmp/cydia.chk", 0644));
3181 if (!cache_.Open(progress_, true)) {
3183 if (!_error->PopMessage(error))
3186 lprintf("cache_.Open():[%s]\n", error.c_str());
3188 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3189 [delegate_ repairWithSelector:@selector(configure)];
3190 else if (error == "The package lists or status file could not be parsed or opened.")
3191 [delegate_ repairWithSelector:@selector(update)];
3192 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3193 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3194 // else if (error == "The list of sources could not be read.")
3195 else _assert(false);
3201 unlink("/tmp/cydia.chk");
3203 now_ = [[NSDate date] retain];
3205 policy_ = new pkgDepCache::Policy();
3206 records_ = new pkgRecords(cache_);
3207 resolver_ = new pkgProblemResolver(cache_);
3208 fetcher_ = new pkgAcquire(&status_);
3211 list_ = new pkgSourceList();
3212 _assert(list_->ReadMainList());
3214 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3215 _assert(pkgApplyStatus(cache_));
3217 if (cache_->BrokenCount() != 0) {
3218 _assert(pkgFixBroken(cache_));
3219 _assert(cache_->BrokenCount() == 0);
3220 _assert(pkgMinimizeUpgrade(cache_));
3225 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3226 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3227 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3228 // XXX: this could be more intelligent
3229 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3230 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3232 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3239 /*std::vector<Package *> packages;
3240 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3241 [packages_ release];
3246 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3247 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3248 //packages.push_back(package);
3249 [packages_ addObject:package];
3253 /*if (packages.empty())
3254 packages_ = [[NSArray alloc] init];
3256 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3259 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3260 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3261 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3269 /*if (!packages.empty())
3270 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3271 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3273 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3275 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3277 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3283 - (void) configure {
3284 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3285 system([dpkg UTF8String]);
3293 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3294 _assert(!_error->PendingError());
3297 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3300 public pkgArchiveCleaner
3303 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3308 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3310 while (_error->PopMessage(error))
3311 lprintf("ArchiveCleaner: %s\n", error.c_str());
3316 pkgRecords records(cache_);
3318 lock_ = new FileFd();
3319 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3320 _assert(!_error->PendingError());
3323 // XXX: explain this with an error message
3324 _assert(list.ReadMainList());
3326 manager_ = (_system->CreatePM(cache_));
3327 _assert(manager_->GetArchives(fetcher_, &list, &records));
3328 _assert(!_error->PendingError());
3332 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3334 _assert(list.ReadMainList());
3335 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3336 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3339 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3344 bool failed = false;
3345 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3346 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3348 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3351 std::string uri = (*item)->DescURI();
3352 std::string error = (*item)->ErrorText;
3354 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3357 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3358 withObject:[NSArray arrayWithObjects:
3359 [NSString stringWithUTF8String:error.c_str()],
3371 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3373 if (_error->PendingError()) {
3378 if (result == pkgPackageManager::Failed) {
3383 if (result != pkgPackageManager::Completed) {
3388 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3390 _assert(list.ReadMainList());
3391 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3392 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3395 if (![before isEqualToArray:after])
3400 _assert(pkgDistUpgrade(cache_));
3404 [self updateWithStatus:status_];
3407 - (NSString *) updateWithStatus:(Status &)status {
3409 _assert(list.ReadMainList());
3412 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3414 if (_error->PendingError()) {
3416 if (!_error->PopMessage(error))
3419 return [NSString stringWithUTF8String:error.c_str()];
3422 pkgAcquire fetcher(&status);
3423 _assert(list.GetIndexes(&fetcher));
3425 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3426 bool failed = false;
3427 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3428 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3429 (*item)->Finished();
3433 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3434 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3435 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3438 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3445 - (void) setDelegate:(id)delegate {
3446 delegate_ = delegate;
3447 status_.setDelegate(delegate);
3448 progress_.setDelegate(delegate);
3451 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3452 SourceMap::const_iterator i(sources_.find(file->ID));
3453 return i == sources_.end() ? nil : i->second;
3459 /* PopUp Windows {{{ */
3460 @interface PopUpView : UIView {
3461 _transient id delegate_;
3462 UITransitionView *transition_;
3467 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3471 @implementation PopUpView
3474 [transition_ setDelegate:nil];
3475 [transition_ release];
3481 [transition_ transition:UITransitionPushFromTop toView:nil];
3484 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3485 if (from != nil && to == nil)
3486 [self removeFromSuperview];
3489 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3490 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3491 delegate_ = delegate;
3493 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3494 [self addSubview:transition_];
3496 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3498 [view addSubview:self];
3500 [transition_ setDelegate:self];
3502 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3503 [transition_ transition:UITransitionNone toView:blank];
3504 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3512 /* Mail Composition {{{ */
3513 @interface MailToView : PopUpView {
3514 MailComposeController *controller_;
3517 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
3521 @implementation MailToView
3524 [controller_ release];
3528 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
3532 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
3533 NSLog(@"did:%@", delivery);
3534 // [UIApp setStatusBarShowsProgress:NO];
3535 if ([controller error]){
3536 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3537 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3538 [mailAlertSheet setBodyText:[controller error]];
3539 [mailAlertSheet popupAlertAnimated:YES];
3543 - (void) showError {
3544 NSLog(@"%@", [controller_ error]);
3545 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3546 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3547 [mailAlertSheet setBodyText:[controller_ error]];
3548 [mailAlertSheet popupAlertAnimated:YES];
3551 - (void) deliverMessage { _pooled
3555 if (![controller_ deliverMessage])
3556 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
3559 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
3560 if ([controller_ needsDelivery])
3561 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
3566 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
3567 if ((self = [super initWithView:view delegate:delegate]) != nil) {
3568 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
3569 [controller_ setDelegate:self];
3570 [controller_ initializeUI];
3571 [controller_ setupForURL:url];
3573 UIView *view([controller_ view]);
3574 [overlay_ addSubview:view];
3582 /* Confirmation View {{{ */
3583 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3584 if (!iterator.end())
3585 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3586 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3588 pkgCache::PkgIterator package(dep.TargetPkg());
3591 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3598 @protocol ConfirmationViewDelegate
3604 @interface ConfirmationView : BrowserView {
3605 _transient Database *database_;
3606 UIActionSheet *essential_;
3613 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3617 @implementation ConfirmationView
3624 if (essential_ != nil)
3625 [essential_ release];
3631 [book_ popFromSuperviewAnimated:YES];
3634 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3635 NSString *context([sheet context]);
3637 if ([context isEqualToString:@"remove"]) {
3645 [delegate_ confirm];
3652 } else if ([context isEqualToString:@"unable"]) {
3656 [super alertSheet:sheet buttonClicked:button];
3659 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3660 [super webView:sender didClearWindowObject:window forFrame:frame];
3661 [window setValue:changes_ forKey:@"changes"];
3662 [window setValue:issues_ forKey:@"issues"];
3663 [window setValue:sizes_ forKey:@"sizes"];
3666 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3667 if ((self = [super initWithBook:book]) != nil) {
3668 database_ = database;
3670 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3671 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3672 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3673 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3674 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3678 pkgDepCache::Policy *policy([database_ policy]);
3680 pkgCacheFile &cache([database_ cache]);
3681 NSArray *packages = [database_ packages];
3682 for (Package *package in packages) {
3683 pkgCache::PkgIterator iterator = [package iterator];
3684 pkgDepCache::StateCache &state(cache[iterator]);
3686 NSString *name([package name]);
3688 if (state.NewInstall())
3689 [installing addObject:name];
3690 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3691 [reinstalling addObject:name];
3692 else if (state.Upgrade())
3693 [upgrading addObject:name];
3694 else if (state.Downgrade())
3695 [downgrading addObject:name];
3696 else if (state.Delete()) {
3697 if ([package essential])
3699 [removing addObject:name];
3702 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3703 substrate_ |= DepSubstrate(iterator.CurrentVer());
3708 else if (Advanced_ || true) {
3709 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
3711 essential_ = [[UIActionSheet alloc]
3712 initWithTitle:CYLocalize("REMOVING_ESSENTIALS")
3713 buttons:[NSArray arrayWithObjects:
3714 [NSString stringWithFormat:parenthetical, CYLocalize("CANCEL_OPERATION"), CYLocalize("SAFE")],
3715 [NSString stringWithFormat:parenthetical, CYLocalize("FORCE_REMOVAL"), CYLocalize("UNSAFE")],
3717 defaultButtonIndex:0
3723 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3725 [essential_ setBodyText:CYLocalize("REMOVING_ESSENTIALS_EX")];
3727 essential_ = [[UIActionSheet alloc]
3728 initWithTitle:CYLocalize("UNABLE_TO_COMPLY")
3729 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3730 defaultButtonIndex:0
3735 [essential_ setBodyText:CYLocalize("UNABLE_TO_COMPLY_EX")];
3738 changes_ = [[NSArray alloc] initWithObjects:
3746 issues_ = [database_ issues];
3748 issues_ = [issues_ retain];
3750 sizes_ = [[NSArray alloc] initWithObjects:
3751 SizeString([database_ fetcher].FetchNeeded()),
3752 SizeString([database_ fetcher].PartialPresent()),
3753 SizeString([database_ cache]->UsrSize()),
3756 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3760 - (NSString *) backButtonTitle {
3761 return CYLocalize("CONFIRM");
3764 - (NSString *) leftButtonTitle {
3765 return [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("CANCEL"), CYLocalize("QUEUE")];
3768 - (id) rightButtonTitle {
3769 return issues_ != nil ? nil : [super rightButtonTitle];
3772 - (id) _rightButtonTitle {
3773 #if AlwaysReload || IgnoreInstall
3774 return [super _rightButtonTitle];
3776 return CYLocalize("CONFIRM");
3780 - (void) _leftButtonClicked {
3785 - (void) _rightButtonClicked {
3787 return [super _rightButtonClicked];
3789 if (essential_ != nil)
3790 [essential_ popupAlertAnimated:YES];
3794 [delegate_ confirm];
3802 /* Progress Data {{{ */
3803 @interface ProgressData : NSObject {
3809 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3816 @implementation ProgressData
3818 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3819 if ((self = [super init]) != nil) {
3820 selector_ = selector;
3840 /* Progress View {{{ */
3841 @interface ProgressView : UIView <
3842 ConfigurationDelegate,
3845 _transient Database *database_;
3847 UIView *background_;
3848 UITransitionView *transition_;
3850 UINavigationBar *navbar_;
3851 UIProgressBar *progress_;
3852 UITextView *output_;
3853 UITextLabel *status_;
3854 UIPushButton *close_;
3857 SHA1SumValue springlist_;
3858 SHA1SumValue notifyconf_;
3859 SHA1SumValue sandplate_;
3862 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
3864 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
3865 - (void) setContentView:(UIView *)view;
3868 - (void) _retachThread;
3869 - (void) _detachNewThreadData:(ProgressData *)data;
3870 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
3876 @protocol ProgressViewDelegate
3877 - (void) progressViewIsComplete:(ProgressView *)sender;
3880 @implementation ProgressView
3883 [transition_ setDelegate:nil];
3884 [navbar_ setDelegate:nil];
3887 if (background_ != nil)
3888 [background_ release];
3889 [transition_ release];
3892 [progress_ release];
3899 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3900 if (bootstrap_ && from == overlay_ && to == view_)
3904 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
3905 if ((self = [super initWithFrame:frame]) != nil) {
3906 database_ = database;
3907 delegate_ = delegate;
3909 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3910 [transition_ setDelegate:self];
3912 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3915 [overlay_ setBackgroundColor:[UIColor blackColor]];
3917 background_ = [[UIView alloc] initWithFrame:[self bounds]];
3918 [background_ setBackgroundColor:[UIColor blackColor]];
3919 [self addSubview:background_];
3922 [self addSubview:transition_];
3924 CGSize navsize = [UINavigationBar defaultSize];
3925 CGRect navrect = {{0, 0}, navsize};
3927 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
3928 [overlay_ addSubview:navbar_];
3930 [navbar_ setBarStyle:1];
3931 [navbar_ setDelegate:self];
3933 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
3934 [navbar_ pushNavigationItem:navitem];
3936 CGRect bounds = [overlay_ bounds];
3937 CGSize prgsize = [UIProgressBar defaultSize];
3940 (bounds.size.width - prgsize.width) / 2,
3941 bounds.size.height - prgsize.height - 20
3944 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3945 [progress_ setStyle:0];
3947 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3949 bounds.size.height - prgsize.height - 50,
3950 bounds.size.width - 20,
3954 [status_ setColor:[UIColor whiteColor]];
3955 [status_ setBackgroundColor:[UIColor clearColor]];
3957 [status_ setCentersHorizontally:YES];
3958 //[status_ setFont:font];
3961 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3963 navrect.size.height + 20,
3964 bounds.size.width - 20,
3965 bounds.size.height - navsize.height - 62 - navrect.size.height
3969 //[output_ setTextFont:@"Courier New"];
3970 [output_ setTextSize:12];
3972 [output_ setTextColor:[UIColor whiteColor]];
3973 [output_ setBackgroundColor:[UIColor clearColor]];
3975 [output_ setMarginTop:0];
3976 [output_ setAllowsRubberBanding:YES];
3977 [output_ setEditable:NO];
3979 [overlay_ addSubview:output_];
3981 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3983 bounds.size.height - prgsize.height - 50,
3984 bounds.size.width - 20,
3988 [close_ setAutosizesToFit:NO];
3989 [close_ setDrawsShadow:YES];
3990 [close_ setStretchBackground:YES];
3991 [close_ setEnabled:YES];
3993 UIFont *bold = [UIFont boldSystemFontOfSize:22];
3994 [close_ setTitleFont:bold];
3996 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
3997 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
3998 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4002 - (void) setContentView:(UIView *)view {
4003 view_ = [view retain];
4006 - (void) resetView {
4007 [transition_ transition:6 toView:view_];
4010 - (void) _checkError {
4011 if (_error->PendingError()) {
4013 if (!_error->PopMessage(error))
4016 UIActionSheet *sheet = [[[UIActionSheet alloc]
4017 initWithTitle:CYLocalize("ERROR")
4018 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
4019 defaultButtonIndex:0
4024 [sheet setBodyText:[NSString stringWithUTF8String:error.c_str()]];
4025 [sheet popupAlertAnimated:YES];
4030 [delegate_ progressViewIsComplete:self];
4033 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4034 MMap mmap(file, MMap::ReadOnly);
4036 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4037 if (!(sandplate_ == sha1.Result()))
4042 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4043 MMap mmap(file, MMap::ReadOnly);
4045 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4046 if (!(notifyconf_ == sha1.Result()))
4051 FileFd file(SpringBoard_, FileFd::ReadOnly);
4052 MMap mmap(file, MMap::ReadOnly);
4054 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4055 if (!(springlist_ == sha1.Result()))
4060 case 0: [close_ setTitle:CYLocalize("RETURN_TO_CYDIA")]; break;
4061 case 1: [close_ setTitle:CYLocalize("CLOSE_CYDIA")]; break;
4062 case 2: [close_ setTitle:CYLocalize("RESTART_SPRINGBOARD")]; break;
4063 case 3: [close_ setTitle:CYLocalize("RELOAD_SPRINGBOARD")]; break;
4064 case 4: [close_ setTitle:CYLocalize("REBOOT_DEVICE")]; break;
4067 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4069 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
4070 [cache autorelease];
4072 NSFileManager *manager = [NSFileManager defaultManager];
4073 NSError *error = nil;
4075 id system = [cache objectForKey:@"System"];
4080 if (stat(Cache_, &info) == -1)
4083 [system removeAllObjects];
4085 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4086 for (NSString *app in apps)
4087 if ([app hasSuffix:@".app"]) {
4088 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4089 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4090 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4092 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4093 [info setObject:path forKey:@"Path"];
4094 [info setObject:@"System" forKey:@"ApplicationType"];
4095 [system addInfoDictionary:info];
4101 [cache writeToFile:@Cache_ atomically:YES];
4103 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
4105 if (chmod(Cache_, info.st_mode) == -1)
4109 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4112 notify_post("com.apple.mobile.application_installed");
4114 [delegate_ setStatusBarShowsProgress:NO];
4117 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4118 NSString *context([sheet context]);
4120 if ([context isEqualToString:@"error"])
4122 else if ([context isEqualToString:@"_error"]) {
4125 } else if ([context isEqualToString:@"conffile"]) {
4126 FILE *input = [database_ input];
4130 fprintf(input, "N\n");
4134 fprintf(input, "Y\n");
4145 - (void) closeButtonPushed {
4154 [delegate_ suspendWithAnimation:YES];
4158 system("launchctl stop com.apple.SpringBoard");
4162 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4171 - (void) _retachThread {
4172 UINavigationItem *item = [navbar_ topItem];
4173 [item setTitle:CYLocalize("COMPLETE")];
4175 [overlay_ addSubview:close_];
4176 [progress_ removeFromSuperview];
4177 [status_ removeFromSuperview];
4182 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4183 [[data target] performSelector:[data selector] withObject:[data object]];
4186 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4189 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4190 UINavigationItem *item = [navbar_ topItem];
4191 [item setTitle:title];
4193 [status_ setText:nil];
4194 [output_ setText:@""];
4195 [progress_ setProgress:0];
4197 [close_ removeFromSuperview];
4198 [overlay_ addSubview:progress_];
4199 [overlay_ addSubview:status_];
4201 [delegate_ setStatusBarShowsProgress:YES];
4205 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4206 MMap mmap(file, MMap::ReadOnly);
4208 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4209 sandplate_ = sha1.Result();
4213 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4214 MMap mmap(file, MMap::ReadOnly);
4216 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4217 notifyconf_ = sha1.Result();
4221 FileFd file(SpringBoard_, FileFd::ReadOnly);
4222 MMap mmap(file, MMap::ReadOnly);
4224 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4225 springlist_ = sha1.Result();
4228 [transition_ transition:6 toView:overlay_];
4231 detachNewThreadSelector:@selector(_detachNewThreadData:)
4233 withObject:[[ProgressData alloc]
4234 initWithSelector:selector
4241 - (void) repairWithSelector:(SEL)selector {
4243 detachNewThreadSelector:selector
4246 title:CYLocalize("REPAIRING")
4250 - (void) setConfigurationData:(NSString *)data {
4252 performSelectorOnMainThread:@selector(_setConfigurationData:)
4258 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4259 Package *package = id == nil ? nil : [database_ packageWithName:id];
4261 UIActionSheet *sheet = [[[UIActionSheet alloc]
4262 initWithTitle:(package == nil ? id : [package name])
4263 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
4264 defaultButtonIndex:0
4269 [sheet setBodyText:error];
4270 [sheet popupAlertAnimated:YES];
4273 - (void) setProgressTitle:(NSString *)title {
4275 performSelectorOnMainThread:@selector(_setProgressTitle:)
4281 - (void) setProgressPercent:(float)percent {
4283 performSelectorOnMainThread:@selector(_setProgressPercent:)
4284 withObject:[NSNumber numberWithFloat:percent]
4289 - (void) startProgress {
4292 - (void) addProgressOutput:(NSString *)output {
4294 performSelectorOnMainThread:@selector(_addProgressOutput:)
4300 - (bool) isCancelling:(size_t)received {
4304 - (void) _setConfigurationData:(NSString *)data {
4305 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4307 _assert(conffile_r(data));
4309 NSString *ofile = conffile_r[1];
4310 //NSString *nfile = conffile_r[2];
4312 UIActionSheet *sheet = [[[UIActionSheet alloc]
4313 initWithTitle:CYLocalize("CONFIGURATION_UPGRADE")
4314 buttons:[NSArray arrayWithObjects:
4315 CYLocalize("KEEP_OLD_COPY"),
4316 CYLocalize("ACCEPT_NEW_COPY"),
4317 // XXX: CYLocalize("SEE_WHAT_CHANGED"),
4319 defaultButtonIndex:0
4324 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", CYLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4325 [sheet popupAlertAnimated:YES];
4328 - (void) _setProgressTitle:(NSString *)title {
4329 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4330 for (size_t i(0), e([words count]); i != e; ++i) {
4331 NSString *word([words objectAtIndex:i]);
4332 if (Package *package = [database_ packageWithName:word])
4333 [words replaceObjectAtIndex:i withObject:[package name]];
4336 [status_ setText:[words componentsJoinedByString:@" "]];
4339 - (void) _setProgressPercent:(NSNumber *)percent {
4340 [progress_ setProgress:[percent floatValue]];
4343 - (void) _addProgressOutput:(NSString *)output {
4344 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4345 CGSize size = [output_ contentSize];
4346 CGRect rect = {{0, size.height}, {size.width, 0}};
4347 [output_ scrollRectToVisible:rect animated:YES];
4350 - (BOOL) isRunning {
4357 /* Package Cell {{{ */
4358 @interface PackageCell : UITableCell {
4361 NSString *description_;
4368 UITextLabel *status_;
4372 - (PackageCell *) init;
4373 - (void) setPackage:(Package *)package;
4375 + (int) heightForPackage:(Package *)package;
4379 @implementation PackageCell
4381 - (void) clearPackage {
4392 if (description_ != nil) {
4393 [description_ release];
4397 if (source_ != nil) {
4402 if (badge_ != nil) {
4412 [self clearPackage];
4419 - (PackageCell *) init {
4420 if ((self = [super init]) != nil) {
4422 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4423 [status_ setBackgroundColor:[UIColor clearColor]];
4424 [status_ setFont:small];
4429 - (void) setPackage:(Package *)package {
4430 [self clearPackage];
4433 Source *source = [package source];
4435 icon_ = [[package icon] retain];
4436 name_ = [[package name] retain];
4437 description_ = [[package shortDescription] retain];
4438 commercial_ = [package isCommercial];
4440 package_ = [package retain];
4442 NSString *label = nil;
4443 bool trusted = false;
4445 if (source != nil) {
4446 label = [source label];
4447 trusted = [source trusted];
4448 } else if ([[package id] isEqualToString:@"firmware"])
4449 label = CYLocalize("APPLE");
4451 label = [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("UNKNOWN"), CYLocalize("LOCAL")];
4453 NSString *from(label);
4455 NSString *section = [package simpleSection];
4456 if (section != nil && ![section isEqualToString:label]) {
4457 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4458 from = [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), from, section];
4461 from = [NSString stringWithFormat:CYLocalize("FROM"), from];
4462 source_ = [from retain];
4464 if (NSString *purpose = [package primaryPurpose])
4465 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4466 badge_ = [badge_ retain];
4469 if (NSString *mode = [package mode]) {
4470 [badge_ setImage:[UIImage applicationImageNamed:
4471 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4474 [status_ setText:[NSString stringWithFormat:CYLocalize("QUEUED_FOR"), CYLocalize(mode)]];
4475 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4476 } else if ([package half]) {
4477 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4478 [status_ setText:CYLocalize("PACKAGE_DAMAGED")];
4479 [status_ setColor:[UIColor redColor]];
4481 [badge_ setImage:nil];
4482 [status_ setText:nil];
4489 - (void) drawRect:(CGRect)rect {
4493 if (NSString *mode = [package_ mode]) {
4494 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4495 color = remove ? RemovingColor_ : InstallingColor_;
4497 color = [UIColor whiteColor];
4499 [self setBackgroundColor:color];
4503 [super drawRect:rect];
4506 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4508 CGContextRef context(UIGraphicsGetCurrentContext());
4509 [[self backgroundColor] set];
4511 back.size.height -= 1;
4512 CGContextFillRect(context, back);
4515 [super drawBackgroundInRect:rect withFade:fade];
4518 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4521 rect.size = [icon_ size];
4523 rect.size.width /= 2;
4524 rect.size.height /= 2;
4526 rect.origin.x = 25 - rect.size.width / 2;
4527 rect.origin.y = 25 - rect.size.height / 2;
4529 [icon_ drawInRect:rect];
4532 if (badge_ != nil) {
4533 CGSize size = [badge_ size];
4535 [badge_ drawAtPoint:CGPointMake(
4536 36 - size.width / 2,
4537 36 - size.height / 2
4545 UISetColor(commercial_ ? Purple_ : Black_);
4546 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4547 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4550 UISetColor(commercial_ ? Purplish_ : Gray_);
4551 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4553 [super drawContentInRect:rect selected:selected];
4556 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4558 [super setSelected:selected withFade:fade];
4561 + (int) heightForPackage:(Package *)package {
4567 /* Section Cell {{{ */
4568 @interface SectionCell : UISimpleTableCell {
4573 _UISwitchSlider *switch_;
4578 - (void) setSection:(Section *)section editing:(BOOL)editing;
4582 @implementation SectionCell
4584 - (void) clearSection {
4585 if (section_ != nil) {
4595 if (count_ != nil) {
4602 [self clearSection];
4609 if ((self = [super init]) != nil) {
4610 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4612 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4613 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4617 - (void) onSwitch:(id)sender {
4618 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4619 if (metadata == nil) {
4620 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4621 [Sections_ setObject:metadata forKey:section_];
4625 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4628 - (void) setSection:(Section *)section editing:(BOOL)editing {
4629 if (editing != editing_) {
4631 [switch_ removeFromSuperview];
4633 [self addSubview:switch_];
4637 [self clearSection];
4639 if (section == nil) {
4640 name_ = [CYLocalize("ALL_PACKAGES") retain];
4643 section_ = [section localized];
4644 if (section_ != nil)
4645 section_ = [section_ retain];
4646 name_ = [(section_ == nil ? CYLocalize("NO_SECTION") : section_) retain];
4647 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4650 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4654 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4655 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4662 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4664 CGSize size = [count_ sizeWithFont:Font14_];
4668 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4670 [super drawContentInRect:rect selected:selected];
4676 /* File Table {{{ */
4677 @interface FileTable : RVPage {
4678 _transient Database *database_;
4681 NSMutableArray *files_;
4685 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4686 - (void) setPackage:(Package *)package;
4690 @implementation FileTable
4693 if (package_ != nil)
4702 - (int) numberOfRowsInTable:(UITable *)table {
4703 return files_ == nil ? 0 : [files_ count];
4706 - (float) table:(UITable *)table heightForRow:(int)row {
4710 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4711 if (reusing == nil) {
4712 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4713 UIFont *font = [UIFont systemFontOfSize:16];
4714 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4716 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4720 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4724 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4725 if ((self = [super initWithBook:book]) != nil) {
4726 database_ = database;
4728 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4730 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4731 [self addSubview:list_];
4733 UITableColumn *column = [[[UITableColumn alloc]
4734 initWithTitle:CYLocalize("NAME")
4736 width:[self frame].size.width
4739 [list_ setDataSource:self];
4740 [list_ setSeparatorStyle:1];
4741 [list_ addTableColumn:column];
4742 [list_ setDelegate:self];
4743 [list_ setReusesTableCells:YES];
4747 - (void) setPackage:(Package *)package {
4748 if (package_ != nil) {
4749 [package_ autorelease];
4758 [files_ removeAllObjects];
4760 if (package != nil) {
4761 package_ = [package retain];
4762 name_ = [[package id] retain];
4764 if (NSArray *files = [package files])
4765 [files_ addObjectsFromArray:files];
4767 if ([files_ count] != 0) {
4768 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4769 [files_ removeObjectAtIndex:0];
4770 [files_ sortUsingSelector:@selector(compareByPath:)];
4772 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4773 [stack addObject:@"/"];
4775 for (int i(0), e([files_ count]); i != e; ++i) {
4776 NSString *file = [files_ objectAtIndex:i];
4777 while (![file hasPrefix:[stack lastObject]])
4778 [stack removeLastObject];
4779 NSString *directory = [stack lastObject];
4780 [stack addObject:[file stringByAppendingString:@"/"]];
4781 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4782 ([stack count] - 2) * 3, "",
4783 [file substringFromIndex:[directory length]]
4792 - (void) resetViewAnimated:(BOOL)animated {
4793 [list_ resetViewAnimated:animated];
4796 - (void) reloadData {
4797 [self setPackage:[database_ packageWithName:name_]];
4798 [self reloadButtons];
4801 - (NSString *) title {
4802 return CYLocalize("INSTALLED_FILES");
4805 - (NSString *) backButtonTitle {
4806 return CYLocalize("FILES");
4811 /* Package View {{{ */
4812 @interface PackageView : BrowserView {
4813 _transient Database *database_;
4817 NSMutableArray *buttons_;
4820 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4821 - (void) setPackage:(Package *)package;
4825 @implementation PackageView
4828 if (package_ != nil)
4837 if ([self retainCount] == 1)
4838 [delegate_ setPackageView:self];
4842 /* XXX: this is not safe at all... localization of /fail/ */
4843 - (void) _clickButtonWithName:(NSString *)name {
4844 if ([name isEqualToString:CYLocalize("CLEAR")])
4845 [delegate_ clearPackage:package_];
4846 else if ([name isEqualToString:CYLocalize("INSTALL")])
4847 [delegate_ installPackage:package_];
4848 else if ([name isEqualToString:CYLocalize("REINSTALL")])
4849 [delegate_ installPackage:package_];
4850 else if ([name isEqualToString:CYLocalize("REMOVE")])
4851 [delegate_ removePackage:package_];
4852 else if ([name isEqualToString:CYLocalize("UPGRADE")])
4853 [delegate_ installPackage:package_];
4854 else _assert(false);
4857 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4858 NSString *context([sheet context]);
4860 if ([context isEqualToString:@"modify"]) {
4861 int count = [buttons_ count];
4862 _assert(count != 0);
4863 _assert(button <= count + 1);
4865 if (count != button - 1)
4866 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
4870 [super alertSheet:sheet buttonClicked:button];
4873 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
4874 return [super webView:sender didFinishLoadForFrame:frame];
4877 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4878 [super webView:sender didClearWindowObject:window forFrame:frame];
4879 [window setValue:package_ forKey:@"package"];
4882 - (bool) _allowJavaScriptPanel {
4887 - (void) __rightButtonClicked {
4888 int count = [buttons_ count];
4889 _assert(count != 0);
4892 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
4894 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
4895 [buttons addObjectsFromArray:buttons_];
4896 [buttons addObject:CYLocalize("CANCEL")];
4898 [delegate_ slideUp:[[[UIActionSheet alloc]
4901 defaultButtonIndex:([buttons count] - 1)
4908 - (void) _rightButtonClicked {
4910 [super _rightButtonClicked];
4912 [self __rightButtonClicked];
4916 - (id) _rightButtonTitle {
4917 int count = [buttons_ count];
4918 return count == 0 ? nil : count != 1 ? CYLocalize("MODIFY") : [buttons_ objectAtIndex:0];
4921 - (NSString *) backButtonTitle {
4925 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4926 if ((self = [super initWithBook:book]) != nil) {
4927 database_ = database;
4928 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
4929 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
4933 - (void) setPackage:(Package *)package {
4934 if (package_ != nil) {
4935 [package_ autorelease];
4944 [buttons_ removeAllObjects];
4946 if (package != nil) {
4949 package_ = [package retain];
4950 name_ = [[package id] retain];
4951 commercial_ = [package isCommercial];
4953 if ([package_ mode] != nil)
4954 [buttons_ addObject:CYLocalize("CLEAR")];
4955 if ([package_ source] == nil);
4956 else if ([package_ upgradableAndEssential:NO])
4957 [buttons_ addObject:CYLocalize("UPGRADE")];
4958 else if ([package_ installed] == nil)
4959 [buttons_ addObject:CYLocalize("INSTALL")];
4961 [buttons_ addObject:CYLocalize("REINSTALL")];
4962 if ([package_ installed] != nil)
4963 [buttons_ addObject:CYLocalize("REMOVE")];
4965 if (special_ != NULL) {
4966 CGRect frame([webview_ frame]);
4967 frame.size.width = 320;
4968 frame.size.height = 0;
4969 [webview_ setFrame:frame];
4971 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
4974 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
4976 [self setButtonTitle:nil withStyle:nil toFunction:nil];
4978 [self setFinishHook:nil];
4979 [self setPopupHook:nil];
4982 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
4983 [super callFunction:special_];
4987 [self reloadButtons];
4990 - (bool) isLoading {
4991 return commercial_ ? [super isLoading] : false;
4994 - (void) reloadData {
4995 [self setPackage:[database_ packageWithName:name_]];
5000 /* Package Table {{{ */
5001 @interface PackageTable : RVPage {
5002 _transient Database *database_;
5004 NSMutableArray *packages_;
5005 NSMutableArray *sections_;
5006 UISectionList *list_;
5009 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5011 - (void) setDelegate:(id)delegate;
5013 - (void) reloadData;
5014 - (void) resetCursor;
5016 - (UISectionList *) list;
5018 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5022 @implementation PackageTable
5025 [list_ setDataSource:nil];
5028 [packages_ release];
5029 [sections_ release];
5034 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5035 return [sections_ count];
5038 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5039 return [[sections_ objectAtIndex:section] name];
5042 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5043 return [[sections_ objectAtIndex:section] row];
5046 - (int) numberOfRowsInTable:(UITable *)table {
5047 return [packages_ count];
5050 - (float) table:(UITable *)table heightForRow:(int)row {
5051 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
5054 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
5056 reusing = [[[PackageCell alloc] init] autorelease];
5057 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
5061 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5065 - (void) tableRowSelected:(NSNotification *)notification {
5066 int row = [[notification object] selectedRow];
5070 Package *package = [packages_ objectAtIndex:row];
5071 package = [database_ packageWithName:[package id]];
5072 PackageView *view([delegate_ packageView]);
5073 [view setPackage:package];
5074 [view setDelegate:delegate_];
5075 [book_ pushPage:view];
5078 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5079 if ((self = [super initWithBook:book]) != nil) {
5080 database_ = database;
5081 title_ = [title retain];
5083 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5084 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5086 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
5087 [list_ setDataSource:self];
5089 UITableColumn *column = [[[UITableColumn alloc]
5090 initWithTitle:CYLocalize("NAME")
5092 width:[self frame].size.width
5095 UITable *table = [list_ table];
5096 [table setSeparatorStyle:1];
5097 [table addTableColumn:column];
5098 [table setDelegate:self];
5099 [table setReusesTableCells:YES];
5101 [self addSubview:list_];
5103 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5104 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5108 - (void) setDelegate:(id)delegate {
5109 delegate_ = delegate;
5112 - (bool) hasPackage:(Package *)package {
5116 - (void) reloadData {
5117 NSArray *packages = [database_ packages];
5119 [packages_ removeAllObjects];
5120 [sections_ removeAllObjects];
5122 _profile(PackageTable$reloadData$Filter)
5123 for (Package *package in packages)
5124 if ([self hasPackage:package])
5125 [packages_ addObject:package];
5128 Section *section = nil;
5130 _profile(PackageTable$reloadData$Section)
5131 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5135 _profile(PackageTable$reloadData$Section$Package)
5136 package = [packages_ objectAtIndex:offset];
5137 index = [package index];
5140 if (section == nil || [section index] != index) {
5141 _profile(PackageTable$reloadData$Section$Allocate)
5142 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5145 _profile(PackageTable$reloadData$Section$Add)
5146 [sections_ addObject:section];
5150 [section addToCount];
5154 _profile(PackageTable$reloadData$List)
5159 - (NSString *) title {
5163 - (void) resetViewAnimated:(BOOL)animated {
5164 [list_ resetViewAnimated:animated];
5167 - (void) resetCursor {
5168 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
5171 - (UISectionList *) list {
5175 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5176 [list_ setShouldHideHeaderInShortLists:hide];
5181 /* Filtered Package Table {{{ */
5182 @interface FilteredPackageTable : PackageTable {
5188 - (void) setObject:(id)object;
5190 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5194 @implementation FilteredPackageTable
5202 - (void) setObject:(id)object {
5208 object_ = [object retain];
5211 - (bool) hasPackage:(Package *)package {
5212 _profile(FilteredPackageTable$hasPackage)
5213 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5217 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5218 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5220 object_ = object == nil ? nil : [object retain];
5222 /* XXX: this is an unsafe optimization of doomy hell */
5223 Method method = class_getInstanceMethod([Package class], filter);
5224 _assert(method != NULL);
5225 imp_ = method_getImplementation(method);
5226 _assert(imp_ != NULL);
5235 /* Add Source View {{{ */
5236 @interface AddSourceView : RVPage {
5237 _transient Database *database_;
5240 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5244 @implementation AddSourceView
5246 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5247 if ((self = [super initWithBook:book]) != nil) {
5248 database_ = database;
5254 /* Source Cell {{{ */
5255 @interface SourceCell : UITableCell {
5258 NSString *description_;
5264 - (SourceCell *) initWithSource:(Source *)source;
5268 @implementation SourceCell
5273 [description_ release];
5278 - (SourceCell *) initWithSource:(Source *)source {
5279 if ((self = [super init]) != nil) {
5281 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5283 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5284 icon_ = [icon_ retain];
5286 origin_ = [[source name] retain];
5287 label_ = [[source uri] retain];
5288 description_ = [[source description] retain];
5292 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5294 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5301 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5305 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5309 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5311 [super drawContentInRect:rect selected:selected];
5316 /* Source Table {{{ */
5317 @interface SourceTable : RVPage {
5318 _transient Database *database_;
5319 UISectionList *list_;
5320 NSMutableArray *sources_;
5321 UIActionSheet *alert_;
5325 UIProgressHUD *hud_;
5328 //NSURLConnection *installer_;
5329 NSURLConnection *trivial_bz2_;
5330 NSURLConnection *trivial_gz_;
5331 //NSURLConnection *automatic_;
5336 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5340 @implementation SourceTable
5342 - (void) _deallocConnection:(NSURLConnection *)connection {
5343 if (connection != nil) {
5344 [connection cancel];
5345 //[connection setDelegate:nil];
5346 [connection release];
5351 [[list_ table] setDelegate:nil];
5352 [list_ setDataSource:nil];
5361 //[self _deallocConnection:installer_];
5362 [self _deallocConnection:trivial_gz_];
5363 [self _deallocConnection:trivial_bz2_];
5364 //[self _deallocConnection:automatic_];
5371 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5372 return offset_ == 0 ? 1 : 2;
5375 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5376 switch (section + (offset_ == 0 ? 1 : 0)) {
5377 case 0: return CYLocalize("ENTERED_BY_USER");
5378 case 1: return CYLocalize("INSTALLED_BY_PACKAGE");
5386 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5387 switch (section + (offset_ == 0 ? 1 : 0)) {
5389 case 1: return offset_;
5397 - (int) numberOfRowsInTable:(UITable *)table {
5398 return [sources_ count];
5401 - (float) table:(UITable *)table heightForRow:(int)row {
5402 Source *source = [sources_ objectAtIndex:row];
5403 return [source description] == nil ? 56 : 73;
5406 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5407 Source *source = [sources_ objectAtIndex:row];
5408 // XXX: weird warning, stupid selectors ;P
5409 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5412 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5416 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5420 - (void) tableRowSelected:(NSNotification*)notification {
5421 UITable *table([list_ table]);
5422 int row([table selectedRow]);
5426 Source *source = [sources_ objectAtIndex:row];
5428 PackageTable *packages = [[[FilteredPackageTable alloc]
5431 title:[source label]
5432 filter:@selector(isVisibleInSource:)
5436 [packages setDelegate:delegate_];
5438 [book_ pushPage:packages];
5441 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5442 Source *source = [sources_ objectAtIndex:row];
5443 return [source record] != nil;
5446 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5447 [[list_ table] setDeleteConfirmationRow:row];
5450 - (void) table:(UITable *)table deleteRow:(int)row {
5451 Source *source = [sources_ objectAtIndex:row];
5452 [Sources_ removeObjectForKey:[source key]];
5453 [delegate_ syncData];
5457 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5460 @"./", @"Distribution",
5461 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5463 [delegate_ syncData];
5466 - (NSString *) getWarning {
5467 NSString *href(href_);
5468 NSRange colon([href rangeOfString:@"://"]);
5469 if (colon.location != NSNotFound)
5470 href = [href substringFromIndex:(colon.location + 3)];
5471 href = [href stringByAddingPercentEscapes];
5472 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5473 href = [href stringByCachingURLWithCurrentCDN];
5475 NSURL *url([NSURL URLWithString:href]);
5477 NSStringEncoding encoding;
5478 NSError *error(nil);
5480 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5481 return [warning length] == 0 ? nil : warning;
5485 - (void) _endConnection:(NSURLConnection *)connection {
5486 NSURLConnection **field = NULL;
5487 if (connection == trivial_bz2_)
5488 field = &trivial_bz2_;
5489 else if (connection == trivial_gz_)
5490 field = &trivial_gz_;
5491 _assert(field != NULL);
5492 [connection release];
5496 trivial_bz2_ == nil &&
5502 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5505 UIActionSheet *sheet = [[[UIActionSheet alloc]
5506 initWithTitle:CYLocalize("SOURCE_WARNING")
5507 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_ANYWAY"), CYLocalize("CANCEL"), nil]
5508 defaultButtonIndex:0
5513 [sheet setNumberOfRows:1];
5515 [sheet setBodyText:warning];
5516 [sheet popupAlertAnimated:YES];
5519 } else if (error_ != nil) {
5520 UIActionSheet *sheet = [[[UIActionSheet alloc]
5521 initWithTitle:CYLocalize("VERIFICATION_ERROR")
5522 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5523 defaultButtonIndex:0
5528 [sheet setBodyText:[error_ localizedDescription]];
5529 [sheet popupAlertAnimated:YES];
5531 UIActionSheet *sheet = [[[UIActionSheet alloc]
5532 initWithTitle:CYLocalize("NOT_REPOSITORY")
5533 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5534 defaultButtonIndex:0
5539 [sheet setBodyText:CYLocalize("NOT_REPOSITORY_EX")];
5540 [sheet popupAlertAnimated:YES];
5543 [delegate_ setStatusBarShowsProgress:NO];
5544 [delegate_ removeProgressHUD:hud_];
5554 if (error_ != nil) {
5561 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5562 switch ([response statusCode]) {
5568 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5569 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5571 error_ = [error retain];
5572 [self _endConnection:connection];
5575 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5576 [self _endConnection:connection];
5579 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5580 NSMutableURLRequest *request = [NSMutableURLRequest
5581 requestWithURL:[NSURL URLWithString:href]
5582 cachePolicy:NSURLRequestUseProtocolCachePolicy
5583 timeoutInterval:20.0
5586 [request setHTTPMethod:method];
5588 if (Machine_ != NULL)
5589 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5590 if (UniqueID_ != nil)
5591 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5594 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5596 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5599 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5600 NSString *context([sheet context]);
5602 if ([context isEqualToString:@"source"]) {
5605 NSString *href = [[sheet textField] text];
5607 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5609 if (![href hasSuffix:@"/"])
5610 href_ = [href stringByAppendingString:@"/"];
5613 href_ = [href_ retain];
5615 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5616 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5617 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5621 hud_ = [[delegate_ addProgressHUD] retain];
5622 [hud_ setText:CYLocalize("VERIFYING_URL")];
5633 } else if ([context isEqualToString:@"trivial"])
5635 else if ([context isEqualToString:@"urlerror"])
5637 else if ([context isEqualToString:@"warning"]) {
5657 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5658 if ((self = [super initWithBook:book]) != nil) {
5659 database_ = database;
5660 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5662 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5663 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5664 [list_ setShouldHideHeaderInShortLists:NO];
5666 [self addSubview:list_];
5667 [list_ setDataSource:self];
5669 UITableColumn *column = [[UITableColumn alloc]
5670 initWithTitle:CYLocalize("NAME")
5672 width:[self frame].size.width
5675 UITable *table = [list_ table];
5676 [table setSeparatorStyle:1];
5677 [table addTableColumn:column];
5678 [table setDelegate:self];
5682 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5683 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5687 - (void) reloadData {
5689 _assert(list.ReadMainList());
5691 [sources_ removeAllObjects];
5692 [sources_ addObjectsFromArray:[database_ sources]];
5694 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5697 int count = [sources_ count];
5698 for (offset_ = 0; offset_ != count; ++offset_) {
5699 Source *source = [sources_ objectAtIndex:offset_];
5700 if ([source record] == nil)
5707 - (void) resetViewAnimated:(BOOL)animated {
5708 [list_ resetViewAnimated:animated];
5711 - (void) _leftButtonClicked {
5712 /*[book_ pushPage:[[[AddSourceView alloc]
5717 UIActionSheet *sheet = [[[UIActionSheet alloc]
5718 initWithTitle:CYLocalize("ENTER_APT_URL")
5719 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_SOURCE"), CYLocalize("CANCEL"), nil]
5720 defaultButtonIndex:0
5725 [sheet setNumberOfRows:1];
5727 [sheet addTextFieldWithValue:@"http://" label:@""];
5729 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5730 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5731 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5732 [traits setKeyboardType:UIKeyboardTypeURL];
5733 // XXX: UIReturnKeyDone
5734 [traits setReturnKeyType:UIReturnKeyNext];
5736 [sheet popupAlertAnimated:YES];
5739 - (void) _rightButtonClicked {
5740 UITable *table = [list_ table];
5741 BOOL editing = [table isRowDeletionEnabled];
5742 [table enableRowDeletion:!editing animated:YES];
5743 [book_ reloadButtonsForPage:self];
5746 - (NSString *) title {
5747 return CYLocalize("SOURCES");
5750 - (NSString *) leftButtonTitle {
5751 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("ADD") : nil;
5754 - (id) rightButtonTitle {
5755 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("DONE") : CYLocalize("EDIT");
5758 - (UINavigationButtonStyle) rightButtonStyle {
5759 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5765 /* Installed View {{{ */
5766 @interface InstalledView : RVPage {
5767 _transient Database *database_;
5768 FilteredPackageTable *packages_;
5772 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5776 @implementation InstalledView
5779 [packages_ release];
5783 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5784 if ((self = [super initWithBook:book]) != nil) {
5785 database_ = database;
5787 packages_ = [[FilteredPackageTable alloc]
5791 filter:@selector(isInstalledAndVisible:)
5792 with:[NSNumber numberWithBool:YES]
5795 [self addSubview:packages_];
5797 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5798 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5802 - (void) resetViewAnimated:(BOOL)animated {
5803 [packages_ resetViewAnimated:animated];
5806 - (void) reloadData {
5807 [packages_ reloadData];
5810 - (void) _rightButtonClicked {
5811 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5812 [packages_ reloadData];
5814 [book_ reloadButtonsForPage:self];
5817 - (NSString *) title {
5818 return CYLocalize("INSTALLED");
5821 - (NSString *) backButtonTitle {
5822 return CYLocalize("PACKAGES");
5825 - (id) rightButtonTitle {
5826 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? CYLocalize("EXPERT") : CYLocalize("SIMPLE");
5829 - (UINavigationButtonStyle) rightButtonStyle {
5830 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5833 - (void) setDelegate:(id)delegate {
5834 [super setDelegate:delegate];
5835 [packages_ setDelegate:delegate];
5842 @interface HomeView : BrowserView {
5847 @implementation HomeView
5849 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5850 NSString *context([sheet context]);
5852 if ([context isEqualToString:@"about"])
5855 [super alertSheet:sheet buttonClicked:button];
5858 - (void) _leftButtonClicked {
5859 UIActionSheet *sheet = [[[UIActionSheet alloc]
5860 initWithTitle:CYLocalize("ABOUT_CYDIA")
5861 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
5862 defaultButtonIndex:0
5868 @"Copyright (C) 2008-2009\n"
5869 "Jay Freeman (saurik)\n"
5870 "saurik@saurik.com\n"
5871 "http://www.saurik.com/\n"
5874 "http://www.theokorigroup.com/\n"
5876 "College of Creative Studies,\n"
5877 "University of California,\n"
5879 "http://www.ccs.ucsb.edu/"
5882 [sheet popupAlertAnimated:YES];
5885 - (NSString *) leftButtonTitle {
5886 return CYLocalize("ABOUT");
5891 /* Manage View {{{ */
5892 @interface ManageView : BrowserView {
5897 @implementation ManageView
5899 - (NSString *) title {
5900 return CYLocalize("MANAGE");
5903 - (void) _leftButtonClicked {
5904 [delegate_ askForSettings];
5907 - (NSString *) leftButtonTitle {
5908 return CYLocalize("SETTINGS");
5912 - (id) _rightButtonTitle {
5913 return Queuing_ ? CYLocalize("QUEUE") : nil;
5916 - (UINavigationButtonStyle) rightButtonStyle {
5917 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5920 - (void) _rightButtonClicked {
5925 - (bool) isLoading {
5932 #include <BrowserView.m>
5934 /* Cydia Book {{{ */
5935 @interface CYBook : RVBook <
5938 _transient Database *database_;
5939 UINavigationBar *overlay_;
5940 UINavigationBar *underlay_;
5941 UIProgressIndicator *indicator_;
5942 UITextLabel *prompt_;
5943 UIProgressBar *progress_;
5944 UINavigationButton *cancel_;
5948 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
5954 @implementation CYBook
5958 [indicator_ release];
5960 [progress_ release];
5965 - (NSString *) getTitleForPage:(RVPage *)page {
5966 return [super getTitleForPage:page];
5974 [UIView beginAnimations:nil context:NULL];
5976 CGRect ovrframe = [overlay_ frame];
5977 ovrframe.origin.y = 0;
5978 [overlay_ setFrame:ovrframe];
5980 CGRect barframe = [navbar_ frame];
5981 barframe.origin.y += ovrframe.size.height;
5982 [navbar_ setFrame:barframe];
5984 CGRect trnframe = [transition_ frame];
5985 trnframe.origin.y += ovrframe.size.height;
5986 trnframe.size.height -= ovrframe.size.height;
5987 [transition_ setFrame:trnframe];
5989 [UIView endAnimations];
5991 [indicator_ startAnimation];
5992 [prompt_ setText:CYLocalize("UPDATING_DATABASE")];
5993 [progress_ setProgress:0];
5996 [overlay_ addSubview:cancel_];
5999 detachNewThreadSelector:@selector(_update)
6005 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6006 NSString *context([sheet context]);
6008 if ([context isEqualToString:@"refresh"])
6012 - (void) _update_:(NSString *)error {
6015 [indicator_ stopAnimation];
6017 [UIView beginAnimations:nil context:NULL];
6019 CGRect ovrframe = [overlay_ frame];
6020 ovrframe.origin.y = -ovrframe.size.height;
6021 [overlay_ setFrame:ovrframe];
6023 CGRect barframe = [navbar_ frame];
6024 barframe.origin.y -= ovrframe.size.height;
6025 [navbar_ setFrame:barframe];
6027 CGRect trnframe = [transition_ frame];
6028 trnframe.origin.y -= ovrframe.size.height;
6029 trnframe.size.height += ovrframe.size.height;
6030 [transition_ setFrame:trnframe];
6032 [UIView commitAnimations];
6035 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6037 UIActionSheet *sheet = [[[UIActionSheet alloc]
6038 initWithTitle:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), CYLocalize("REFRESH")]
6039 buttons:[NSArray arrayWithObjects:
6042 defaultButtonIndex:0
6047 [sheet setBodyText:error];
6048 [sheet popupAlertAnimated:YES];
6050 [self reloadButtons];
6054 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6055 if ((self = [super initWithFrame:frame]) != nil) {
6056 database_ = database;
6058 CGRect ovrrect = [navbar_ bounds];
6059 ovrrect.size.height = [UINavigationBar defaultSize].height;
6060 ovrrect.origin.y = -ovrrect.size.height;
6062 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6063 [self addSubview:overlay_];
6065 ovrrect.origin.y = frame.size.height;
6066 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6067 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6068 [self addSubview:underlay_];
6070 [overlay_ setBarStyle:1];
6071 [underlay_ setBarStyle:1];
6073 int barstyle = [overlay_ _barStyle:NO];
6074 bool ugly = barstyle == 0;
6076 UIProgressIndicatorStyle style = ugly ?
6077 UIProgressIndicatorStyleMediumBrown :
6078 UIProgressIndicatorStyleMediumWhite;
6080 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
6081 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6082 CGRect indrect = {{indoffset, indoffset}, indsize};
6084 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6085 [indicator_ setStyle:style];
6086 [overlay_ addSubview:indicator_];
6088 CGSize prmsize = {215, indsize.height + 4};
6091 indoffset * 2 + indsize.width,
6095 unsigned(ovrrect.size.height - prmsize.height) / 2
6098 UIFont *font = [UIFont systemFontOfSize:15];
6100 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6102 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6103 [prompt_ setBackgroundColor:[UIColor clearColor]];
6104 [prompt_ setFont:font];
6106 [overlay_ addSubview:prompt_];
6108 CGSize prgsize = {75, 100};
6111 ovrrect.size.width - prgsize.width - 10,
6112 (ovrrect.size.height - prgsize.height) / 2
6115 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6116 [progress_ setStyle:0];
6117 [overlay_ addSubview:progress_];
6119 cancel_ = [[UINavigationButton alloc] initWithTitle:CYLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6120 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6122 CGRect frame = [cancel_ frame];
6123 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6124 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6125 [cancel_ setFrame:frame];
6127 [cancel_ setBarStyle:barstyle];
6131 - (void) _onCancel {
6133 [cancel_ removeFromSuperview];
6136 - (void) _update { _pooled
6138 status.setDelegate(self);
6140 NSString *error([database_ updateWithStatus:status]);
6143 performSelectorOnMainThread:@selector(_update_:)
6149 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
6150 [prompt_ setText:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), error]];
6153 - (void) setProgressTitle:(NSString *)title {
6155 performSelectorOnMainThread:@selector(_setProgressTitle:)
6161 - (void) setProgressPercent:(float)percent {
6163 performSelectorOnMainThread:@selector(_setProgressPercent:)
6164 withObject:[NSNumber numberWithFloat:percent]
6169 - (void) startProgress {
6172 - (void) addProgressOutput:(NSString *)output {
6174 performSelectorOnMainThread:@selector(_addProgressOutput:)
6180 - (bool) isCancelling:(size_t)received {
6184 - (void) _setProgressTitle:(NSString *)title {
6185 [prompt_ setText:title];
6188 - (void) _setProgressPercent:(NSNumber *)percent {
6189 [progress_ setProgress:[percent floatValue]];
6192 - (void) _addProgressOutput:(NSString *)output {
6197 /* Cydia:// Protocol {{{ */
6198 @interface CydiaURLProtocol : NSURLProtocol {
6203 @implementation CydiaURLProtocol
6205 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6206 NSURL *url([request URL]);
6209 NSString *scheme([[url scheme] lowercaseString]);
6210 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6215 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6219 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6220 id<NSURLProtocolClient> client([self client]);
6222 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6224 NSData *data(UIImagePNGRepresentation(icon));
6226 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6227 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6228 [client URLProtocol:self didLoadData:data];
6229 [client URLProtocolDidFinishLoading:self];
6233 - (void) startLoading {
6234 id<NSURLProtocolClient> client([self client]);
6235 NSURLRequest *request([self request]);
6237 NSURL *url([request URL]);
6238 NSString *href([url absoluteString]);
6240 NSString *path([href substringFromIndex:8]);
6241 NSRange slash([path rangeOfString:@"/"]);
6244 if (slash.location == NSNotFound) {
6248 command = [path substringToIndex:slash.location];
6249 path = [path substringFromIndex:(slash.location + 1)];
6252 Database *database([Database sharedInstance]);
6254 if ([command isEqualToString:@"package-icon"]) {
6257 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6258 Package *package([database packageWithName:path]);
6261 UIImage *icon([package icon]);
6262 [self _returnPNGWithImage:icon forRequest:request];
6263 } else if ([command isEqualToString:@"source-icon"]) {
6266 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6267 NSString *source(Simplify(path));
6268 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6270 icon = [UIImage applicationImageNamed:@"unknown.png"];
6271 [self _returnPNGWithImage:icon forRequest:request];
6272 } else if ([command isEqualToString:@"uikit-image"]) {
6275 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6276 UIImage *icon(_UIImageWithName(path));
6277 [self _returnPNGWithImage:icon forRequest:request];
6278 } else if ([command isEqualToString:@"section-icon"]) {
6281 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6282 NSString *section(Simplify(path));
6283 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6285 icon = [UIImage applicationImageNamed:@"unknown.png"];
6286 [self _returnPNGWithImage:icon forRequest:request];
6288 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6292 - (void) stopLoading {
6298 /* Sections View {{{ */
6299 @interface SectionsView : RVPage {
6300 _transient Database *database_;
6301 NSMutableArray *sections_;
6302 NSMutableArray *filtered_;
6303 UITransitionView *transition_;
6309 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6310 - (void) reloadData;
6315 @implementation SectionsView
6318 [list_ setDataSource:nil];
6319 [list_ setDelegate:nil];
6321 [sections_ release];
6322 [filtered_ release];
6323 [transition_ release];
6325 [accessory_ release];
6329 - (int) numberOfRowsInTable:(UITable *)table {
6330 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6333 - (float) table:(UITable *)table heightForRow:(int)row {
6337 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6339 reusing = [[[SectionCell alloc] init] autorelease];
6340 [(SectionCell *)reusing setSection:(editing_ ?
6341 [sections_ objectAtIndex:row] :
6342 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6343 ) editing:editing_];
6347 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6351 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6355 - (void) tableRowSelected:(NSNotification *)notification {
6356 int row = [[notification object] selectedRow];
6367 title = CYLocalize("ALL_PACKAGES");
6369 section = [filtered_ objectAtIndex:(row - 1)];
6370 name = [section name];
6373 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6376 title = CYLocalize("NO_SECTION");
6380 PackageTable *table = [[[FilteredPackageTable alloc]
6384 filter:@selector(isVisiblyUninstalledInSection:)
6388 [table setDelegate:delegate_];
6390 [book_ pushPage:table];
6393 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6394 if ((self = [super initWithBook:book]) != nil) {
6395 database_ = database;
6397 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6398 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6400 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6401 [self addSubview:transition_];
6403 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6404 [transition_ transition:0 toView:list_];
6406 UITableColumn *column = [[[UITableColumn alloc]
6407 initWithTitle:CYLocalize("NAME")
6409 width:[self frame].size.width
6412 [list_ setDataSource:self];
6413 [list_ setSeparatorStyle:1];
6414 [list_ addTableColumn:column];
6415 [list_ setDelegate:self];
6416 [list_ setReusesTableCells:YES];
6420 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6421 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6425 - (void) reloadData {
6426 NSArray *packages = [database_ packages];
6428 [sections_ removeAllObjects];
6429 [filtered_ removeAllObjects];
6432 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6433 SectionMap sections;
6434 sections.resize(64);
6436 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6440 for (Package *package in packages) {
6441 NSString *name([package section]);
6442 NSString *key(name == nil ? @"" : name);
6447 _profile(SectionsView$reloadData$Section)
6448 section = §ions[key];
6449 if (*section == nil) {
6450 _profile(SectionsView$reloadData$Section$Allocate)
6451 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6456 [*section addToCount];
6458 _profile(SectionsView$reloadData$Filter)
6459 if (![package valid] || [package installed] != nil || ![package visible])
6463 [*section addToRow];
6467 _profile(SectionsView$reloadData$Section)
6468 section = [sections objectForKey:key];
6469 if (section == nil) {
6470 _profile(SectionsView$reloadData$Section$Allocate)
6471 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6472 [sections setObject:section forKey:key];
6477 [section addToCount];
6479 _profile(SectionsView$reloadData$Filter)
6480 if (![package valid] || [package installed] != nil || ![package visible])
6490 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6491 [sections_ addObject:i->second];
6493 [sections_ addObjectsFromArray:[sections allValues]];
6496 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6498 for (Section *section in sections_) {
6499 size_t count([section row]);
6503 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6504 [section setCount:count];
6505 [filtered_ addObject:section];
6512 - (void) resetView {
6514 [self _rightButtonClicked];
6517 - (void) resetViewAnimated:(BOOL)animated {
6518 [list_ resetViewAnimated:animated];
6521 - (void) _rightButtonClicked {
6522 if ((editing_ = !editing_))
6525 [delegate_ updateData];
6526 [book_ reloadTitleForPage:self];
6527 [book_ reloadButtonsForPage:self];
6530 - (NSString *) title {
6531 return editing_ ? CYLocalize("SECTION_VISIBILITY") : CYLocalize("INSTALL_BY_SECTION");
6534 - (NSString *) backButtonTitle {
6535 return CYLocalize("SECTIONS");
6538 - (id) rightButtonTitle {
6539 return [sections_ count] == 0 ? nil : editing_ ? CYLocalize("DONE") : CYLocalize("EDIT");
6542 - (UINavigationButtonStyle) rightButtonStyle {
6543 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6546 - (UIView *) accessoryView {
6552 /* Changes View {{{ */
6553 @interface ChangesView : RVPage {
6554 _transient Database *database_;
6555 NSMutableArray *packages_;
6556 NSMutableArray *sections_;
6557 UISectionList *list_;
6561 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6562 - (void) reloadData;
6566 @implementation ChangesView
6569 [[list_ table] setDelegate:nil];
6570 [list_ setDataSource:nil];
6572 [packages_ release];
6573 [sections_ release];
6578 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6579 return [sections_ count];
6582 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6583 return [[sections_ objectAtIndex:section] name];
6586 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6587 return [[sections_ objectAtIndex:section] row];
6590 - (int) numberOfRowsInTable:(UITable *)table {
6591 return [packages_ count];
6594 - (float) table:(UITable *)table heightForRow:(int)row {
6595 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6598 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6600 reusing = [[[PackageCell alloc] init] autorelease];
6601 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6605 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6609 - (void) tableRowSelected:(NSNotification *)notification {
6610 int row = [[notification object] selectedRow];
6613 Package *package = [packages_ objectAtIndex:row];
6614 PackageView *view([delegate_ packageView]);
6615 [view setDelegate:delegate_];
6616 [view setPackage:package];
6617 [book_ pushPage:view];
6620 - (void) _leftButtonClicked {
6621 [(CYBook *)book_ update];
6622 [self reloadButtons];
6625 - (void) _rightButtonClicked {
6626 [delegate_ distUpgrade];
6629 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6630 if ((self = [super initWithBook:book]) != nil) {
6631 database_ = database;
6633 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6634 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6636 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6637 [self addSubview:list_];
6639 [list_ setShouldHideHeaderInShortLists:NO];
6640 [list_ setDataSource:self];
6641 //[list_ setSectionListStyle:1];
6643 UITableColumn *column = [[[UITableColumn alloc]
6644 initWithTitle:CYLocalize("NAME")
6646 width:[self frame].size.width
6649 UITable *table = [list_ table];
6650 [table setSeparatorStyle:1];
6651 [table addTableColumn:column];
6652 [table setDelegate:self];
6653 [table setReusesTableCells:YES];
6657 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6658 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6662 - (void) reloadData {
6663 NSArray *packages = [database_ packages];
6665 [packages_ removeAllObjects];
6666 [sections_ removeAllObjects];
6669 for (Package *package in packages)
6671 [package installed] == nil && [package valid] && [package visible] ||
6672 [package upgradableAndEssential:YES]
6674 [packages_ addObject:package];
6677 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6680 Section *upgradable = [[[Section alloc] initWithName:CYLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6681 Section *ignored = [[[Section alloc] initWithName:CYLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6682 Section *section = nil;
6686 bool unseens = false;
6688 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6690 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6691 Package *package = [packages_ objectAtIndex:offset];
6693 BOOL uae = [package upgradableAndEssential:YES];
6699 _profile(ChangesView$reloadData$Remember)
6700 seen = [package seen];
6703 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6708 name = CYLocalize("UNKNOWN");
6710 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6714 _profile(ChangesView$reloadData$Allocate)
6715 name = [NSString stringWithFormat:CYLocalize("NEW_AT"), name];
6716 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6717 [sections_ addObject:section];
6721 [section addToCount];
6722 } else if ([package ignored])
6723 [ignored addToCount];
6726 [upgradable addToCount];
6731 CFRelease(formatter);
6734 Section *last = [sections_ lastObject];
6735 size_t count = [last count];
6736 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6737 [sections_ removeLastObject];
6740 if ([ignored count] != 0)
6741 [sections_ insertObject:ignored atIndex:0];
6743 [sections_ insertObject:upgradable atIndex:0];
6746 [self reloadButtons];
6749 - (void) resetViewAnimated:(BOOL)animated {
6750 [list_ resetViewAnimated:animated];
6753 - (NSString *) leftButtonTitle {
6754 return [(CYBook *)book_ updating] ? nil : CYLocalize("REFRESH");
6757 - (id) rightButtonTitle {
6758 return upgrades_ == 0 ? nil : [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6761 - (NSString *) title {
6762 return CYLocalize("CHANGES");
6767 /* Search View {{{ */
6768 @protocol SearchViewDelegate
6769 - (void) showKeyboard:(BOOL)show;
6772 @interface SearchView : RVPage {
6774 UISearchField *field_;
6775 UITransitionView *transition_;
6776 FilteredPackageTable *table_;
6777 UIPreferencesTable *advanced_;
6783 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6784 - (void) reloadData;
6788 @implementation SearchView
6791 [field_ setDelegate:nil];
6793 [accessory_ release];
6795 [transition_ release];
6797 [advanced_ release];
6802 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6806 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6808 case 0: return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("ADVANCED_SEARCH"), CYLocalize("COMING_SOON")];
6810 default: _assert(false);
6814 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6818 default: _assert(false);
6822 - (void) _showKeyboard:(BOOL)show {
6823 CGSize keysize = [UIKeyboard defaultSize];
6824 CGRect keydown = [book_ pageBounds];
6825 CGRect keyup = keydown;
6826 keyup.size.height -= keysize.height - ButtonBarHeight_;
6828 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6830 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6831 [animation setSignificantRectFields:8];
6834 [animation setStartFrame:keydown];
6835 [animation setEndFrame:keyup];
6837 [animation setStartFrame:keyup];
6838 [animation setEndFrame:keydown];
6841 UIAnimator *animator = [UIAnimator sharedAnimator];
6844 addAnimations:[NSArray arrayWithObjects:animation, nil]
6845 withDuration:(KeyboardTime_ - delay)
6850 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6852 [delegate_ showKeyboard:show];
6855 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6856 [self _showKeyboard:YES];
6859 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
6860 [self _showKeyboard:NO];
6863 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
6865 NSString *text([field_ text]);
6866 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6872 - (void) textFieldClearButtonPressed:(UITextField *)field {
6876 - (void) keyboardInputShouldDelete:(id)input {
6880 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
6881 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6885 [field_ resignFirstResponder];
6890 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6891 if ((self = [super initWithBook:book]) != nil) {
6892 CGRect pageBounds = [book_ pageBounds];
6894 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6895 [self addSubview:transition_];
6897 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6899 [advanced_ setReusesTableCells:YES];
6900 [advanced_ setDataSource:self];
6901 [advanced_ reloadData];
6903 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6904 CGColor dimmed(space_, 0, 0, 0, 0.5);
6905 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
6907 table_ = [[FilteredPackageTable alloc]
6911 filter:@selector(isUnfilteredAndSearchedForBy:)
6915 [table_ setShouldHideHeaderInShortLists:NO];
6916 [transition_ transition:0 toView:table_];
6925 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
6932 [self bounds].size.width - area.origin.x - 18;
6934 area.size.height = [UISearchField defaultHeight];
6936 field_ = [[UISearchField alloc] initWithFrame:area];
6938 UIFont *font = [UIFont systemFontOfSize:16];
6939 [field_ setFont:font];
6941 [field_ setPlaceholder:CYLocalize("SEARCH_EX")];
6942 [field_ setDelegate:self];
6944 [field_ setPaddingTop:5];
6946 UITextInputTraits *traits([field_ textInputTraits]);
6947 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6948 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6949 [traits setReturnKeyType:UIReturnKeySearch];
6951 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
6953 accessory_ = [[UIView alloc] initWithFrame:accrect];
6954 [accessory_ addSubview:field_];
6956 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
6957 [configure setShowPressFeedback:YES];
6958 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
6959 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
6960 [accessory_ addSubview:configure];*/
6962 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6963 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6969 LKAnimation *animation = [LKTransition animation];
6970 [animation setType:@"oglFlip"];
6971 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
6972 [animation setFillMode:@"extended"];
6973 [animation setTransitionFlags:3];
6974 [animation setDuration:10];
6975 [animation setSpeed:0.35];
6976 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
6977 [[transition_ _layer] addAnimation:animation forKey:0];
6978 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
6979 flipped_ = !flipped_;
6983 - (void) configurePushed {
6984 [field_ resignFirstResponder];
6988 - (void) resetViewAnimated:(BOOL)animated {
6991 [table_ resetViewAnimated:animated];
6994 - (void) _reloadData {
6997 - (void) reloadData {
7000 [table_ setObject:[field_ text]];
7001 _profile(SearchView$reloadData)
7002 [table_ reloadData];
7005 [table_ resetCursor];
7008 - (UIView *) accessoryView {
7012 - (NSString *) title {
7016 - (NSString *) backButtonTitle {
7017 return CYLocalize("SEARCH");
7020 - (void) setDelegate:(id)delegate {
7021 [table_ setDelegate:delegate];
7022 [super setDelegate:delegate];
7028 @interface SettingsView : RVPage {
7029 _transient Database *database_;
7032 UIPreferencesTable *table_;
7033 _UISwitchSlider *subscribedSwitch_;
7034 _UISwitchSlider *ignoredSwitch_;
7035 UIPreferencesControlTableCell *subscribedCell_;
7036 UIPreferencesControlTableCell *ignoredCell_;
7039 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7043 @implementation SettingsView
7046 [table_ setDataSource:nil];
7049 if (package_ != nil)
7052 [subscribedSwitch_ release];
7053 [ignoredSwitch_ release];
7054 [subscribedCell_ release];
7055 [ignoredCell_ release];
7059 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7060 if (package_ == nil)
7066 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7067 if (package_ == nil)
7074 default: _assert(false);
7080 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7081 if (package_ == nil)
7088 default: _assert(false);
7094 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7095 if (package_ == nil)
7102 default: _assert(false);
7108 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7109 if (package_ == nil)
7112 _UISwitchSlider *slider([cell control]);
7113 BOOL value([slider value] != 0);
7114 NSMutableDictionary *metadata([package_ metadata]);
7117 if (NSNumber *number = [metadata objectForKey:key])
7118 before = [number boolValue];
7122 if (value != before) {
7123 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7125 [delegate_ updateData];
7129 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7130 [self onSomething:cell withKey:@"IsSubscribed"];
7133 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7134 [self onSomething:cell withKey:@"IsIgnored"];
7137 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7138 if (package_ == nil)
7142 case 0: switch (row) {
7144 return subscribedCell_;
7146 return ignoredCell_;
7147 default: _assert(false);
7150 case 1: switch (row) {
7152 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7153 [cell setShowSelection:NO];
7154 [cell setTitle:CYLocalize("SHOW_ALL_CHANGES_EX")];
7158 default: _assert(false);
7161 default: _assert(false);
7167 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7168 if ((self = [super initWithBook:book])) {
7169 database_ = database;
7170 name_ = [package retain];
7172 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7173 [self addSubview:table_];
7175 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7176 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
7178 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7179 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
7181 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7182 [subscribedCell_ setShowSelection:NO];
7183 [subscribedCell_ setTitle:CYLocalize("SHOW_ALL_CHANGES")];
7184 [subscribedCell_ setControl:subscribedSwitch_];
7186 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7187 [ignoredCell_ setShowSelection:NO];
7188 [ignoredCell_ setTitle:CYLocalize("IGNORE_UPGRADES")];
7189 [ignoredCell_ setControl:ignoredSwitch_];
7191 [table_ setDataSource:self];
7196 - (void) resetViewAnimated:(BOOL)animated {
7197 [table_ resetViewAnimated:animated];
7200 - (void) reloadData {
7201 if (package_ != nil)
7202 [package_ autorelease];
7203 package_ = [database_ packageWithName:name_];
7204 if (package_ != nil) {
7206 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7207 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7210 [table_ reloadData];
7213 - (NSString *) title {
7214 return CYLocalize("SETTINGS");
7219 /* Signature View {{{ */
7220 @interface SignatureView : BrowserView {
7221 _transient Database *database_;
7225 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7229 @implementation SignatureView
7236 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7238 [super webView:sender didClearWindowObject:window forFrame:frame];
7241 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7242 if ((self = [super initWithBook:book]) != nil) {
7243 database_ = database;
7244 package_ = [package retain];
7249 - (void) resetViewAnimated:(BOOL)animated {
7252 - (void) reloadData {
7253 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7259 @interface Cydia : UIApplication <
7260 ConfirmationViewDelegate,
7261 ProgressViewDelegate,
7270 UIToolbar *buttonbar_;
7274 NSMutableArray *essential_;
7275 NSMutableArray *broken_;
7277 Database *database_;
7278 ProgressView *progress_;
7282 UIKeyboard *keyboard_;
7283 UIProgressHUD *hud_;
7285 SectionsView *sections_;
7286 ChangesView *changes_;
7287 ManageView *manage_;
7288 SearchView *search_;
7290 NSMutableArray *details_;
7295 @implementation Cydia
7298 if ([broken_ count] != 0) {
7299 int count = [broken_ count];
7301 UIActionSheet *sheet = [[[UIActionSheet alloc]
7302 initWithTitle:(count == 1 ? CYLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:CYLocalize("HALFINSTALLED_PACKAGES"), count])
7303 buttons:[NSArray arrayWithObjects:
7304 CYLocalize("FORCIBLY_CLEAR"),
7305 CYLocalize("TEMPORARY_IGNORE"),
7307 defaultButtonIndex:0
7312 [sheet setBodyText:CYLocalize("HALFINSTALLED_PACKAGE_EX")];
7313 [sheet popupAlertAnimated:YES];
7314 } else if (!Ignored_ && [essential_ count] != 0) {
7315 int count = [essential_ count];
7317 UIActionSheet *sheet = [[[UIActionSheet alloc]
7318 initWithTitle:(count == 1 ? CYLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:CYLocalize("ESSENTIAL_UPGRADES"), count])
7319 buttons:[NSArray arrayWithObjects:
7320 CYLocalize("UPGRADE_ESSENTIAL"),
7321 CYLocalize("COMPLETE_UPGRADE"),
7322 CYLocalize("TEMPORARY_IGNORE"),
7324 defaultButtonIndex:0
7329 [sheet setBodyText:CYLocalize("ESSENTIAL_UPGRADE_EX")];
7330 [sheet popupAlertAnimated:YES];
7334 - (void) _reloadData {
7337 static bool loaded(false);
7338 UIProgressHUD *hud([self addProgressHUD]);
7339 [hud setText:(loaded ? CYLocalize("RELOADING_DATA") : CYLocalize("LOADING_DATA"))];
7342 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7345 [self removeProgressHUD:hud];
7349 [essential_ removeAllObjects];
7350 [broken_ removeAllObjects];
7352 NSArray *packages = [database_ packages];
7353 for (Package *package in packages) {
7355 [broken_ addObject:package];
7356 if ([package upgradableAndEssential:NO]) {
7357 if ([package essential])
7358 [essential_ addObject:package];
7364 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7365 [buttonbar_ setBadgeValue:badge forButton:3];
7366 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7367 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7368 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7369 [self setApplicationBadge:badge];
7371 [self setApplicationBadgeString:badge];
7373 [buttonbar_ setBadgeValue:nil forButton:3];
7374 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7375 [buttonbar_ setBadgeAnimated:NO forButton:3];
7376 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7377 [self removeApplicationBadge];
7378 else // XXX: maybe use setApplicationBadgeString also?
7379 [self setApplicationIconBadgeNumber:0];
7383 [buttonbar_ setBadgeValue:nil forButton:4];
7387 // XXX: what is this line of code for?
7388 if ([packages count] == 0);
7389 else if (Loaded_ || ManualRefresh) loaded:
7394 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7395 NSTimeInterval interval([update timeIntervalSinceNow]);
7396 if (interval <= 0 && interval > -600)
7404 - (void) _saveConfig {
7407 NSString *error(nil);
7408 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7410 NSError *error(nil);
7411 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7412 NSLog(@"failure to save metadata data: %@", error);
7415 NSLog(@"failure to serialize metadata: %@", error);
7423 - (void) updateData {
7426 /* XXX: this is just stupid */
7427 if (tag_ != 2 && sections_ != nil)
7428 [sections_ reloadData];
7429 if (tag_ != 3 && changes_ != nil)
7430 [changes_ reloadData];
7431 if (tag_ != 5 && search_ != nil)
7432 [search_ reloadData];
7442 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7443 _assert(file != NULL);
7445 NSArray *keys = [Sources_ allKeys];
7447 for (NSString *key in keys) {
7448 NSDictionary *source = [Sources_ objectForKey:key];
7450 fprintf(file, "%s %s %s\n",
7451 [[source objectForKey:@"Type"] UTF8String],
7452 [[source objectForKey:@"URI"] UTF8String],
7453 [[source objectForKey:@"Distribution"] UTF8String]
7462 detachNewThreadSelector:@selector(update_)
7465 title:CYLocalize("UPDATING_SOURCES")
7469 - (void) reloadData {
7470 @synchronized (self) {
7471 if (confirm_ == nil)
7477 pkgProblemResolver *resolver = [database_ resolver];
7479 resolver->InstallProtect();
7480 if (!resolver->Resolve(true))
7484 - (void) popUpBook:(RVBook *)book {
7485 [underlay_ popSubview:book];
7488 - (CGRect) popUpBounds {
7489 return [underlay_ bounds];
7493 [database_ prepare];
7495 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7496 [confirm_ setDelegate:self];
7498 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7499 [page setDelegate:self];
7501 [confirm_ setPage:page];
7502 [self popUpBook:confirm_];
7506 @synchronized (self) {
7511 - (void) clearPackage:(Package *)package {
7512 @synchronized (self) {
7519 - (void) installPackage:(Package *)package {
7520 @synchronized (self) {
7527 - (void) removePackage:(Package *)package {
7528 @synchronized (self) {
7535 - (void) distUpgrade {
7536 @synchronized (self) {
7537 [database_ upgrade];
7543 [self slideUp:[[[UIActionSheet alloc]
7545 buttons:[NSArray arrayWithObjects:CYLocalize("CONTINUE_QUEUING"), CYLocalize("CANCEL_CLEAR"), nil]
7546 defaultButtonIndex:1
7553 @synchronized (self) {
7556 if (confirm_ != nil) {
7564 [overlay_ removeFromSuperview];
7568 detachNewThreadSelector:@selector(perform)
7571 title:CYLocalize("RUNNING")
7575 - (void) bootstrap_ {
7577 [database_ upgrade];
7578 [database_ prepare];
7579 [database_ perform];
7582 /* XXX: replace and localize */
7583 - (void) bootstrap {
7585 detachNewThreadSelector:@selector(bootstrap_)
7588 title:@"Bootstrap Install"
7592 - (void) progressViewIsComplete:(ProgressView *)progress {
7593 if (confirm_ != nil) {
7594 [underlay_ addSubview:overlay_];
7595 [confirm_ popFromSuperviewAnimated:NO];
7601 - (void) setPage:(RVPage *)page {
7602 [page resetViewAnimated:NO];
7603 [page setDelegate:self];
7604 [book_ setPage:page];
7607 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7608 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7609 [browser loadURL:url];
7613 - (void) _setHomePage {
7614 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7617 - (SectionsView *) sectionsView {
7618 if (sections_ == nil)
7619 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7623 - (void) buttonBarItemTapped:(id)sender {
7624 unsigned tag = [sender tag];
7626 [book_ resetViewAnimated:YES];
7628 } else if (tag_ == 2 && tag != 2)
7629 [[self sectionsView] resetView];
7632 case 1: [self _setHomePage]; break;
7634 case 2: [self setPage:[self sectionsView]]; break;
7635 case 3: [self setPage:changes_]; break;
7636 case 4: [self setPage:manage_]; break;
7637 case 5: [self setPage:search_]; break;
7639 default: _assert(false);
7645 - (void) applicationWillSuspend {
7647 [super applicationWillSuspend];
7650 - (void) askForSettings {
7651 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
7653 UIActionSheet *role = [[[UIActionSheet alloc]
7654 initWithTitle:CYLocalize("WHO_ARE_YOU")
7655 buttons:[NSArray arrayWithObjects:
7656 [NSString stringWithFormat:parenthetical, CYLocalize("USER"), CYLocalize("USER_EX")],
7657 [NSString stringWithFormat:parenthetical, CYLocalize("HACKER"), CYLocalize("HACKER_EX")],
7658 [NSString stringWithFormat:parenthetical, CYLocalize("DEVELOPER"), CYLocalize("DEVELOPER_EX")],
7660 defaultButtonIndex:-1
7665 [role setBodyText:CYLocalize("ROLE_EX")];
7666 [role popupAlertAnimated:YES];
7669 - (void) setPackageView:(PackageView *)view {
7671 [view setPackage:nil];
7672 if ([details_ count] < 3)
7673 [details_ addObject:view];
7677 - (PackageView *) _packageView {
7678 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7681 - (PackageView *) packageView {
7683 size_t count([details_ count]);
7686 view = [self _packageView];
7688 [details_ addObject:[self _packageView]];
7690 view = [[[details_ lastObject] retain] autorelease];
7691 [details_ removeLastObject];
7701 [self setStatusBarShowsProgress:NO];
7702 [self removeProgressHUD:hud_];
7707 pid_t pid = ExecFork();
7709 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7710 perror("launchctl stop");
7717 [self askForSettings];
7722 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7724 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7725 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7726 0, 0, screenrect.size.width, screenrect.size.height - 48
7727 ) database:database_];
7729 [book_ setDelegate:self];
7731 [overlay_ addSubview:book_];
7733 NSArray *buttonitems = [NSArray arrayWithObjects:
7734 [NSDictionary dictionaryWithObjectsAndKeys:
7735 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7736 @"home-up.png", kUIButtonBarButtonInfo,
7737 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7738 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7739 self, kUIButtonBarButtonTarget,
7740 @"Cydia", kUIButtonBarButtonTitle,
7741 @"0", kUIButtonBarButtonType,
7744 [NSDictionary dictionaryWithObjectsAndKeys:
7745 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7746 @"install-up.png", kUIButtonBarButtonInfo,
7747 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7748 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7749 self, kUIButtonBarButtonTarget,
7750 CYLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7751 @"0", kUIButtonBarButtonType,
7754 [NSDictionary dictionaryWithObjectsAndKeys:
7755 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7756 @"changes-up.png", kUIButtonBarButtonInfo,
7757 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7758 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7759 self, kUIButtonBarButtonTarget,
7760 CYLocalize("CHANGES"), kUIButtonBarButtonTitle,
7761 @"0", kUIButtonBarButtonType,
7764 [NSDictionary dictionaryWithObjectsAndKeys:
7765 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7766 @"manage-up.png", kUIButtonBarButtonInfo,
7767 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7768 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7769 self, kUIButtonBarButtonTarget,
7770 CYLocalize("MANAGE"), kUIButtonBarButtonTitle,
7771 @"0", kUIButtonBarButtonType,
7774 [NSDictionary dictionaryWithObjectsAndKeys:
7775 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7776 @"search-up.png", kUIButtonBarButtonInfo,
7777 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7778 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7779 self, kUIButtonBarButtonTarget,
7780 CYLocalize("SEARCH"), kUIButtonBarButtonTitle,
7781 @"0", kUIButtonBarButtonType,
7785 buttonbar_ = [[UIToolbar alloc]
7787 withFrame:CGRectMake(
7788 0, screenrect.size.height - ButtonBarHeight_,
7789 screenrect.size.width, ButtonBarHeight_
7791 withItemList:buttonitems
7794 [buttonbar_ setDelegate:self];
7795 [buttonbar_ setBarStyle:1];
7796 [buttonbar_ setButtonBarTrackingMode:2];
7798 int buttons[5] = {1, 2, 3, 4, 5};
7799 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7800 [buttonbar_ showButtonGroup:0 withDuration:0];
7802 for (int i = 0; i != 5; ++i)
7803 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7804 i * 64 + 2, 1, 60, ButtonBarHeight_
7807 [buttonbar_ showSelectionForButton:1];
7808 [overlay_ addSubview:buttonbar_];
7810 [UIKeyboard initImplementationNow];
7811 CGSize keysize = [UIKeyboard defaultSize];
7812 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7813 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7814 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
7815 [overlay_ addSubview:keyboard_];
7818 [underlay_ addSubview:overlay_];
7822 [self sectionsView];
7823 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7824 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7826 manage_ = (ManageView *) [[self
7827 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7828 withClass:[ManageView class]
7831 details_ = [[NSMutableArray alloc] initWithCapacity:4];
7832 [details_ addObject:[self _packageView]];
7833 [details_ addObject:[self _packageView]];
7840 [self _setHomePage];
7843 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7844 NSString *context([sheet context]);
7846 if ([context isEqualToString:@"missing"])
7848 else if ([context isEqualToString:@"cancel"]) {
7866 @synchronized (self) {
7871 [buttonbar_ setBadgeValue:CYLocalize("Q_D") forButton:4];
7875 if (confirm_ != nil) {
7880 } else if ([context isEqualToString:@"fixhalf"]) {
7883 @synchronized (self) {
7884 for (Package *broken in broken_) {
7887 NSString *id = [broken id];
7888 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7889 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7890 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7891 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7900 [broken_ removeAllObjects];
7909 } else if ([context isEqualToString:@"role"]) {
7911 case 1: Role_ = @"User"; break;
7912 case 2: Role_ = @"Hacker"; break;
7913 case 3: Role_ = @"Developer"; break;
7920 bool reset = Settings_ != nil;
7922 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7926 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7936 } else if ([context isEqualToString:@"upgrade"]) {
7939 @synchronized (self) {
7940 for (Package *essential in essential_)
7941 [essential install];
7964 - (void) reorganize { _pooled
7965 system("/usr/libexec/cydia/free.sh");
7966 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
7969 - (void) applicationSuspend:(__GSEvent *)event {
7970 if (hud_ == nil && ![progress_ isRunning])
7971 [super applicationSuspend:event];
7974 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7976 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7979 - (void) _setSuspended:(BOOL)value {
7981 [super _setSuspended:value];
7984 - (UIProgressHUD *) addProgressHUD {
7985 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
7986 [window_ setUserInteractionEnabled:NO];
7988 [progress_ addSubview:hud];
7992 - (void) removeProgressHUD:(UIProgressHUD *)hud {
7994 [hud removeFromSuperview];
7995 [window_ setUserInteractionEnabled:YES];
7998 - (void) openMailToURL:(NSURL *)url {
7999 // XXX: this makes me sad
8001 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
8003 [UIApp openURL:url];// asPanel:YES];
8007 - (void) clearFirstResponder {
8008 if (id responder = [window_ firstResponder])
8009 [responder resignFirstResponder];
8012 - (RVPage *) pageForPackage:(NSString *)name {
8013 if (Package *package = [database_ packageWithName:name]) {
8014 PackageView *view([self packageView]);
8015 [view setPackage:package];
8018 UIActionSheet *sheet = [[[UIActionSheet alloc]
8019 initWithTitle:CYLocalize("CANNOT_LOCATE_PACKAGE")
8020 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
8021 defaultButtonIndex:0
8026 [sheet setBodyText:[NSString stringWithFormat:CYLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
8028 [sheet popupAlertAnimated:YES];
8033 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8037 NSString *scheme([[url scheme] lowercaseString]);
8038 if (![scheme isEqualToString:@"cydia"])
8040 NSString *path([url absoluteString]);
8041 if ([path length] < 8)
8043 path = [path substringFromIndex:8];
8044 if (![path hasPrefix:@"/"])
8045 path = [@"/" stringByAppendingString:path];
8047 if ([path isEqualToString:@"/add-source"])
8048 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8049 else if ([path isEqualToString:@"/storage"])
8050 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[BrowserView class]];
8051 else if ([path isEqualToString:@"/sources"])
8052 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8053 else if ([path isEqualToString:@"/packages"])
8054 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8055 else if ([path hasPrefix:@"/url/"])
8056 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[BrowserView class]];
8057 else if ([path hasPrefix:@"/launch/"])
8058 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8059 else if ([path hasPrefix:@"/package-settings/"])
8060 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8061 else if ([path hasPrefix:@"/package-signature/"])
8062 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8063 else if ([path hasPrefix:@"/package/"])
8064 return [self pageForPackage:[path substringFromIndex:9]];
8065 else if ([path hasPrefix:@"/files/"]) {
8066 NSString *name = [path substringFromIndex:7];
8068 if (Package *package = [database_ packageWithName:name]) {
8069 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8070 [files setPackage:package];
8078 - (void) applicationOpenURL:(NSURL *)url {
8079 [super applicationOpenURL:url];
8081 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8082 [self setPage:page];
8083 [buttonbar_ showSelectionForButton:tag];
8088 - (void) applicationDidFinishLaunching:(id)unused {
8090 Font12_ = [[UIFont systemFontOfSize:12] retain];
8091 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8092 Font14_ = [[UIFont systemFontOfSize:14] retain];
8093 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8094 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8098 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8099 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8101 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8103 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8104 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
8106 [window_ orderFront:self];
8107 [window_ makeKey:self];
8108 [window_ setHidden:NO];
8110 database_ = [Database sharedInstance];
8111 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8112 [database_ setDelegate:progress_];
8113 [window_ setContentView:progress_];
8115 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8116 [progress_ setContentView:underlay_];
8118 [progress_ resetView];
8121 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8122 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8123 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8124 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8125 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8126 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
8127 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
8129 [self setIdleTimerDisabled:YES];
8131 hud_ = [[self addProgressHUD] retain];
8132 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8134 [self setStatusBarShowsProgress:YES];
8137 detachNewThreadSelector:@selector(reorganize)
8145 - (void) showKeyboard:(BOOL)show {
8146 CGSize keysize = [UIKeyboard defaultSize];
8147 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8148 CGRect keyup = keydown;
8149 keyup.origin.y -= keysize.height;
8151 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
8152 [animation setSignificantRectFields:2];
8155 [animation setStartFrame:keydown];
8156 [animation setEndFrame:keyup];
8157 [keyboard_ activate];
8159 [animation setStartFrame:keyup];
8160 [animation setEndFrame:keydown];
8161 [keyboard_ deactivate];
8164 [[UIAnimator sharedAnimator]
8165 addAnimations:[NSArray arrayWithObjects:animation, nil]
8166 withDuration:KeyboardTime_
8171 - (void) slideUp:(UIActionSheet *)alert {
8173 [alert presentSheetFromButtonBar:buttonbar_];
8175 [alert presentSheetInView:overlay_];
8180 void AddPreferences(NSString *plist) { _pooled
8181 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
8182 _assert(settings != NULL);
8183 NSMutableArray *items = [settings objectForKey:@"items"];
8187 for (NSMutableDictionary *item in items) {
8188 NSString *label = [item objectForKey:@"label"];
8189 if (label != nil && [label isEqualToString:@"Cydia"]) {
8196 for (size_t i(0); i != [items count]; ++i) {
8197 NSDictionary *item([items objectAtIndex:i]);
8198 NSString *label = [item objectForKey:@"label"];
8199 if (label != nil && [label isEqualToString:@"General"]) {
8200 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
8201 @"CydiaSettings", @"bundle",
8202 @"PSLinkCell", @"cell",
8203 [NSNumber numberWithBool:YES], @"hasIcon",
8204 [NSNumber numberWithBool:YES], @"isController",
8206 nil] atIndex:(i + 1)];
8212 _assert([settings writeToFile:plist atomically:YES] == YES);
8217 id Alloc_(id self, SEL selector) {
8218 id object = alloc_(self, selector);
8219 lprintf("[%s]A-%p\n", self->isa->name, object);
8224 id Dealloc_(id self, SEL selector) {
8225 id object = dealloc_(self, selector);
8226 lprintf("[%s]D-%p\n", self->isa->name, object);
8230 Class $WebDefaultUIKitDelegate;
8232 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
8234 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
8235 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8236 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8237 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
8240 int main(int argc, char *argv[]) { _pooled
8243 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8245 /* Library Hacks {{{ */
8246 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8248 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8249 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8250 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8251 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8252 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8255 /* Set Locale {{{ */
8256 Locale_ = CFLocaleCopyCurrent();
8257 Languages_ = [NSLocale preferredLanguages];
8258 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8259 //NSLog(@"%@", [Languages_ description]);
8261 if (Languages_ == nil || [Languages_ count] == 0)
8264 lang = [[Languages_ objectAtIndex:0] UTF8String];
8265 setenv("LANG", lang, true);
8266 //std::setlocale(LC_ALL, lang);
8267 NSLog(@"Setting Language: %s", lang);
8270 // XXX: apr_app_initialize?
8273 /* Parse Arguments {{{ */
8274 bool substrate(false);
8280 for (int argi(1); argi != argc; ++argi)
8281 if (strcmp(argv[argi], "--") == 0) {
8283 argv[argi] = argv[0];
8289 for (int argi(1); argi != arge; ++argi)
8290 if (strcmp(args[argi], "--bootstrap") == 0)
8292 else if (strcmp(args[argi], "--substrate") == 0)
8295 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8300 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
8301 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
8302 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
8303 Sounds_Keyboard_ = [keyboard boolValue];
8306 App_ = [[NSBundle mainBundle] bundlePath];
8307 Home_ = NSHomeDirectory();
8312 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8313 alloc_ = alloc->method_imp;
8314 alloc->method_imp = (IMP) &Alloc_;*/
8316 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8317 dealloc_ = dealloc->method_imp;
8318 dealloc->method_imp = (IMP) &Dealloc_;*/
8323 size = sizeof(maxproc);
8324 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8325 perror("sysctlbyname(\"kern.maxproc\", ?)");
8326 else if (maxproc < 64) {
8328 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8329 perror("sysctlbyname(\"kern.maxproc\", #)");
8332 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8333 char *machine = new char[size];
8334 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8335 perror("sysctlbyname(\"hw.machine\", ?)");
8339 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8341 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8342 Build_ = [system objectForKey:@"ProductBuildVersion"];
8343 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8344 Product_ = [info objectForKey:@"SafariProductVersion"];
8345 Safari_ = [info objectForKey:@"CFBundleVersion"];
8348 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8349 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
8351 /* Load Database {{{ */
8353 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8355 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8358 if (Metadata_ == NULL)
8359 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8361 Settings_ = [Metadata_ objectForKey:@"Settings"];
8363 Packages_ = [Metadata_ objectForKey:@"Packages"];
8364 Sections_ = [Metadata_ objectForKey:@"Sections"];
8365 Sources_ = [Metadata_ objectForKey:@"Sources"];
8368 if (Settings_ != nil)
8369 Role_ = [Settings_ objectForKey:@"Role"];
8371 if (Packages_ == nil) {
8372 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8373 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8376 if (Sections_ == nil) {
8377 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8378 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8381 if (Sources_ == nil) {
8382 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8383 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8388 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8391 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8392 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8393 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8394 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8396 if (access("/User", F_OK) != 0) {
8398 system("/usr/libexec/cydia/firmware.sh");
8402 _assert([[NSFileManager defaultManager]
8403 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8404 withIntermediateDirectories:YES
8409 if (access("/tmp/cydia.chk", F_OK) == 0) {
8410 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8411 _assert(errno == ENOENT);
8412 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8413 _assert(errno == ENOENT);
8416 _assert(pkgInitConfig(*_config));
8417 _assert(pkgInitSystem(*_config, _system));
8420 _config->Set("APT::Acquire::Translation", lang);
8421 _config->Set("Acquire::http::Timeout", 15);
8422 _config->Set("Acquire::http::MaxParallel", 4);
8424 /* Color Choices {{{ */
8425 space_ = CGColorSpaceCreateDeviceRGB();
8427 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8428 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8429 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8430 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8431 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8432 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8433 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8434 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8435 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8436 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8437 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8438 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8439 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8440 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8441 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8444 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8445 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8448 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8450 /* UIKit Configuration {{{ */
8451 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8452 if ($GSFontSetUseLegacyFontMetrics != NULL)
8453 $GSFontSetUseLegacyFontMetrics(YES);
8455 UIKeyboardDisableAutomaticAppearance();
8459 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8461 CGColorSpaceRelease(space_);