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 const char *StripVersion_(const char *version) {
1154 const char *colon(strchr(version, ':'));
1156 version = colon + 1;
1160 CFStringRef StripVersion(const char *version) {
1161 const char *colon(strchr(version, ':'));
1163 version = colon + 1;
1164 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1166 return CFCString(version);
1169 NSString *LocalizeSection(NSString *section) {
1170 static Pcre title_r("^(.*?) \\((.*)\\)$");
1171 if (title_r(section)) {
1172 NSString *parent(title_r[1]);
1173 NSString *child(title_r[2]);
1175 return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"),
1176 LocalizeSection(parent),
1177 LocalizeSection(child)
1181 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1184 NSString *Simplify(NSString *title) {
1185 const char *data = [title UTF8String];
1186 size_t size = [title length];
1188 static Pcre square_r("^\\[(.*)\\]$");
1189 if (square_r(data, size))
1190 return Simplify(square_r[1]);
1192 static Pcre paren_r("^\\((.*)\\)$");
1193 if (paren_r(data, size))
1194 return Simplify(paren_r[1]);
1196 static Pcre title_r("^(.*?) \\((.*)\\)$");
1197 if (title_r(data, size))
1198 return Simplify(title_r[1]);
1204 bool isSectionVisible(NSString *section) {
1205 NSDictionary *metadata([Sections_ objectForKey:section]);
1206 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1207 return hidden == nil || ![hidden boolValue];
1210 /* Delegate Prototypes {{{ */
1214 @interface NSObject (ProgressDelegate)
1217 @implementation NSObject(ProgressDelegate)
1219 - (void) _setProgressError:(NSArray *)args {
1220 [self performSelector:@selector(setProgressError:forPackage:)
1221 withObject:[args objectAtIndex:0]
1222 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1228 @protocol ProgressDelegate
1229 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1230 - (void) setProgressTitle:(NSString *)title;
1231 - (void) setProgressPercent:(float)percent;
1232 - (void) startProgress;
1233 - (void) addProgressOutput:(NSString *)output;
1234 - (bool) isCancelling:(size_t)received;
1237 @protocol ConfigurationDelegate
1238 - (void) repairWithSelector:(SEL)selector;
1239 - (void) setConfigurationData:(NSString *)data;
1244 @protocol CydiaDelegate
1245 - (void) setPackageView:(PackageView *)view;
1246 - (void) clearPackage:(Package *)package;
1247 - (void) installPackage:(Package *)package;
1248 - (void) removePackage:(Package *)package;
1249 - (void) slideUp:(UIActionSheet *)alert;
1250 - (void) distUpgrade;
1251 - (void) updateData;
1253 - (void) askForSettings;
1254 - (UIProgressHUD *) addProgressHUD;
1255 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1256 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag;
1257 - (RVPage *) pageForPackage:(NSString *)name;
1258 - (void) openMailToURL:(NSURL *)url;
1259 - (void) clearFirstResponder;
1260 - (PackageView *) packageView;
1264 /* Status Delegation {{{ */
1266 public pkgAcquireStatus
1269 _transient NSObject<ProgressDelegate> *delegate_;
1277 void setDelegate(id delegate) {
1278 delegate_ = delegate;
1281 virtual bool MediaChange(std::string media, std::string drive) {
1285 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1288 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1289 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1290 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
1293 virtual void Done(pkgAcquire::ItemDesc &item) {
1296 virtual void Fail(pkgAcquire::ItemDesc &item) {
1298 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1299 item.Owner->Status == pkgAcquire::Item::StatDone
1303 std::string &error(item.Owner->ErrorText);
1307 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1308 NSArray *fields([description componentsSeparatedByString:@" "]);
1309 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1311 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1312 withObject:[NSArray arrayWithObjects:
1313 [NSString stringWithUTF8String:error.c_str()],
1320 virtual bool Pulse(pkgAcquire *Owner) {
1321 bool value = pkgAcquireStatus::Pulse(Owner);
1324 double(CurrentBytes + CurrentItems) /
1325 double(TotalBytes + TotalItems)
1328 [delegate_ setProgressPercent:percent];
1329 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1332 virtual void Start() {
1333 [delegate_ startProgress];
1336 virtual void Stop() {
1340 /* Progress Delegation {{{ */
1345 _transient id<ProgressDelegate> delegate_;
1348 virtual void Update() {
1349 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1350 [delegate_ setProgressPercent:(Percent / 100)];*/
1359 void setDelegate(id delegate) {
1360 delegate_ = delegate;
1363 virtual void Done() {
1364 //[delegate_ setProgressPercent:1];
1369 /* Database Interface {{{ */
1370 typedef std::map< unsigned long, _H<Source> > SourceMap;
1372 @interface Database : NSObject {
1378 pkgCacheFile cache_;
1379 pkgDepCache::Policy *policy_;
1380 pkgRecords *records_;
1381 pkgProblemResolver *resolver_;
1382 pkgAcquire *fetcher_;
1384 SPtr<pkgPackageManager> manager_;
1385 pkgSourceList *list_;
1388 NSMutableArray *packages_;
1390 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1399 + (Database *) sharedInstance;
1402 - (void) _readCydia:(NSNumber *)fd;
1403 - (void) _readStatus:(NSNumber *)fd;
1404 - (void) _readOutput:(NSNumber *)fd;
1408 - (Package *) packageWithName:(NSString *)name;
1410 - (pkgCacheFile &) cache;
1411 - (pkgDepCache::Policy *) policy;
1412 - (pkgRecords *) records;
1413 - (pkgProblemResolver *) resolver;
1414 - (pkgAcquire &) fetcher;
1415 - (pkgSourceList &) list;
1416 - (NSArray *) packages;
1417 - (NSArray *) sources;
1418 - (void) reloadData;
1426 - (NSString *) updateWithStatus:(Status &)status;
1428 - (void) setDelegate:(id)delegate;
1429 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1433 /* Source Class {{{ */
1434 @interface Source : NSObject {
1435 CYString depiction_;
1436 CYString description_;
1442 CYString distribution_;
1448 CYString defaultIcon_;
1450 NSDictionary *record_;
1454 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1456 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1458 - (NSString *) depictionForPackage:(NSString *)package;
1459 - (NSString *) supportForPackage:(NSString *)package;
1461 - (NSDictionary *) record;
1465 - (NSString *) distribution;
1466 - (NSString *) type;
1468 - (NSString *) host;
1470 - (NSString *) name;
1471 - (NSString *) description;
1472 - (NSString *) label;
1473 - (NSString *) origin;
1474 - (NSString *) version;
1476 - (NSString *) defaultIcon;
1480 @implementation Source
1484 distribution_.clear();
1487 description_.clear();
1493 defaultIcon_.clear();
1495 if (record_ != nil) {
1511 + (NSArray *) _attributeKeys {
1512 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1515 - (NSArray *) attributeKeys {
1516 return [[self class] _attributeKeys];
1519 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1520 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1523 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1526 trusted_ = index->IsTrusted();
1528 uri_.set(pool, index->GetURI());
1529 distribution_.set(pool, index->GetDist());
1530 type_.set(pool, index->GetType());
1532 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1533 if (dindex != NULL) {
1535 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1538 pkgTagFile tags(&fd);
1540 pkgTagSection section;
1547 {"default-icon", &defaultIcon_},
1548 {"depiction", &depiction_},
1549 {"description", &description_},
1551 {"origin", &origin_},
1552 {"support", &support_},
1553 {"version", &version_},
1556 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1557 const char *start, *end;
1559 if (section.Find(names[i].name_, start, end)) {
1560 CYString &value(*names[i].value_);
1561 value.set(pool, start, end - start);
1567 record_ = [Sources_ objectForKey:[self key]];
1569 record_ = [record_ retain];
1571 host_ = [[[[NSURL URLWithString:uri_] host] lowercaseString] retain];
1574 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1575 if ((self = [super init]) != nil) {
1576 [self setMetaIndex:index inPool:pool];
1580 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1581 NSDictionary *lhr = [self record];
1582 NSDictionary *rhr = [source record];
1585 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1587 NSString *lhs = [self name];
1588 NSString *rhs = [source name];
1590 if ([lhs length] != 0 && [rhs length] != 0) {
1591 unichar lhc = [lhs characterAtIndex:0];
1592 unichar rhc = [rhs characterAtIndex:0];
1594 if (isalpha(lhc) && !isalpha(rhc))
1595 return NSOrderedAscending;
1596 else if (!isalpha(lhc) && isalpha(rhc))
1597 return NSOrderedDescending;
1600 return [lhs compare:rhs options:LaxCompareOptions_];
1603 - (NSString *) depictionForPackage:(NSString *)package {
1604 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1607 - (NSString *) supportForPackage:(NSString *)package {
1608 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1611 - (NSDictionary *) record {
1619 - (NSString *) uri {
1623 - (NSString *) distribution {
1624 return distribution_;
1627 - (NSString *) type {
1631 - (NSString *) key {
1632 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1635 - (NSString *) host {
1639 - (NSString *) name {
1640 return origin_.empty() ? host_ : origin_;
1643 - (NSString *) description {
1644 return description_;
1647 - (NSString *) label {
1648 return label_.empty() ? host_ : label_;
1651 - (NSString *) origin {
1655 - (NSString *) version {
1659 - (NSString *) defaultIcon {
1660 return defaultIcon_;
1665 /* Relationship Class {{{ */
1666 @interface Relationship : NSObject {
1671 - (NSString *) type;
1673 - (NSString *) name;
1677 @implementation Relationship
1685 - (NSString *) type {
1693 - (NSString *) name {
1700 /* Package Class {{{ */
1701 @interface Package : NSObject {
1705 pkgCache::VerIterator version_;
1706 pkgCache::PkgIterator iterator_;
1707 _transient Database *database_;
1708 pkgCache::VerFileIterator file_;
1715 NSString *section$_;
1720 CYString installed_;
1726 CYString depiction_;
1736 NSMutableArray *tags_;
1739 NSArray *relationships_;
1741 NSMutableDictionary *metadata_;
1742 _transient NSDate *firstSeen_;
1743 _transient NSDate *lastSeen_;
1747 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1748 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1750 - (pkgCache::PkgIterator) iterator;
1753 - (NSString *) section;
1754 - (NSString *) simpleSection;
1756 - (NSString *) longSection;
1757 - (NSString *) shortSection;
1761 - (Address *) maintainer;
1763 - (NSString *) longDescription;
1764 - (NSString *) shortDescription;
1767 - (NSMutableDictionary *) metadata;
1769 - (BOOL) subscribed;
1772 - (NSString *) latest;
1773 - (NSString *) installed;
1774 - (BOOL) uninstalled;
1777 - (BOOL) upgradableAndEssential:(BOOL)essential;
1780 - (BOOL) unfiltered;
1784 - (BOOL) halfConfigured;
1785 - (BOOL) halfInstalled;
1787 - (NSString *) mode;
1790 - (NSString *) name;
1792 - (NSString *) homepage;
1793 - (NSString *) depiction;
1794 - (Address *) author;
1796 - (NSString *) support;
1798 - (NSArray *) files;
1799 - (NSArray *) relationships;
1800 - (NSArray *) warnings;
1801 - (NSArray *) applications;
1803 - (Source *) source;
1804 - (NSString *) role;
1806 - (BOOL) matches:(NSString *)text;
1808 - (bool) hasSupportingRole;
1809 - (BOOL) hasTag:(NSString *)tag;
1810 - (NSString *) primaryPurpose;
1811 - (NSArray *) purposes;
1812 - (bool) isCommercial;
1814 - (CYString &) cyname;
1816 - (uint32_t) compareBySection:(NSArray *)sections;
1818 - (uint32_t) compareForChanges;
1823 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1824 - (bool) isInstalledAndVisible:(NSNumber *)number;
1825 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1826 - (bool) isVisibleInSource:(Source *)source;
1830 uint32_t PackageChangesRadix(Package *self, void *) {
1835 uint32_t timestamp : 30;
1836 uint32_t ignored : 1;
1837 uint32_t upgradable : 1;
1841 bool upgradable([self upgradableAndEssential:YES]);
1842 value.bits.upgradable = upgradable ? 1 : 0;
1845 value.bits.timestamp = 0;
1846 value.bits.ignored = [self ignored] ? 0 : 1;
1847 value.bits.upgradable = 1;
1849 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1850 value.bits.ignored = 0;
1851 value.bits.upgradable = 0;
1854 return _not(uint32_t) - value.key;
1857 _finline static void Stifle(uint8_t &value) {
1860 uint32_t PackagePrefixRadix(Package *self, void *context) {
1861 size_t offset(reinterpret_cast<size_t>(context));
1862 CYString &name([self cyname]);
1864 size_t size(name.size());
1867 char *text(name.data());
1870 if (!isdigit(text[0]))
1874 while (size != digits && isdigit(text[digits]))
1884 if (offset == 0 && zeros != 0) {
1885 memset(data, '0', zeros);
1886 memcpy(data + zeros, text, 4 - zeros);
1888 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1889 if (size <= offset - zeros)
1892 text += offset - zeros;
1893 size -= offset - zeros;
1896 memcpy(data, text, 4);
1898 memcpy(data, text, size);
1899 memset(data + size, 0, 4 - size);
1902 for (size_t i(0); i != 4; ++i)
1903 if (isalpha(data[i]))
1908 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1910 /* XXX: ntohl may be more honest */
1911 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1914 CYString &(*PackageName)(Package *self, SEL sel);
1916 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1917 _profile(PackageNameCompare)
1918 CYString &lhi(PackageName(lhs, @selector(cyname)));
1919 CYString &rhi(PackageName(rhs, @selector(cyname)));
1920 CFStringRef lhn(lhi), rhn(rhi);
1922 _profile(PackageNameCompare$NumbersLast)
1923 if (!lhi.empty() && !rhi.empty()) {
1924 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1925 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1926 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1927 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1928 return lha ? NSOrderedAscending : NSOrderedDescending;
1932 CFIndex length = CFStringGetLength(lhn);
1934 _profile(PackageNameCompare$Compare)
1935 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1940 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1941 return PackageNameCompare(*lhs, *rhs, context);
1944 struct PackageNameOrdering :
1945 std::binary_function<Package *, Package *, bool>
1947 _finline bool operator ()(Package *lhs, Package *rhs) const {
1948 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1952 @implementation Package
1954 - (NSString *) description {
1955 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1961 if (section$_ != nil)
1962 [section$_ release];
1967 if (sponsor$_ != nil)
1968 [sponsor$_ release];
1969 if (author$_ != nil)
1976 if (relationships_ != nil)
1977 [relationships_ release];
1978 if (metadata_ != nil)
1979 [metadata_ release];
1984 + (NSString *) webScriptNameForSelector:(SEL)selector {
1985 if (selector == @selector(hasTag:))
1991 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1992 return [self webScriptNameForSelector:selector] == nil;
1995 + (NSArray *) _attributeKeys {
1996 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];
1999 - (NSArray *) attributeKeys {
2000 return [[self class] _attributeKeys];
2003 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2004 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2014 _profile(Package$parse)
2015 pkgRecords::Parser *parser;
2017 _profile(Package$parse$Lookup)
2018 parser = &[database_ records]->Lookup(file_);
2023 _profile(Package$parse$Find)
2029 {"depiction", &depiction_},
2030 {"homepage", &homepage_},
2031 {"website", &website},
2032 {"support", &support_},
2033 {"sponsor", &sponsor_},
2034 {"author", &author_},
2037 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2038 const char *start, *end;
2040 if (parser->Find(names[i].name_, start, end)) {
2041 CYString &value(*names[i].value_);
2042 _profile(Package$parse$Value)
2043 value.set(pool_, start, end - start);
2049 _profile(Package$parse$Tagline)
2050 const char *start, *end;
2051 if (parser->ShortDesc(start, end)) {
2052 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2055 while (stop != start && stop[-1] == '\r')
2057 tagline_.set(pool_, start, stop - start);
2061 _profile(Package$parse$Retain)
2062 if (!homepage_.empty())
2063 homepage_ = website;
2064 if (homepage_ == depiction_)
2070 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2071 if ((self = [super init]) != nil) {
2072 _profile(Package$initWithVersion)
2073 @synchronized (database) {
2074 era_ = [database era];
2078 iterator_ = version.ParentPkg();
2079 database_ = database;
2081 _profile(Package$initWithVersion$Latest)
2082 latest_ = (NSString *) StripVersion(version_.VerStr());
2085 pkgCache::VerIterator current;
2086 _profile(Package$initWithVersion$Versions)
2087 current = iterator_.CurrentVer();
2089 installed_.set(pool_, StripVersion_(current.VerStr()));
2091 if (!version_.end())
2092 file_ = version_.FileList();
2094 pkgCache &cache([database_ cache]);
2095 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2099 _profile(Package$initWithVersion$Name)
2100 id_.set(pool_, iterator_.Name());
2101 name_.set(pool, iterator_.Display());
2105 _profile(Package$initWithVersion$Source)
2106 source_ = [database_ getSource:file_.File()];
2115 _profile(Package$initWithVersion$Tags)
2116 pkgCache::TagIterator tag(iterator_.TagList());
2118 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2120 const char *name(tag.Name());
2121 [tags_ addObject:(NSString *)CFCString(name)];
2122 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2123 role_ = (NSString *) CFCString(name + 6);
2124 if (visible_ && strncmp(name, "require::", 9) == 0 && (
2129 } while (!tag.end());
2133 bool changed(false);
2134 NSString *key([id_ lowercaseString]);
2136 _profile(Package$initWithVersion$Metadata)
2137 metadata_ = [Packages_ objectForKey:key];
2139 if (metadata_ == nil) {
2142 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2143 firstSeen_, @"FirstSeen",
2144 latest_, @"LastVersion",
2149 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2150 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2152 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2153 subscribed_ = [subscribed boolValue];
2155 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2157 if (firstSeen_ == nil) {
2158 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2159 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2163 if (version == nil) {
2164 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2167 if (![version isEqualToString:latest_]) {
2168 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2170 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2175 metadata_ = [metadata_ retain];
2178 [Packages_ setObject:metadata_ forKey:key];
2183 _profile(Package$initWithVersion$Section)
2184 section_.set(pool_, iterator_.Section());
2187 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2188 visible_ = visible_ && [self hasSupportingRole] && [self unfiltered];
2189 } _end } return self;
2192 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2193 pkgCache::VerIterator version;
2195 _profile(Package$packageWithIterator$GetCandidateVer)
2196 version = [database policy]->GetCandidateVer(iterator);
2202 return [[[Package alloc]
2203 initWithVersion:version
2210 - (pkgCache::PkgIterator) iterator {
2214 - (NSString *) section {
2215 if (section$_ == nil) {
2216 if (section_.empty())
2219 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2220 NSString *name(section_);
2223 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2224 if (NSString *rename = [value objectForKey:@"Rename"]) {
2229 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2233 - (NSString *) simpleSection {
2234 if (NSString *section = [self section])
2235 return Simplify(section);
2240 - (NSString *) longSection {
2241 return LocalizeSection([self section]);
2244 - (NSString *) shortSection {
2245 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2248 - (NSString *) uri {
2251 pkgIndexFile *index;
2252 pkgCache::PkgFileIterator file(file_.File());
2253 if (![database_ list].FindIndex(file, index))
2255 return [NSString stringWithUTF8String:iterator_->Path];
2256 //return [NSString stringWithUTF8String:file.Site()];
2257 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2261 - (Address *) maintainer {
2264 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2265 const std::string &maintainer(parser->Maintainer());
2266 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2270 return version_.end() ? 0 : version_->InstalledSize;
2273 - (NSString *) longDescription {
2276 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2277 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2279 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2280 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2281 if ([lines count] < 2)
2284 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2285 for (size_t i(1), e([lines count]); i != e; ++i) {
2286 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2287 [trimmed addObject:trim];
2290 return [trimmed componentsJoinedByString:@"\n"];
2293 - (NSString *) shortDescription {
2298 _profile(Package$index)
2299 CFStringRef name((CFStringRef) [self name]);
2300 if (CFStringGetLength(name) == 0)
2302 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2303 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2305 return toupper(character);
2309 - (NSMutableDictionary *) metadata {
2314 if (subscribed_ && lastSeen_ != nil)
2319 - (BOOL) subscribed {
2324 NSDictionary *metadata([self metadata]);
2325 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2326 return [ignored boolValue];
2331 - (NSString *) latest {
2335 - (NSString *) installed {
2339 - (BOOL) uninstalled {
2340 return installed_.empty();
2344 return !version_.end();
2347 - (BOOL) upgradableAndEssential:(BOOL)essential {
2348 _profile(Package$upgradableAndEssential)
2349 pkgCache::VerIterator current(iterator_.CurrentVer());
2351 return essential && essential_ && visible_;
2353 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2357 - (BOOL) essential {
2362 return [database_ cache][iterator_].InstBroken();
2365 - (BOOL) unfiltered {
2366 NSString *section([self section]);
2367 return section == nil || isSectionVisible(section);
2375 unsigned char current(iterator_->CurrentState);
2376 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2379 - (BOOL) halfConfigured {
2380 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2383 - (BOOL) halfInstalled {
2384 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2388 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2389 return state.Mode != pkgDepCache::ModeKeep;
2392 - (NSString *) mode {
2393 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2395 switch (state.Mode) {
2396 case pkgDepCache::ModeDelete:
2397 if ((state.iFlags & pkgDepCache::Purge) != 0)
2401 case pkgDepCache::ModeKeep:
2402 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2403 return @"REINSTALL";
2404 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2408 case pkgDepCache::ModeInstall:
2409 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2410 return @"REINSTALL";
2411 else*/ switch (state.Status) {
2413 return @"DOWNGRADE";
2419 return @"NEW_INSTALL";
2432 - (NSString *) name {
2433 return name_.empty() ? id_ : name_;
2436 - (UIImage *) icon {
2437 NSString *section = [self simpleSection];
2441 if ([icon_ hasPrefix:@"file:///"])
2442 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2443 if (icon == nil) if (section != nil)
2444 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2445 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2446 if ([dicon hasPrefix:@"file:///"])
2447 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2449 icon = [UIImage applicationImageNamed:@"unknown.png"];
2453 - (NSString *) homepage {
2457 - (NSString *) depiction {
2458 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2461 - (Address *) sponsor {
2462 if (sponsor$_ == nil) {
2463 if (sponsor_.empty())
2465 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2469 - (Address *) author {
2470 if (author$_ == nil) {
2471 if (author_.empty())
2473 author$_ = [[Address addressWithString:author_] retain];
2477 - (NSString *) support {
2478 return !support_.empty() ? support_ : [[self source] supportForPackage:id_];
2481 - (NSArray *) files {
2482 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2483 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2486 fin.open([path UTF8String]);
2491 while (std::getline(fin, line))
2492 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2497 - (NSArray *) relationships {
2498 return relationships_;
2501 - (NSArray *) warnings {
2502 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2503 const char *name(iterator_.Name());
2505 size_t length(strlen(name));
2506 if (length < 2) invalid:
2507 [warnings addObject:CYLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2508 else for (size_t i(0); i != length; ++i)
2510 /* XXX: technically this is not allowed */
2511 (name[i] < 'A' || name[i] > 'Z') &&
2512 (name[i] < 'a' || name[i] > 'z') &&
2513 (name[i] < '0' || name[i] > '9') &&
2514 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2517 if (strcmp(name, "cydia") != 0) {
2519 bool _private = false;
2522 bool repository = [[self section] isEqualToString:@"Repositories"];
2524 if (NSArray *files = [self files])
2525 for (NSString *file in files)
2526 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2528 else if (!_private && [file isEqualToString:@"/private"])
2530 else if (!stash && [file isEqualToString:@"/var/stash"])
2533 /* XXX: this is not sensitive enough. only some folders are valid. */
2534 if (cydia && !repository)
2535 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2537 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/private"]];
2539 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2542 return [warnings count] == 0 ? nil : warnings;
2545 - (NSArray *) applications {
2546 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2548 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2550 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2551 if (NSArray *files = [self files])
2552 for (NSString *file in files)
2553 if (application_r(file)) {
2554 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2555 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2556 if ([id isEqualToString:me])
2559 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2561 display = application_r[1];
2563 NSString *bundle([file stringByDeletingLastPathComponent]);
2564 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2565 if (icon == nil || [icon length] == 0)
2567 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2569 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2570 [applications addObject:application];
2572 [application addObject:id];
2573 [application addObject:display];
2574 [application addObject:url];
2577 return [applications count] == 0 ? nil : applications;
2580 - (Source *) source {
2582 @synchronized (database_) {
2583 if ([database_ era] != era_ || file_.end())
2586 source_ = [database_ getSource:file_.File()];
2598 - (NSString *) role {
2602 - (BOOL) matches:(NSString *)text {
2608 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2609 if (range.location != NSNotFound)
2612 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2613 if (range.location != NSNotFound)
2616 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2617 if (range.location != NSNotFound)
2623 - (bool) hasSupportingRole {
2626 if ([role_ isEqualToString:@"enduser"])
2628 if ([Role_ isEqualToString:@"User"])
2630 if ([role_ isEqualToString:@"hacker"])
2632 if ([Role_ isEqualToString:@"Hacker"])
2634 if ([role_ isEqualToString:@"developer"])
2636 if ([Role_ isEqualToString:@"Developer"])
2641 - (BOOL) hasTag:(NSString *)tag {
2642 return tags_ == nil ? NO : [tags_ containsObject:tag];
2645 - (NSString *) primaryPurpose {
2646 for (NSString *tag in tags_)
2647 if ([tag hasPrefix:@"purpose::"])
2648 return [tag substringFromIndex:9];
2652 - (NSArray *) purposes {
2653 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2654 for (NSString *tag in tags_)
2655 if ([tag hasPrefix:@"purpose::"])
2656 [purposes addObject:[tag substringFromIndex:9]];
2657 return [purposes count] == 0 ? nil : purposes;
2660 - (bool) isCommercial {
2661 return [self hasTag:@"cydia::commercial"];
2664 - (CYString &) cyname {
2665 return name_.empty() ? id_ : name_;
2668 - (uint32_t) compareBySection:(NSArray *)sections {
2669 NSString *section([self section]);
2670 for (size_t i(0), e([sections count]); i != e; ++i) {
2671 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2675 return _not(uint32_t);
2678 - (uint32_t) compareForChanges {
2683 uint32_t timestamp : 30;
2684 uint32_t ignored : 1;
2685 uint32_t upgradable : 1;
2689 bool upgradable([self upgradableAndEssential:YES]);
2690 value.bits.upgradable = upgradable ? 1 : 0;
2693 value.bits.timestamp = 0;
2694 value.bits.ignored = [self ignored] ? 0 : 1;
2695 value.bits.upgradable = 1;
2697 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2698 value.bits.ignored = 0;
2699 value.bits.upgradable = 0;
2702 return _not(uint32_t) - value.key;
2706 pkgProblemResolver *resolver = [database_ resolver];
2707 resolver->Clear(iterator_);
2708 resolver->Protect(iterator_);
2712 pkgProblemResolver *resolver = [database_ resolver];
2713 resolver->Clear(iterator_);
2714 resolver->Protect(iterator_);
2715 pkgCacheFile &cache([database_ cache]);
2716 cache->MarkInstall(iterator_, false);
2717 pkgDepCache::StateCache &state((*cache)[iterator_]);
2718 if (!state.Install())
2719 cache->SetReInstall(iterator_, true);
2723 pkgProblemResolver *resolver = [database_ resolver];
2724 resolver->Clear(iterator_);
2725 resolver->Protect(iterator_);
2726 resolver->Remove(iterator_);
2727 [database_ cache]->MarkDelete(iterator_, true);
2730 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2731 _profile(Package$isUnfilteredAndSearchedForBy)
2734 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2735 value &= [self unfiltered];
2738 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2739 value &= [self matches:search];
2746 - (bool) isInstalledAndVisible:(NSNumber *)number {
2747 return (![number boolValue] || [self visible]) && ![self uninstalled];
2750 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2751 NSString *section = [self section];
2755 [self uninstalled] && (
2757 section == nil && [name length] == 0 ||
2758 [name isEqualToString:section]
2762 - (bool) isVisibleInSource:(Source *)source {
2763 return [self source] == source && [self visible];
2768 /* Section Class {{{ */
2769 @interface Section : NSObject {
2774 NSString *localized_;
2777 - (NSComparisonResult) compareByLocalized:(Section *)section;
2778 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2779 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2780 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2781 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2782 - (NSString *) name;
2789 - (void) addToCount;
2791 - (void) setCount:(size_t)count;
2792 - (NSString *) localized;
2796 @implementation Section
2800 if (localized_ != nil)
2801 [localized_ release];
2805 - (NSComparisonResult) compareByLocalized:(Section *)section {
2806 NSString *lhs(localized_);
2807 NSString *rhs([section localized]);
2809 /*if ([lhs length] != 0 && [rhs length] != 0) {
2810 unichar lhc = [lhs characterAtIndex:0];
2811 unichar rhc = [rhs characterAtIndex:0];
2813 if (isalpha(lhc) && !isalpha(rhc))
2814 return NSOrderedAscending;
2815 else if (!isalpha(lhc) && isalpha(rhc))
2816 return NSOrderedDescending;
2819 return [lhs compare:rhs options:LaxCompareOptions_];
2822 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2823 if ((self = [self initWithName:name localize:NO]) != nil) {
2824 if (localized != nil)
2825 localized_ = [localized retain];
2829 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2830 return [self initWithName:name row:0 localize:localize];
2833 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2834 if ((self = [super init]) != nil) {
2835 name_ = [name retain];
2839 localized_ = [LocalizeSection(name_) retain];
2843 /* XXX: localize the index thingees */
2844 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2845 if ((self = [super init]) != nil) {
2846 name_ = [(index == '#' ? @"123" : [NSString stringWithCharacters:&index length:1]) retain];
2852 - (NSString *) name {
2872 - (void) addToCount {
2876 - (void) setCount:(size_t)count {
2880 - (NSString *) localized {
2888 static NSArray *Finishes_;
2890 /* Database Implementation {{{ */
2891 @implementation Database
2893 + (Database *) sharedInstance {
2894 static Database *instance;
2895 if (instance == nil)
2896 instance = [[Database alloc] init];
2906 NSRecycleZone(zone_);
2907 // XXX: malloc_destroy_zone(zone_);
2908 apr_pool_destroy(pool_);
2912 - (void) _readCydia:(NSNumber *)fd { _pooled
2913 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2914 std::istream is(&ib);
2917 static Pcre finish_r("^finish:([^:]*)$");
2919 while (std::getline(is, line)) {
2920 const char *data(line.c_str());
2921 size_t size = line.size();
2922 lprintf("C:%s\n", data);
2924 if (finish_r(data, size)) {
2925 NSString *finish = finish_r[1];
2926 int index = [Finishes_ indexOfObject:finish];
2927 if (index != INT_MAX && index > Finish_)
2935 - (void) _readStatus:(NSNumber *)fd { _pooled
2936 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2937 std::istream is(&ib);
2940 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2941 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2943 while (std::getline(is, line)) {
2944 const char *data(line.c_str());
2945 size_t size = line.size();
2946 lprintf("S:%s\n", data);
2948 if (conffile_r(data, size)) {
2949 [delegate_ setConfigurationData:conffile_r[1]];
2950 } else if (strncmp(data, "status: ", 8) == 0) {
2951 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2952 [delegate_ setProgressTitle:string];
2953 } else if (pmstatus_r(data, size)) {
2954 std::string type([pmstatus_r[1] UTF8String]);
2955 NSString *id = pmstatus_r[2];
2957 float percent([pmstatus_r[3] floatValue]);
2958 [delegate_ setProgressPercent:(percent / 100)];
2960 NSString *string = pmstatus_r[4];
2962 if (type == "pmerror")
2963 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2964 withObject:[NSArray arrayWithObjects:string, id, nil]
2967 else if (type == "pmstatus") {
2968 [delegate_ setProgressTitle:string];
2969 } else if (type == "pmconffile")
2970 [delegate_ setConfigurationData:string];
2971 else _assert(false);
2972 } else _assert(false);
2978 - (void) _readOutput:(NSNumber *)fd { _pooled
2979 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2980 std::istream is(&ib);
2983 while (std::getline(is, line)) {
2984 lprintf("O:%s\n", line.c_str());
2985 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2995 - (Package *) packageWithName:(NSString *)name {
2996 if (static_cast<pkgDepCache *>(cache_) == NULL)
2998 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
2999 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3002 - (Database *) init {
3003 if ((self = [super init]) != nil) {
3010 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3011 apr_pool_create(&pool_, NULL);
3013 packages_ = [[NSMutableArray alloc] init];
3017 _assert(pipe(fds) != -1);
3020 _config->Set("APT::Keep-Fds::", cydiafd_);
3021 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3024 detachNewThreadSelector:@selector(_readCydia:)
3026 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3029 _assert(pipe(fds) != -1);
3033 detachNewThreadSelector:@selector(_readStatus:)
3035 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3038 _assert(pipe(fds) != -1);
3039 _assert(dup2(fds[0], 0) != -1);
3040 _assert(close(fds[0]) != -1);
3042 input_ = fdopen(fds[1], "a");
3044 _assert(pipe(fds) != -1);
3045 _assert(dup2(fds[1], 1) != -1);
3046 _assert(close(fds[1]) != -1);
3049 detachNewThreadSelector:@selector(_readOutput:)
3051 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3056 - (pkgCacheFile &) cache {
3060 - (pkgDepCache::Policy *) policy {
3064 - (pkgRecords *) records {
3068 - (pkgProblemResolver *) resolver {
3072 - (pkgAcquire &) fetcher {
3076 - (pkgSourceList &) list {
3080 - (NSArray *) packages {
3084 - (NSArray *) sources {
3085 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3086 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3087 [sources addObject:i->second];
3091 - (NSArray *) issues {
3092 if (cache_->BrokenCount() == 0)
3095 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3097 for (Package *package in packages_) {
3098 if (![package broken])
3100 pkgCache::PkgIterator pkg([package iterator]);
3102 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3103 [entry addObject:[package name]];
3104 [issues addObject:entry];
3106 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3110 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3111 pkgCache::DepIterator start;
3112 pkgCache::DepIterator end;
3113 dep.GlobOr(start, end); // ++dep
3115 if (!cache_->IsImportantDep(end))
3117 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3120 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3121 [entry addObject:failure];
3122 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3124 Package *package([self packageWithName:[NSString stringWithUTF8String:start.TargetPkg().Name()]]);
3125 [failure addObject:[package name]];
3127 pkgCache::PkgIterator target(start.TargetPkg());
3128 if (target->ProvidesList != 0)
3129 [failure addObject:@"?"];
3131 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3133 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3134 else if (!cache_[target].CandidateVerIter(cache_).end())
3135 [failure addObject:@"-"];
3136 else if (target->ProvidesList == 0)
3137 [failure addObject:@"!"];
3139 [failure addObject:@"%"];
3143 if (start.TargetVer() != 0)
3144 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3155 - (void) reloadData { _pooled
3156 @synchronized (self) {
3160 [packages_ removeAllObjects];
3186 apr_pool_clear(pool_);
3187 NSRecycleZone(zone_);
3189 int chk(creat("/tmp/cydia.chk", 0644));
3194 if (!cache_.Open(progress_, true)) {
3196 if (!_error->PopMessage(error))
3199 lprintf("cache_.Open():[%s]\n", error.c_str());
3201 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3202 [delegate_ repairWithSelector:@selector(configure)];
3203 else if (error == "The package lists or status file could not be parsed or opened.")
3204 [delegate_ repairWithSelector:@selector(update)];
3205 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3206 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3207 // else if (error == "The list of sources could not be read.")
3208 else _assert(false);
3214 unlink("/tmp/cydia.chk");
3216 now_ = [[NSDate date] retain];
3218 policy_ = new pkgDepCache::Policy();
3219 records_ = new pkgRecords(cache_);
3220 resolver_ = new pkgProblemResolver(cache_);
3221 fetcher_ = new pkgAcquire(&status_);
3224 list_ = new pkgSourceList();
3225 _assert(list_->ReadMainList());
3227 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3228 _assert(pkgApplyStatus(cache_));
3230 if (cache_->BrokenCount() != 0) {
3231 _assert(pkgFixBroken(cache_));
3232 _assert(cache_->BrokenCount() == 0);
3233 _assert(pkgMinimizeUpgrade(cache_));
3238 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3239 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3240 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3241 // XXX: this could be more intelligent
3242 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3243 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3245 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3252 /*std::vector<Package *> packages;
3253 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3254 [packages_ release];
3259 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3260 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3261 //packages.push_back(package);
3262 [packages_ addObject:package];
3266 /*if (packages.empty())
3267 packages_ = [[NSArray alloc] init];
3269 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3272 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3273 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3274 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3282 /*if (!packages.empty())
3283 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3284 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3286 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3288 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3290 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3296 - (void) configure {
3297 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3298 system([dpkg UTF8String]);
3306 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3307 _assert(!_error->PendingError());
3310 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3313 public pkgArchiveCleaner
3316 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3321 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3323 while (_error->PopMessage(error))
3324 lprintf("ArchiveCleaner: %s\n", error.c_str());
3329 pkgRecords records(cache_);
3331 lock_ = new FileFd();
3332 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3333 _assert(!_error->PendingError());
3336 // XXX: explain this with an error message
3337 _assert(list.ReadMainList());
3339 manager_ = (_system->CreatePM(cache_));
3340 _assert(manager_->GetArchives(fetcher_, &list, &records));
3341 _assert(!_error->PendingError());
3345 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3347 _assert(list.ReadMainList());
3348 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3349 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3352 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3357 bool failed = false;
3358 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3359 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3361 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3364 std::string uri = (*item)->DescURI();
3365 std::string error = (*item)->ErrorText;
3367 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3370 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3371 withObject:[NSArray arrayWithObjects:
3372 [NSString stringWithUTF8String:error.c_str()],
3384 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3386 if (_error->PendingError()) {
3391 if (result == pkgPackageManager::Failed) {
3396 if (result != pkgPackageManager::Completed) {
3401 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3403 _assert(list.ReadMainList());
3404 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3405 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3408 if (![before isEqualToArray:after])
3413 _assert(pkgDistUpgrade(cache_));
3417 [self updateWithStatus:status_];
3420 - (NSString *) updateWithStatus:(Status &)status {
3422 _assert(list.ReadMainList());
3425 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3427 if (_error->PendingError()) {
3429 if (!_error->PopMessage(error))
3432 return [NSString stringWithUTF8String:error.c_str()];
3435 pkgAcquire fetcher(&status);
3436 _assert(list.GetIndexes(&fetcher));
3438 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3439 bool failed = false;
3440 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3441 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3442 (*item)->Finished();
3446 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3447 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3448 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3451 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3458 - (void) setDelegate:(id)delegate {
3459 delegate_ = delegate;
3460 status_.setDelegate(delegate);
3461 progress_.setDelegate(delegate);
3464 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3465 SourceMap::const_iterator i(sources_.find(file->ID));
3466 return i == sources_.end() ? nil : i->second;
3472 /* PopUp Windows {{{ */
3473 @interface PopUpView : UIView {
3474 _transient id delegate_;
3475 UITransitionView *transition_;
3480 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3484 @implementation PopUpView
3487 [transition_ setDelegate:nil];
3488 [transition_ release];
3494 [transition_ transition:UITransitionPushFromTop toView:nil];
3497 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3498 if (from != nil && to == nil)
3499 [self removeFromSuperview];
3502 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3503 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3504 delegate_ = delegate;
3506 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3507 [self addSubview:transition_];
3509 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3511 [view addSubview:self];
3513 [transition_ setDelegate:self];
3515 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3516 [transition_ transition:UITransitionNone toView:blank];
3517 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3525 /* Mail Composition {{{ */
3526 @interface MailToView : PopUpView {
3527 MailComposeController *controller_;
3530 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
3534 @implementation MailToView
3537 [controller_ release];
3541 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
3545 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
3546 NSLog(@"did:%@", delivery);
3547 // [UIApp setStatusBarShowsProgress:NO];
3548 if ([controller error]){
3549 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3550 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3551 [mailAlertSheet setBodyText:[controller error]];
3552 [mailAlertSheet popupAlertAnimated:YES];
3556 - (void) showError {
3557 NSLog(@"%@", [controller_ error]);
3558 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3559 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3560 [mailAlertSheet setBodyText:[controller_ error]];
3561 [mailAlertSheet popupAlertAnimated:YES];
3564 - (void) deliverMessage { _pooled
3568 if (![controller_ deliverMessage])
3569 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
3572 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
3573 if ([controller_ needsDelivery])
3574 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
3579 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
3580 if ((self = [super initWithView:view delegate:delegate]) != nil) {
3581 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
3582 [controller_ setDelegate:self];
3583 [controller_ initializeUI];
3584 [controller_ setupForURL:url];
3586 UIView *view([controller_ view]);
3587 [overlay_ addSubview:view];
3595 /* Confirmation View {{{ */
3596 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3597 if (!iterator.end())
3598 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3599 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3601 pkgCache::PkgIterator package(dep.TargetPkg());
3604 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3611 @protocol ConfirmationViewDelegate
3617 @interface ConfirmationView : BrowserView {
3618 _transient Database *database_;
3619 UIActionSheet *essential_;
3626 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3630 @implementation ConfirmationView
3637 if (essential_ != nil)
3638 [essential_ release];
3644 [book_ popFromSuperviewAnimated:YES];
3647 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3648 NSString *context([sheet context]);
3650 if ([context isEqualToString:@"remove"]) {
3658 [delegate_ confirm];
3665 } else if ([context isEqualToString:@"unable"]) {
3669 [super alertSheet:sheet buttonClicked:button];
3672 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3673 [super webView:sender didClearWindowObject:window forFrame:frame];
3674 [window setValue:changes_ forKey:@"changes"];
3675 [window setValue:issues_ forKey:@"issues"];
3676 [window setValue:sizes_ forKey:@"sizes"];
3679 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3680 if ((self = [super initWithBook:book]) != nil) {
3681 database_ = database;
3683 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3684 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3685 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3686 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3687 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3691 pkgDepCache::Policy *policy([database_ policy]);
3693 pkgCacheFile &cache([database_ cache]);
3694 NSArray *packages = [database_ packages];
3695 for (Package *package in packages) {
3696 pkgCache::PkgIterator iterator = [package iterator];
3697 pkgDepCache::StateCache &state(cache[iterator]);
3699 NSString *name([package name]);
3701 if (state.NewInstall())
3702 [installing addObject:name];
3703 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3704 [reinstalling addObject:name];
3705 else if (state.Upgrade())
3706 [upgrading addObject:name];
3707 else if (state.Downgrade())
3708 [downgrading addObject:name];
3709 else if (state.Delete()) {
3710 if ([package essential])
3712 [removing addObject:name];
3715 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3716 substrate_ |= DepSubstrate(iterator.CurrentVer());
3721 else if (Advanced_ || true) {
3722 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
3724 essential_ = [[UIActionSheet alloc]
3725 initWithTitle:CYLocalize("REMOVING_ESSENTIALS")
3726 buttons:[NSArray arrayWithObjects:
3727 [NSString stringWithFormat:parenthetical, CYLocalize("CANCEL_OPERATION"), CYLocalize("SAFE")],
3728 [NSString stringWithFormat:parenthetical, CYLocalize("FORCE_REMOVAL"), CYLocalize("UNSAFE")],
3730 defaultButtonIndex:0
3736 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3738 [essential_ setBodyText:CYLocalize("REMOVING_ESSENTIALS_EX")];
3740 essential_ = [[UIActionSheet alloc]
3741 initWithTitle:CYLocalize("UNABLE_TO_COMPLY")
3742 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3743 defaultButtonIndex:0
3748 [essential_ setBodyText:CYLocalize("UNABLE_TO_COMPLY_EX")];
3751 changes_ = [[NSArray alloc] initWithObjects:
3759 issues_ = [database_ issues];
3761 issues_ = [issues_ retain];
3763 sizes_ = [[NSArray alloc] initWithObjects:
3764 SizeString([database_ fetcher].FetchNeeded()),
3765 SizeString([database_ fetcher].PartialPresent()),
3766 SizeString([database_ cache]->UsrSize()),
3769 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3773 - (NSString *) backButtonTitle {
3774 return CYLocalize("CONFIRM");
3777 - (NSString *) leftButtonTitle {
3778 return [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("CANCEL"), CYLocalize("QUEUE")];
3781 - (id) rightButtonTitle {
3782 return issues_ != nil ? nil : [super rightButtonTitle];
3785 - (id) _rightButtonTitle {
3786 #if AlwaysReload || IgnoreInstall
3787 return [super _rightButtonTitle];
3789 return CYLocalize("CONFIRM");
3793 - (void) _leftButtonClicked {
3798 - (void) _rightButtonClicked {
3800 return [super _rightButtonClicked];
3802 if (essential_ != nil)
3803 [essential_ popupAlertAnimated:YES];
3807 [delegate_ confirm];
3815 /* Progress Data {{{ */
3816 @interface ProgressData : NSObject {
3822 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3829 @implementation ProgressData
3831 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3832 if ((self = [super init]) != nil) {
3833 selector_ = selector;
3853 /* Progress View {{{ */
3854 @interface ProgressView : UIView <
3855 ConfigurationDelegate,
3858 _transient Database *database_;
3860 UIView *background_;
3861 UITransitionView *transition_;
3863 UINavigationBar *navbar_;
3864 UIProgressBar *progress_;
3865 UITextView *output_;
3866 UITextLabel *status_;
3867 UIPushButton *close_;
3870 SHA1SumValue springlist_;
3871 SHA1SumValue notifyconf_;
3872 SHA1SumValue sandplate_;
3875 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
3877 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
3878 - (void) setContentView:(UIView *)view;
3881 - (void) _retachThread;
3882 - (void) _detachNewThreadData:(ProgressData *)data;
3883 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
3889 @protocol ProgressViewDelegate
3890 - (void) progressViewIsComplete:(ProgressView *)sender;
3893 @implementation ProgressView
3896 [transition_ setDelegate:nil];
3897 [navbar_ setDelegate:nil];
3900 if (background_ != nil)
3901 [background_ release];
3902 [transition_ release];
3905 [progress_ release];
3912 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3913 if (bootstrap_ && from == overlay_ && to == view_)
3917 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
3918 if ((self = [super initWithFrame:frame]) != nil) {
3919 database_ = database;
3920 delegate_ = delegate;
3922 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3923 [transition_ setDelegate:self];
3925 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3928 [overlay_ setBackgroundColor:[UIColor blackColor]];
3930 background_ = [[UIView alloc] initWithFrame:[self bounds]];
3931 [background_ setBackgroundColor:[UIColor blackColor]];
3932 [self addSubview:background_];
3935 [self addSubview:transition_];
3937 CGSize navsize = [UINavigationBar defaultSize];
3938 CGRect navrect = {{0, 0}, navsize};
3940 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
3941 [overlay_ addSubview:navbar_];
3943 [navbar_ setBarStyle:1];
3944 [navbar_ setDelegate:self];
3946 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
3947 [navbar_ pushNavigationItem:navitem];
3949 CGRect bounds = [overlay_ bounds];
3950 CGSize prgsize = [UIProgressBar defaultSize];
3953 (bounds.size.width - prgsize.width) / 2,
3954 bounds.size.height - prgsize.height - 20
3957 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3958 [progress_ setStyle:0];
3960 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3962 bounds.size.height - prgsize.height - 50,
3963 bounds.size.width - 20,
3967 [status_ setColor:[UIColor whiteColor]];
3968 [status_ setBackgroundColor:[UIColor clearColor]];
3970 [status_ setCentersHorizontally:YES];
3971 //[status_ setFont:font];
3974 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3976 navrect.size.height + 20,
3977 bounds.size.width - 20,
3978 bounds.size.height - navsize.height - 62 - navrect.size.height
3982 //[output_ setTextFont:@"Courier New"];
3983 [output_ setTextSize:12];
3985 [output_ setTextColor:[UIColor whiteColor]];
3986 [output_ setBackgroundColor:[UIColor clearColor]];
3988 [output_ setMarginTop:0];
3989 [output_ setAllowsRubberBanding:YES];
3990 [output_ setEditable:NO];
3992 [overlay_ addSubview:output_];
3994 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3996 bounds.size.height - prgsize.height - 50,
3997 bounds.size.width - 20,
4001 [close_ setAutosizesToFit:NO];
4002 [close_ setDrawsShadow:YES];
4003 [close_ setStretchBackground:YES];
4004 [close_ setEnabled:YES];
4006 UIFont *bold = [UIFont boldSystemFontOfSize:22];
4007 [close_ setTitleFont:bold];
4009 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
4010 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4011 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4015 - (void) setContentView:(UIView *)view {
4016 view_ = [view retain];
4019 - (void) resetView {
4020 [transition_ transition:6 toView:view_];
4023 - (void) _checkError {
4024 if (_error->PendingError()) {
4026 if (!_error->PopMessage(error))
4029 UIActionSheet *sheet = [[[UIActionSheet alloc]
4030 initWithTitle:CYLocalize("ERROR")
4031 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
4032 defaultButtonIndex:0
4037 [sheet setBodyText:[NSString stringWithUTF8String:error.c_str()]];
4038 [sheet popupAlertAnimated:YES];
4043 [delegate_ progressViewIsComplete:self];
4047 if (!file.Open(SandboxTemplate_, FileFd::ReadOnly))
4050 MMap mmap(file, MMap::ReadOnly);
4052 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4053 if (!(sandplate_ == sha1.Result()))
4060 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4063 MMap mmap(file, MMap::ReadOnly);
4065 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4066 if (!(notifyconf_ == sha1.Result()))
4073 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4076 MMap mmap(file, MMap::ReadOnly);
4078 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4079 if (!(springlist_ == sha1.Result()))
4085 case 0: [close_ setTitle:CYLocalize("RETURN_TO_CYDIA")]; break;
4086 case 1: [close_ setTitle:CYLocalize("CLOSE_CYDIA")]; break;
4087 case 2: [close_ setTitle:CYLocalize("RESTART_SPRINGBOARD")]; break;
4088 case 3: [close_ setTitle:CYLocalize("RELOAD_SPRINGBOARD")]; break;
4089 case 4: [close_ setTitle:CYLocalize("REBOOT_DEVICE")]; break;
4092 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4094 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
4095 [cache autorelease];
4097 NSFileManager *manager = [NSFileManager defaultManager];
4098 NSError *error = nil;
4100 id system = [cache objectForKey:@"System"];
4105 if (stat(Cache_, &info) == -1)
4108 [system removeAllObjects];
4110 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4111 for (NSString *app in apps)
4112 if ([app hasSuffix:@".app"]) {
4113 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4114 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4115 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4117 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4118 [info setObject:path forKey:@"Path"];
4119 [info setObject:@"System" forKey:@"ApplicationType"];
4120 [system addInfoDictionary:info];
4126 [cache writeToFile:@Cache_ atomically:YES];
4128 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
4130 if (chmod(Cache_, info.st_mode) == -1)
4134 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4137 notify_post("com.apple.mobile.application_installed");
4139 [delegate_ setStatusBarShowsProgress:NO];
4142 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4143 NSString *context([sheet context]);
4145 if ([context isEqualToString:@"error"])
4147 else if ([context isEqualToString:@"_error"]) {
4150 } else if ([context isEqualToString:@"conffile"]) {
4151 FILE *input = [database_ input];
4155 fprintf(input, "N\n");
4159 fprintf(input, "Y\n");
4170 - (void) closeButtonPushed {
4179 [delegate_ suspendWithAnimation:YES];
4183 system("launchctl stop com.apple.SpringBoard");
4187 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4196 - (void) _retachThread {
4197 UINavigationItem *item = [navbar_ topItem];
4198 [item setTitle:CYLocalize("COMPLETE")];
4200 [overlay_ addSubview:close_];
4201 [progress_ removeFromSuperview];
4202 [status_ removeFromSuperview];
4207 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4208 [[data target] performSelector:[data selector] withObject:[data object]];
4211 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4214 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4215 UINavigationItem *item = [navbar_ topItem];
4216 [item setTitle:title];
4218 [status_ setText:nil];
4219 [output_ setText:@""];
4220 [progress_ setProgress:0];
4222 [close_ removeFromSuperview];
4223 [overlay_ addSubview:progress_];
4224 [overlay_ addSubview:status_];
4226 [delegate_ setStatusBarShowsProgress:YES];
4231 if (!file.Open(SandboxTemplate_, FileFd::ReadOnly))
4234 MMap mmap(file, MMap::ReadOnly);
4236 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4237 sandplate_ = sha1.Result();
4243 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4246 MMap mmap(file, MMap::ReadOnly);
4248 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4249 notifyconf_ = sha1.Result();
4255 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4258 MMap mmap(file, MMap::ReadOnly);
4260 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4261 springlist_ = sha1.Result();
4265 [transition_ transition:6 toView:overlay_];
4268 detachNewThreadSelector:@selector(_detachNewThreadData:)
4270 withObject:[[ProgressData alloc]
4271 initWithSelector:selector
4278 - (void) repairWithSelector:(SEL)selector {
4280 detachNewThreadSelector:selector
4283 title:CYLocalize("REPAIRING")
4287 - (void) setConfigurationData:(NSString *)data {
4289 performSelectorOnMainThread:@selector(_setConfigurationData:)
4295 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4296 Package *package = id == nil ? nil : [database_ packageWithName:id];
4298 UIActionSheet *sheet = [[[UIActionSheet alloc]
4299 initWithTitle:(package == nil ? id : [package name])
4300 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
4301 defaultButtonIndex:0
4306 [sheet setBodyText:error];
4307 [sheet popupAlertAnimated:YES];
4310 - (void) setProgressTitle:(NSString *)title {
4312 performSelectorOnMainThread:@selector(_setProgressTitle:)
4318 - (void) setProgressPercent:(float)percent {
4320 performSelectorOnMainThread:@selector(_setProgressPercent:)
4321 withObject:[NSNumber numberWithFloat:percent]
4326 - (void) startProgress {
4329 - (void) addProgressOutput:(NSString *)output {
4331 performSelectorOnMainThread:@selector(_addProgressOutput:)
4337 - (bool) isCancelling:(size_t)received {
4341 - (void) _setConfigurationData:(NSString *)data {
4342 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4344 _assert(conffile_r(data));
4346 NSString *ofile = conffile_r[1];
4347 //NSString *nfile = conffile_r[2];
4349 UIActionSheet *sheet = [[[UIActionSheet alloc]
4350 initWithTitle:CYLocalize("CONFIGURATION_UPGRADE")
4351 buttons:[NSArray arrayWithObjects:
4352 CYLocalize("KEEP_OLD_COPY"),
4353 CYLocalize("ACCEPT_NEW_COPY"),
4354 // XXX: CYLocalize("SEE_WHAT_CHANGED"),
4356 defaultButtonIndex:0
4361 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", CYLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4362 [sheet popupAlertAnimated:YES];
4365 - (void) _setProgressTitle:(NSString *)title {
4366 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4367 for (size_t i(0), e([words count]); i != e; ++i) {
4368 NSString *word([words objectAtIndex:i]);
4369 if (Package *package = [database_ packageWithName:word])
4370 [words replaceObjectAtIndex:i withObject:[package name]];
4373 [status_ setText:[words componentsJoinedByString:@" "]];
4376 - (void) _setProgressPercent:(NSNumber *)percent {
4377 [progress_ setProgress:[percent floatValue]];
4380 - (void) _addProgressOutput:(NSString *)output {
4381 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4382 CGSize size = [output_ contentSize];
4383 CGRect rect = {{0, size.height}, {size.width, 0}};
4384 [output_ scrollRectToVisible:rect animated:YES];
4387 - (BOOL) isRunning {
4394 /* Package Cell {{{ */
4395 @interface PackageCell : UITableCell {
4398 NSString *description_;
4405 UITextLabel *status_;
4409 - (PackageCell *) init;
4410 - (void) setPackage:(Package *)package;
4412 + (int) heightForPackage:(Package *)package;
4416 @implementation PackageCell
4418 - (void) clearPackage {
4429 if (description_ != nil) {
4430 [description_ release];
4434 if (source_ != nil) {
4439 if (badge_ != nil) {
4449 [self clearPackage];
4456 - (PackageCell *) init {
4457 if ((self = [super init]) != nil) {
4459 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4460 [status_ setBackgroundColor:[UIColor clearColor]];
4461 [status_ setFont:small];
4466 - (void) setPackage:(Package *)package {
4467 [self clearPackage];
4470 Source *source = [package source];
4472 icon_ = [[package icon] retain];
4473 name_ = [[package name] retain];
4474 description_ = [[package shortDescription] retain];
4475 commercial_ = [package isCommercial];
4477 package_ = [package retain];
4479 NSString *label = nil;
4480 bool trusted = false;
4482 if (source != nil) {
4483 label = [source label];
4484 trusted = [source trusted];
4485 } else if ([[package id] isEqualToString:@"firmware"])
4486 label = CYLocalize("APPLE");
4488 label = [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("UNKNOWN"), CYLocalize("LOCAL")];
4490 NSString *from(label);
4492 NSString *section = [package simpleSection];
4493 if (section != nil && ![section isEqualToString:label]) {
4494 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4495 from = [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), from, section];
4498 from = [NSString stringWithFormat:CYLocalize("FROM"), from];
4499 source_ = [from retain];
4501 if (NSString *purpose = [package primaryPurpose])
4502 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4503 badge_ = [badge_ retain];
4506 if (NSString *mode = [package mode]) {
4507 [badge_ setImage:[UIImage applicationImageNamed:
4508 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4511 [status_ setText:[NSString stringWithFormat:CYLocalize("QUEUED_FOR"), CYLocalize(mode)]];
4512 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4513 } else if ([package half]) {
4514 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4515 [status_ setText:CYLocalize("PACKAGE_DAMAGED")];
4516 [status_ setColor:[UIColor redColor]];
4518 [badge_ setImage:nil];
4519 [status_ setText:nil];
4526 - (void) drawRect:(CGRect)rect {
4530 if (NSString *mode = [package_ mode]) {
4531 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4532 color = remove ? RemovingColor_ : InstallingColor_;
4534 color = [UIColor whiteColor];
4536 [self setBackgroundColor:color];
4540 [super drawRect:rect];
4543 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4545 CGContextRef context(UIGraphicsGetCurrentContext());
4546 [[self backgroundColor] set];
4548 back.size.height -= 1;
4549 CGContextFillRect(context, back);
4552 [super drawBackgroundInRect:rect withFade:fade];
4555 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4558 rect.size = [icon_ size];
4560 rect.size.width /= 2;
4561 rect.size.height /= 2;
4563 rect.origin.x = 25 - rect.size.width / 2;
4564 rect.origin.y = 25 - rect.size.height / 2;
4566 [icon_ drawInRect:rect];
4569 if (badge_ != nil) {
4570 CGSize size = [badge_ size];
4572 [badge_ drawAtPoint:CGPointMake(
4573 36 - size.width / 2,
4574 36 - size.height / 2
4582 UISetColor(commercial_ ? Purple_ : Black_);
4583 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4584 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4587 UISetColor(commercial_ ? Purplish_ : Gray_);
4588 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4590 [super drawContentInRect:rect selected:selected];
4593 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4595 [super setSelected:selected withFade:fade];
4598 + (int) heightForPackage:(Package *)package {
4604 /* Section Cell {{{ */
4605 @interface SectionCell : UISimpleTableCell {
4610 _UISwitchSlider *switch_;
4615 - (void) setSection:(Section *)section editing:(BOOL)editing;
4619 @implementation SectionCell
4621 - (void) clearSection {
4622 if (section_ != nil) {
4632 if (count_ != nil) {
4639 [self clearSection];
4646 if ((self = [super init]) != nil) {
4647 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4649 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4650 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4654 - (void) onSwitch:(id)sender {
4655 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4656 if (metadata == nil) {
4657 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4658 [Sections_ setObject:metadata forKey:section_];
4662 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4665 - (void) setSection:(Section *)section editing:(BOOL)editing {
4666 if (editing != editing_) {
4668 [switch_ removeFromSuperview];
4670 [self addSubview:switch_];
4674 [self clearSection];
4676 if (section == nil) {
4677 name_ = [CYLocalize("ALL_PACKAGES") retain];
4680 section_ = [section localized];
4681 if (section_ != nil)
4682 section_ = [section_ retain];
4683 name_ = [(section_ == nil || [section_ length] == 0 ? CYLocalize("NO_SECTION") : section_) retain];
4684 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4687 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4691 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4692 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4699 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4701 CGSize size = [count_ sizeWithFont:Font14_];
4705 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4707 [super drawContentInRect:rect selected:selected];
4713 /* File Table {{{ */
4714 @interface FileTable : RVPage {
4715 _transient Database *database_;
4718 NSMutableArray *files_;
4722 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4723 - (void) setPackage:(Package *)package;
4727 @implementation FileTable
4730 if (package_ != nil)
4739 - (int) numberOfRowsInTable:(UITable *)table {
4740 return files_ == nil ? 0 : [files_ count];
4743 - (float) table:(UITable *)table heightForRow:(int)row {
4747 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4748 if (reusing == nil) {
4749 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4750 UIFont *font = [UIFont systemFontOfSize:16];
4751 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4753 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4757 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4761 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4762 if ((self = [super initWithBook:book]) != nil) {
4763 database_ = database;
4765 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4767 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4768 [self addSubview:list_];
4770 UITableColumn *column = [[[UITableColumn alloc]
4771 initWithTitle:CYLocalize("NAME")
4773 width:[self frame].size.width
4776 [list_ setDataSource:self];
4777 [list_ setSeparatorStyle:1];
4778 [list_ addTableColumn:column];
4779 [list_ setDelegate:self];
4780 [list_ setReusesTableCells:YES];
4784 - (void) setPackage:(Package *)package {
4785 if (package_ != nil) {
4786 [package_ autorelease];
4795 [files_ removeAllObjects];
4797 if (package != nil) {
4798 package_ = [package retain];
4799 name_ = [[package id] retain];
4801 if (NSArray *files = [package files])
4802 [files_ addObjectsFromArray:files];
4804 if ([files_ count] != 0) {
4805 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4806 [files_ removeObjectAtIndex:0];
4807 [files_ sortUsingSelector:@selector(compareByPath:)];
4809 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4810 [stack addObject:@"/"];
4812 for (int i(0), e([files_ count]); i != e; ++i) {
4813 NSString *file = [files_ objectAtIndex:i];
4814 while (![file hasPrefix:[stack lastObject]])
4815 [stack removeLastObject];
4816 NSString *directory = [stack lastObject];
4817 [stack addObject:[file stringByAppendingString:@"/"]];
4818 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4819 ([stack count] - 2) * 3, "",
4820 [file substringFromIndex:[directory length]]
4829 - (void) resetViewAnimated:(BOOL)animated {
4830 [list_ resetViewAnimated:animated];
4833 - (void) reloadData {
4834 [self setPackage:[database_ packageWithName:name_]];
4835 [self reloadButtons];
4838 - (NSString *) title {
4839 return CYLocalize("INSTALLED_FILES");
4842 - (NSString *) backButtonTitle {
4843 return CYLocalize("FILES");
4848 /* Package View {{{ */
4849 @interface PackageView : BrowserView {
4850 _transient Database *database_;
4854 NSMutableArray *buttons_;
4857 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4858 - (void) setPackage:(Package *)package;
4862 @implementation PackageView
4865 if (package_ != nil)
4874 if ([self retainCount] == 1)
4875 [delegate_ setPackageView:self];
4879 /* XXX: this is not safe at all... localization of /fail/ */
4880 - (void) _clickButtonWithName:(NSString *)name {
4881 if ([name isEqualToString:CYLocalize("CLEAR")])
4882 [delegate_ clearPackage:package_];
4883 else if ([name isEqualToString:CYLocalize("INSTALL")])
4884 [delegate_ installPackage:package_];
4885 else if ([name isEqualToString:CYLocalize("REINSTALL")])
4886 [delegate_ installPackage:package_];
4887 else if ([name isEqualToString:CYLocalize("REMOVE")])
4888 [delegate_ removePackage:package_];
4889 else if ([name isEqualToString:CYLocalize("UPGRADE")])
4890 [delegate_ installPackage:package_];
4891 else _assert(false);
4894 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4895 NSString *context([sheet context]);
4897 if ([context isEqualToString:@"modify"]) {
4898 int count = [buttons_ count];
4899 _assert(count != 0);
4900 _assert(button <= count + 1);
4902 if (count != button - 1)
4903 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
4907 [super alertSheet:sheet buttonClicked:button];
4910 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
4911 return [super webView:sender didFinishLoadForFrame:frame];
4914 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4915 [super webView:sender didClearWindowObject:window forFrame:frame];
4916 [window setValue:package_ forKey:@"package"];
4919 - (bool) _allowJavaScriptPanel {
4924 - (void) __rightButtonClicked {
4925 int count = [buttons_ count];
4926 _assert(count != 0);
4929 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
4931 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
4932 [buttons addObjectsFromArray:buttons_];
4933 [buttons addObject:CYLocalize("CANCEL")];
4935 [delegate_ slideUp:[[[UIActionSheet alloc]
4938 defaultButtonIndex:([buttons count] - 1)
4945 - (void) _rightButtonClicked {
4947 [super _rightButtonClicked];
4949 [self __rightButtonClicked];
4953 - (id) _rightButtonTitle {
4954 int count = [buttons_ count];
4955 return count == 0 ? nil : count != 1 ? CYLocalize("MODIFY") : [buttons_ objectAtIndex:0];
4958 - (NSString *) backButtonTitle {
4962 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4963 if ((self = [super initWithBook:book]) != nil) {
4964 database_ = database;
4965 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
4966 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
4970 - (void) setPackage:(Package *)package {
4971 if (package_ != nil) {
4972 [package_ autorelease];
4981 [buttons_ removeAllObjects];
4983 if (package != nil) {
4986 package_ = [package retain];
4987 name_ = [[package id] retain];
4988 commercial_ = [package isCommercial];
4990 if ([package_ mode] != nil)
4991 [buttons_ addObject:CYLocalize("CLEAR")];
4992 if ([package_ source] == nil);
4993 else if ([package_ upgradableAndEssential:NO])
4994 [buttons_ addObject:CYLocalize("UPGRADE")];
4995 else if ([package_ uninstalled])
4996 [buttons_ addObject:CYLocalize("INSTALL")];
4998 [buttons_ addObject:CYLocalize("REINSTALL")];
4999 if (![package_ uninstalled])
5000 [buttons_ addObject:CYLocalize("REMOVE")];
5002 if (special_ != NULL) {
5003 CGRect frame([webview_ frame]);
5004 frame.size.width = 320;
5005 frame.size.height = 0;
5006 [webview_ setFrame:frame];
5008 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
5011 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
5013 [self setButtonTitle:nil withStyle:nil toFunction:nil];
5015 [self setFinishHook:nil];
5016 [self setPopupHook:nil];
5019 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
5020 [super callFunction:special_];
5024 [self reloadButtons];
5027 - (bool) isLoading {
5028 return commercial_ ? [super isLoading] : false;
5031 - (void) reloadData {
5032 [self setPackage:[database_ packageWithName:name_]];
5037 /* Package Table {{{ */
5038 @interface PackageTable : RVPage {
5039 _transient Database *database_;
5041 NSMutableArray *packages_;
5042 NSMutableArray *sections_;
5043 UISectionList *list_;
5046 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5048 - (void) setDelegate:(id)delegate;
5050 - (void) reloadData;
5051 - (void) resetCursor;
5053 - (UISectionList *) list;
5055 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5059 @implementation PackageTable
5062 [list_ setDataSource:nil];
5065 [packages_ release];
5066 [sections_ release];
5071 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5072 return [sections_ count];
5075 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5076 return [[sections_ objectAtIndex:section] name];
5079 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5080 return [[sections_ objectAtIndex:section] row];
5083 - (int) numberOfRowsInTable:(UITable *)table {
5084 return [packages_ count];
5087 - (float) table:(UITable *)table heightForRow:(int)row {
5088 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
5091 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
5093 reusing = [[[PackageCell alloc] init] autorelease];
5094 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
5098 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5102 - (void) tableRowSelected:(NSNotification *)notification {
5103 int row = [[notification object] selectedRow];
5107 Package *package = [packages_ objectAtIndex:row];
5108 package = [database_ packageWithName:[package id]];
5109 PackageView *view([delegate_ packageView]);
5110 [view setPackage:package];
5111 [view setDelegate:delegate_];
5112 [book_ pushPage:view];
5115 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5116 if ((self = [super initWithBook:book]) != nil) {
5117 database_ = database;
5118 title_ = [title retain];
5120 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5121 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5123 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
5124 [list_ setDataSource:self];
5126 UITableColumn *column = [[[UITableColumn alloc]
5127 initWithTitle:CYLocalize("NAME")
5129 width:[self frame].size.width
5132 UITable *table = [list_ table];
5133 [table setSeparatorStyle:1];
5134 [table addTableColumn:column];
5135 [table setDelegate:self];
5136 [table setReusesTableCells:YES];
5138 [self addSubview:list_];
5140 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5141 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5145 - (void) setDelegate:(id)delegate {
5146 delegate_ = delegate;
5149 - (bool) hasPackage:(Package *)package {
5153 - (void) reloadData {
5154 NSArray *packages = [database_ packages];
5156 [packages_ removeAllObjects];
5157 [sections_ removeAllObjects];
5159 _profile(PackageTable$reloadData$Filter)
5160 for (Package *package in packages)
5161 if ([self hasPackage:package])
5162 [packages_ addObject:package];
5165 Section *section = nil;
5167 _profile(PackageTable$reloadData$Section)
5168 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5172 _profile(PackageTable$reloadData$Section$Package)
5173 package = [packages_ objectAtIndex:offset];
5174 index = [package index];
5177 if (section == nil || [section index] != index) {
5178 _profile(PackageTable$reloadData$Section$Allocate)
5179 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5182 _profile(PackageTable$reloadData$Section$Add)
5183 [sections_ addObject:section];
5187 [section addToCount];
5191 _profile(PackageTable$reloadData$List)
5196 - (NSString *) title {
5200 - (void) resetViewAnimated:(BOOL)animated {
5201 [list_ resetViewAnimated:animated];
5204 - (void) resetCursor {
5205 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
5208 - (UISectionList *) list {
5212 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5213 [list_ setShouldHideHeaderInShortLists:hide];
5218 /* Filtered Package Table {{{ */
5219 @interface FilteredPackageTable : PackageTable {
5225 - (void) setObject:(id)object;
5227 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5231 @implementation FilteredPackageTable
5239 - (void) setObject:(id)object {
5245 object_ = [object retain];
5248 - (bool) hasPackage:(Package *)package {
5249 _profile(FilteredPackageTable$hasPackage)
5250 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5254 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5255 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5257 object_ = object == nil ? nil : [object retain];
5259 /* XXX: this is an unsafe optimization of doomy hell */
5260 Method method = class_getInstanceMethod([Package class], filter);
5261 _assert(method != NULL);
5262 imp_ = method_getImplementation(method);
5263 _assert(imp_ != NULL);
5272 /* Add Source View {{{ */
5273 @interface AddSourceView : RVPage {
5274 _transient Database *database_;
5277 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5281 @implementation AddSourceView
5283 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5284 if ((self = [super initWithBook:book]) != nil) {
5285 database_ = database;
5291 /* Source Cell {{{ */
5292 @interface SourceCell : UITableCell {
5295 NSString *description_;
5301 - (SourceCell *) initWithSource:(Source *)source;
5305 @implementation SourceCell
5310 [description_ release];
5315 - (SourceCell *) initWithSource:(Source *)source {
5316 if ((self = [super init]) != nil) {
5318 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5320 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5321 icon_ = [icon_ retain];
5323 origin_ = [[source name] retain];
5324 label_ = [[source uri] retain];
5325 description_ = [[source description] retain];
5329 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5331 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5338 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5342 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5346 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5348 [super drawContentInRect:rect selected:selected];
5353 /* Source Table {{{ */
5354 @interface SourceTable : RVPage {
5355 _transient Database *database_;
5356 UISectionList *list_;
5357 NSMutableArray *sources_;
5358 UIActionSheet *alert_;
5362 UIProgressHUD *hud_;
5365 //NSURLConnection *installer_;
5366 NSURLConnection *trivial_bz2_;
5367 NSURLConnection *trivial_gz_;
5368 //NSURLConnection *automatic_;
5373 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5377 @implementation SourceTable
5379 - (void) _deallocConnection:(NSURLConnection *)connection {
5380 if (connection != nil) {
5381 [connection cancel];
5382 //[connection setDelegate:nil];
5383 [connection release];
5388 [[list_ table] setDelegate:nil];
5389 [list_ setDataSource:nil];
5398 //[self _deallocConnection:installer_];
5399 [self _deallocConnection:trivial_gz_];
5400 [self _deallocConnection:trivial_bz2_];
5401 //[self _deallocConnection:automatic_];
5408 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5409 return offset_ == 0 ? 1 : 2;
5412 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5413 switch (section + (offset_ == 0 ? 1 : 0)) {
5414 case 0: return CYLocalize("ENTERED_BY_USER");
5415 case 1: return CYLocalize("INSTALLED_BY_PACKAGE");
5423 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5424 switch (section + (offset_ == 0 ? 1 : 0)) {
5426 case 1: return offset_;
5434 - (int) numberOfRowsInTable:(UITable *)table {
5435 return [sources_ count];
5438 - (float) table:(UITable *)table heightForRow:(int)row {
5439 Source *source = [sources_ objectAtIndex:row];
5440 return [source description] == nil ? 56 : 73;
5443 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5444 Source *source = [sources_ objectAtIndex:row];
5445 // XXX: weird warning, stupid selectors ;P
5446 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5449 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5453 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5457 - (void) tableRowSelected:(NSNotification*)notification {
5458 UITable *table([list_ table]);
5459 int row([table selectedRow]);
5463 Source *source = [sources_ objectAtIndex:row];
5465 PackageTable *packages = [[[FilteredPackageTable alloc]
5468 title:[source label]
5469 filter:@selector(isVisibleInSource:)
5473 [packages setDelegate:delegate_];
5475 [book_ pushPage:packages];
5478 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5479 Source *source = [sources_ objectAtIndex:row];
5480 return [source record] != nil;
5483 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5484 [[list_ table] setDeleteConfirmationRow:row];
5487 - (void) table:(UITable *)table deleteRow:(int)row {
5488 Source *source = [sources_ objectAtIndex:row];
5489 [Sources_ removeObjectForKey:[source key]];
5490 [delegate_ syncData];
5494 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5497 @"./", @"Distribution",
5498 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5500 [delegate_ syncData];
5503 - (NSString *) getWarning {
5504 NSString *href(href_);
5505 NSRange colon([href rangeOfString:@"://"]);
5506 if (colon.location != NSNotFound)
5507 href = [href substringFromIndex:(colon.location + 3)];
5508 href = [href stringByAddingPercentEscapes];
5509 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5510 href = [href stringByCachingURLWithCurrentCDN];
5512 NSURL *url([NSURL URLWithString:href]);
5514 NSStringEncoding encoding;
5515 NSError *error(nil);
5517 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5518 return [warning length] == 0 ? nil : warning;
5522 - (void) _endConnection:(NSURLConnection *)connection {
5523 NSURLConnection **field = NULL;
5524 if (connection == trivial_bz2_)
5525 field = &trivial_bz2_;
5526 else if (connection == trivial_gz_)
5527 field = &trivial_gz_;
5528 _assert(field != NULL);
5529 [connection release];
5533 trivial_bz2_ == nil &&
5539 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5542 UIActionSheet *sheet = [[[UIActionSheet alloc]
5543 initWithTitle:CYLocalize("SOURCE_WARNING")
5544 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_ANYWAY"), CYLocalize("CANCEL"), nil]
5545 defaultButtonIndex:0
5550 [sheet setNumberOfRows:1];
5552 [sheet setBodyText:warning];
5553 [sheet popupAlertAnimated:YES];
5556 } else if (error_ != nil) {
5557 UIActionSheet *sheet = [[[UIActionSheet alloc]
5558 initWithTitle:CYLocalize("VERIFICATION_ERROR")
5559 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5560 defaultButtonIndex:0
5565 [sheet setBodyText:[error_ localizedDescription]];
5566 [sheet popupAlertAnimated:YES];
5568 UIActionSheet *sheet = [[[UIActionSheet alloc]
5569 initWithTitle:CYLocalize("NOT_REPOSITORY")
5570 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5571 defaultButtonIndex:0
5576 [sheet setBodyText:CYLocalize("NOT_REPOSITORY_EX")];
5577 [sheet popupAlertAnimated:YES];
5580 [delegate_ setStatusBarShowsProgress:NO];
5581 [delegate_ removeProgressHUD:hud_];
5591 if (error_ != nil) {
5598 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5599 switch ([response statusCode]) {
5605 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5606 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5608 error_ = [error retain];
5609 [self _endConnection:connection];
5612 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5613 [self _endConnection:connection];
5616 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5617 NSMutableURLRequest *request = [NSMutableURLRequest
5618 requestWithURL:[NSURL URLWithString:href]
5619 cachePolicy:NSURLRequestUseProtocolCachePolicy
5620 timeoutInterval:20.0
5623 [request setHTTPMethod:method];
5625 if (Machine_ != NULL)
5626 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5627 if (UniqueID_ != nil)
5628 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5631 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5633 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5636 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5637 NSString *context([sheet context]);
5639 if ([context isEqualToString:@"source"]) {
5642 NSString *href = [[sheet textField] text];
5644 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5646 if (![href hasSuffix:@"/"])
5647 href_ = [href stringByAppendingString:@"/"];
5650 href_ = [href_ retain];
5652 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5653 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5654 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5658 hud_ = [[delegate_ addProgressHUD] retain];
5659 [hud_ setText:CYLocalize("VERIFYING_URL")];
5670 } else if ([context isEqualToString:@"trivial"])
5672 else if ([context isEqualToString:@"urlerror"])
5674 else if ([context isEqualToString:@"warning"]) {
5694 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5695 if ((self = [super initWithBook:book]) != nil) {
5696 database_ = database;
5697 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5699 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5700 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5701 [list_ setShouldHideHeaderInShortLists:NO];
5703 [self addSubview:list_];
5704 [list_ setDataSource:self];
5706 UITableColumn *column = [[UITableColumn alloc]
5707 initWithTitle:CYLocalize("NAME")
5709 width:[self frame].size.width
5712 UITable *table = [list_ table];
5713 [table setSeparatorStyle:1];
5714 [table addTableColumn:column];
5715 [table setDelegate:self];
5719 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5720 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5724 - (void) reloadData {
5726 _assert(list.ReadMainList());
5728 [sources_ removeAllObjects];
5729 [sources_ addObjectsFromArray:[database_ sources]];
5731 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5734 int count = [sources_ count];
5735 for (offset_ = 0; offset_ != count; ++offset_) {
5736 Source *source = [sources_ objectAtIndex:offset_];
5737 if ([source record] == nil)
5744 - (void) resetViewAnimated:(BOOL)animated {
5745 [list_ resetViewAnimated:animated];
5748 - (void) _leftButtonClicked {
5749 /*[book_ pushPage:[[[AddSourceView alloc]
5754 UIActionSheet *sheet = [[[UIActionSheet alloc]
5755 initWithTitle:CYLocalize("ENTER_APT_URL")
5756 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_SOURCE"), CYLocalize("CANCEL"), nil]
5757 defaultButtonIndex:0
5762 [sheet setNumberOfRows:1];
5764 [sheet addTextFieldWithValue:@"http://" label:@""];
5766 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5767 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5768 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5769 [traits setKeyboardType:UIKeyboardTypeURL];
5770 // XXX: UIReturnKeyDone
5771 [traits setReturnKeyType:UIReturnKeyNext];
5773 [sheet popupAlertAnimated:YES];
5776 - (void) _rightButtonClicked {
5777 UITable *table = [list_ table];
5778 BOOL editing = [table isRowDeletionEnabled];
5779 [table enableRowDeletion:!editing animated:YES];
5780 [book_ reloadButtonsForPage:self];
5783 - (NSString *) title {
5784 return CYLocalize("SOURCES");
5787 - (NSString *) leftButtonTitle {
5788 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("ADD") : nil;
5791 - (id) rightButtonTitle {
5792 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("DONE") : CYLocalize("EDIT");
5795 - (UINavigationButtonStyle) rightButtonStyle {
5796 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5802 /* Installed View {{{ */
5803 @interface InstalledView : RVPage {
5804 _transient Database *database_;
5805 FilteredPackageTable *packages_;
5809 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5813 @implementation InstalledView
5816 [packages_ release];
5820 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5821 if ((self = [super initWithBook:book]) != nil) {
5822 database_ = database;
5824 packages_ = [[FilteredPackageTable alloc]
5828 filter:@selector(isInstalledAndVisible:)
5829 with:[NSNumber numberWithBool:YES]
5832 [self addSubview:packages_];
5834 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5835 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5839 - (void) resetViewAnimated:(BOOL)animated {
5840 [packages_ resetViewAnimated:animated];
5843 - (void) reloadData {
5844 [packages_ reloadData];
5847 - (void) _rightButtonClicked {
5848 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5849 [packages_ reloadData];
5851 [book_ reloadButtonsForPage:self];
5854 - (NSString *) title {
5855 return CYLocalize("INSTALLED");
5858 - (NSString *) backButtonTitle {
5859 return CYLocalize("PACKAGES");
5862 - (id) rightButtonTitle {
5863 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? CYLocalize("EXPERT") : CYLocalize("SIMPLE");
5866 - (UINavigationButtonStyle) rightButtonStyle {
5867 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5870 - (void) setDelegate:(id)delegate {
5871 [super setDelegate:delegate];
5872 [packages_ setDelegate:delegate];
5879 @interface HomeView : BrowserView {
5884 @implementation HomeView
5886 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5887 NSString *context([sheet context]);
5889 if ([context isEqualToString:@"about"])
5892 [super alertSheet:sheet buttonClicked:button];
5895 - (void) _leftButtonClicked {
5896 UIActionSheet *sheet = [[[UIActionSheet alloc]
5897 initWithTitle:CYLocalize("ABOUT_CYDIA")
5898 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
5899 defaultButtonIndex:0
5905 @"Copyright (C) 2008-2009\n"
5906 "Jay Freeman (saurik)\n"
5907 "saurik@saurik.com\n"
5908 "http://www.saurik.com/\n"
5911 "http://www.theokorigroup.com/\n"
5913 "College of Creative Studies,\n"
5914 "University of California,\n"
5916 "http://www.ccs.ucsb.edu/"
5919 [sheet popupAlertAnimated:YES];
5922 - (NSString *) leftButtonTitle {
5923 return CYLocalize("ABOUT");
5928 /* Manage View {{{ */
5929 @interface ManageView : BrowserView {
5934 @implementation ManageView
5936 - (NSString *) title {
5937 return CYLocalize("MANAGE");
5940 - (void) _leftButtonClicked {
5941 [delegate_ askForSettings];
5944 - (NSString *) leftButtonTitle {
5945 return CYLocalize("SETTINGS");
5949 - (id) _rightButtonTitle {
5950 return Queuing_ ? CYLocalize("QUEUE") : nil;
5953 - (UINavigationButtonStyle) rightButtonStyle {
5954 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5957 - (void) _rightButtonClicked {
5962 - (bool) isLoading {
5969 #include <BrowserView.m>
5971 /* Cydia Book {{{ */
5972 @interface CYBook : RVBook <
5975 _transient Database *database_;
5976 UINavigationBar *overlay_;
5977 UINavigationBar *underlay_;
5978 UIProgressIndicator *indicator_;
5979 UITextLabel *prompt_;
5980 UIProgressBar *progress_;
5981 UINavigationButton *cancel_;
5985 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
5991 @implementation CYBook
5995 [indicator_ release];
5997 [progress_ release];
6002 - (NSString *) getTitleForPage:(RVPage *)page {
6003 return [super getTitleForPage:page];
6011 [UIView beginAnimations:nil context:NULL];
6013 CGRect ovrframe = [overlay_ frame];
6014 ovrframe.origin.y = 0;
6015 [overlay_ setFrame:ovrframe];
6017 CGRect barframe = [navbar_ frame];
6018 barframe.origin.y += ovrframe.size.height;
6019 [navbar_ setFrame:barframe];
6021 CGRect trnframe = [transition_ frame];
6022 trnframe.origin.y += ovrframe.size.height;
6023 trnframe.size.height -= ovrframe.size.height;
6024 [transition_ setFrame:trnframe];
6026 [UIView endAnimations];
6028 [indicator_ startAnimation];
6029 [prompt_ setText:CYLocalize("UPDATING_DATABASE")];
6030 [progress_ setProgress:0];
6033 [overlay_ addSubview:cancel_];
6036 detachNewThreadSelector:@selector(_update)
6042 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6043 NSString *context([sheet context]);
6045 if ([context isEqualToString:@"refresh"])
6049 - (void) _update_:(NSString *)error {
6052 [indicator_ stopAnimation];
6054 [UIView beginAnimations:nil context:NULL];
6056 CGRect ovrframe = [overlay_ frame];
6057 ovrframe.origin.y = -ovrframe.size.height;
6058 [overlay_ setFrame:ovrframe];
6060 CGRect barframe = [navbar_ frame];
6061 barframe.origin.y -= ovrframe.size.height;
6062 [navbar_ setFrame:barframe];
6064 CGRect trnframe = [transition_ frame];
6065 trnframe.origin.y -= ovrframe.size.height;
6066 trnframe.size.height += ovrframe.size.height;
6067 [transition_ setFrame:trnframe];
6069 [UIView commitAnimations];
6072 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6074 UIActionSheet *sheet = [[[UIActionSheet alloc]
6075 initWithTitle:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), CYLocalize("REFRESH")]
6076 buttons:[NSArray arrayWithObjects:
6079 defaultButtonIndex:0
6084 [sheet setBodyText:error];
6085 [sheet popupAlertAnimated:YES];
6087 [self reloadButtons];
6091 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6092 if ((self = [super initWithFrame:frame]) != nil) {
6093 database_ = database;
6095 CGRect ovrrect = [navbar_ bounds];
6096 ovrrect.size.height = [UINavigationBar defaultSize].height;
6097 ovrrect.origin.y = -ovrrect.size.height;
6099 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6100 [self addSubview:overlay_];
6102 ovrrect.origin.y = frame.size.height;
6103 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6104 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6105 [self addSubview:underlay_];
6107 [overlay_ setBarStyle:1];
6108 [underlay_ setBarStyle:1];
6110 int barstyle = [overlay_ _barStyle:NO];
6111 bool ugly = barstyle == 0;
6113 UIProgressIndicatorStyle style = ugly ?
6114 UIProgressIndicatorStyleMediumBrown :
6115 UIProgressIndicatorStyleMediumWhite;
6117 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
6118 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6119 CGRect indrect = {{indoffset, indoffset}, indsize};
6121 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6122 [indicator_ setStyle:style];
6123 [overlay_ addSubview:indicator_];
6125 CGSize prmsize = {215, indsize.height + 4};
6128 indoffset * 2 + indsize.width,
6132 unsigned(ovrrect.size.height - prmsize.height) / 2
6135 UIFont *font = [UIFont systemFontOfSize:15];
6137 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6139 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6140 [prompt_ setBackgroundColor:[UIColor clearColor]];
6141 [prompt_ setFont:font];
6143 [overlay_ addSubview:prompt_];
6145 CGSize prgsize = {75, 100};
6148 ovrrect.size.width - prgsize.width - 10,
6149 (ovrrect.size.height - prgsize.height) / 2
6152 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6153 [progress_ setStyle:0];
6154 [overlay_ addSubview:progress_];
6156 cancel_ = [[UINavigationButton alloc] initWithTitle:CYLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6157 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6159 CGRect frame = [cancel_ frame];
6160 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6161 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6162 [cancel_ setFrame:frame];
6164 [cancel_ setBarStyle:barstyle];
6168 - (void) _onCancel {
6170 [cancel_ removeFromSuperview];
6173 - (void) _update { _pooled
6175 status.setDelegate(self);
6177 NSString *error([database_ updateWithStatus:status]);
6180 performSelectorOnMainThread:@selector(_update_:)
6186 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
6187 [prompt_ setText:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), error]];
6190 - (void) setProgressTitle:(NSString *)title {
6192 performSelectorOnMainThread:@selector(_setProgressTitle:)
6198 - (void) setProgressPercent:(float)percent {
6200 performSelectorOnMainThread:@selector(_setProgressPercent:)
6201 withObject:[NSNumber numberWithFloat:percent]
6206 - (void) startProgress {
6209 - (void) addProgressOutput:(NSString *)output {
6211 performSelectorOnMainThread:@selector(_addProgressOutput:)
6217 - (bool) isCancelling:(size_t)received {
6221 - (void) _setProgressTitle:(NSString *)title {
6222 [prompt_ setText:title];
6225 - (void) _setProgressPercent:(NSNumber *)percent {
6226 [progress_ setProgress:[percent floatValue]];
6229 - (void) _addProgressOutput:(NSString *)output {
6234 /* Cydia:// Protocol {{{ */
6235 @interface CydiaURLProtocol : NSURLProtocol {
6240 @implementation CydiaURLProtocol
6242 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6243 NSURL *url([request URL]);
6246 NSString *scheme([[url scheme] lowercaseString]);
6247 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6252 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6256 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6257 id<NSURLProtocolClient> client([self client]);
6259 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6261 NSData *data(UIImagePNGRepresentation(icon));
6263 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6264 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6265 [client URLProtocol:self didLoadData:data];
6266 [client URLProtocolDidFinishLoading:self];
6270 - (void) startLoading {
6271 id<NSURLProtocolClient> client([self client]);
6272 NSURLRequest *request([self request]);
6274 NSURL *url([request URL]);
6275 NSString *href([url absoluteString]);
6277 NSString *path([href substringFromIndex:8]);
6278 NSRange slash([path rangeOfString:@"/"]);
6281 if (slash.location == NSNotFound) {
6285 command = [path substringToIndex:slash.location];
6286 path = [path substringFromIndex:(slash.location + 1)];
6289 Database *database([Database sharedInstance]);
6291 if ([command isEqualToString:@"package-icon"]) {
6294 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6295 Package *package([database packageWithName:path]);
6298 UIImage *icon([package icon]);
6299 [self _returnPNGWithImage:icon forRequest:request];
6300 } else if ([command isEqualToString:@"source-icon"]) {
6303 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6304 NSString *source(Simplify(path));
6305 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6307 icon = [UIImage applicationImageNamed:@"unknown.png"];
6308 [self _returnPNGWithImage:icon forRequest:request];
6309 } else if ([command isEqualToString:@"uikit-image"]) {
6312 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6313 UIImage *icon(_UIImageWithName(path));
6314 [self _returnPNGWithImage:icon forRequest:request];
6315 } else if ([command isEqualToString:@"section-icon"]) {
6318 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6319 NSString *section(Simplify(path));
6320 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6322 icon = [UIImage applicationImageNamed:@"unknown.png"];
6323 [self _returnPNGWithImage:icon forRequest:request];
6325 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6329 - (void) stopLoading {
6335 /* Sections View {{{ */
6336 @interface SectionsView : RVPage {
6337 _transient Database *database_;
6338 NSMutableArray *sections_;
6339 NSMutableArray *filtered_;
6340 UITransitionView *transition_;
6346 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6347 - (void) reloadData;
6352 @implementation SectionsView
6355 [list_ setDataSource:nil];
6356 [list_ setDelegate:nil];
6358 [sections_ release];
6359 [filtered_ release];
6360 [transition_ release];
6362 [accessory_ release];
6366 - (int) numberOfRowsInTable:(UITable *)table {
6367 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6370 - (float) table:(UITable *)table heightForRow:(int)row {
6374 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6376 reusing = [[[SectionCell alloc] init] autorelease];
6377 [(SectionCell *)reusing setSection:(editing_ ?
6378 [sections_ objectAtIndex:row] :
6379 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6380 ) editing:editing_];
6384 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6388 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6392 - (void) tableRowSelected:(NSNotification *)notification {
6393 int row = [[notification object] selectedRow];
6404 title = CYLocalize("ALL_PACKAGES");
6406 section = [filtered_ objectAtIndex:(row - 1)];
6407 name = [section name];
6410 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6413 title = CYLocalize("NO_SECTION");
6417 PackageTable *table = [[[FilteredPackageTable alloc]
6421 filter:@selector(isVisiblyUninstalledInSection:)
6425 [table setDelegate:delegate_];
6427 [book_ pushPage:table];
6430 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6431 if ((self = [super initWithBook:book]) != nil) {
6432 database_ = database;
6434 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6435 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6437 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6438 [self addSubview:transition_];
6440 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6441 [transition_ transition:0 toView:list_];
6443 UITableColumn *column = [[[UITableColumn alloc]
6444 initWithTitle:CYLocalize("NAME")
6446 width:[self frame].size.width
6449 [list_ setDataSource:self];
6450 [list_ setSeparatorStyle:1];
6451 [list_ addTableColumn:column];
6452 [list_ setDelegate:self];
6453 [list_ setReusesTableCells:YES];
6457 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6458 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6462 - (void) reloadData {
6463 NSArray *packages = [database_ packages];
6465 [sections_ removeAllObjects];
6466 [filtered_ removeAllObjects];
6469 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6470 SectionMap sections;
6471 sections.resize(64);
6473 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6477 for (Package *package in packages) {
6478 NSString *name([package section]);
6479 NSString *key(name == nil ? @"" : name);
6484 _profile(SectionsView$reloadData$Section)
6485 section = §ions[key];
6486 if (*section == nil) {
6487 _profile(SectionsView$reloadData$Section$Allocate)
6488 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6493 [*section addToCount];
6495 _profile(SectionsView$reloadData$Filter)
6496 if (![package valid] || ![package uninstalled] || ![package visible])
6500 [*section addToRow];
6504 _profile(SectionsView$reloadData$Section)
6505 section = [sections objectForKey:key];
6506 if (section == nil) {
6507 _profile(SectionsView$reloadData$Section$Allocate)
6508 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6509 [sections setObject:section forKey:key];
6514 [section addToCount];
6516 _profile(SectionsView$reloadData$Filter)
6517 if (![package valid] || ![package uninstalled] || ![package visible])
6527 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6528 [sections_ addObject:i->second];
6530 [sections_ addObjectsFromArray:[sections allValues]];
6533 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6535 for (Section *section in sections_) {
6536 size_t count([section row]);
6540 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6541 [section setCount:count];
6542 [filtered_ addObject:section];
6549 - (void) resetView {
6551 [self _rightButtonClicked];
6554 - (void) resetViewAnimated:(BOOL)animated {
6555 [list_ resetViewAnimated:animated];
6558 - (void) _rightButtonClicked {
6559 if ((editing_ = !editing_))
6562 [delegate_ updateData];
6563 [book_ reloadTitleForPage:self];
6564 [book_ reloadButtonsForPage:self];
6567 - (NSString *) title {
6568 return editing_ ? CYLocalize("SECTION_VISIBILITY") : CYLocalize("INSTALL_BY_SECTION");
6571 - (NSString *) backButtonTitle {
6572 return CYLocalize("SECTIONS");
6575 - (id) rightButtonTitle {
6576 return [sections_ count] == 0 ? nil : editing_ ? CYLocalize("DONE") : CYLocalize("EDIT");
6579 - (UINavigationButtonStyle) rightButtonStyle {
6580 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6583 - (UIView *) accessoryView {
6589 /* Changes View {{{ */
6590 @interface ChangesView : RVPage {
6591 _transient Database *database_;
6592 NSMutableArray *packages_;
6593 NSMutableArray *sections_;
6594 UISectionList *list_;
6598 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6599 - (void) reloadData;
6603 @implementation ChangesView
6606 [[list_ table] setDelegate:nil];
6607 [list_ setDataSource:nil];
6609 [packages_ release];
6610 [sections_ release];
6615 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6616 return [sections_ count];
6619 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6620 return [[sections_ objectAtIndex:section] name];
6623 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6624 return [[sections_ objectAtIndex:section] row];
6627 - (int) numberOfRowsInTable:(UITable *)table {
6628 return [packages_ count];
6631 - (float) table:(UITable *)table heightForRow:(int)row {
6632 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6635 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6637 reusing = [[[PackageCell alloc] init] autorelease];
6638 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6642 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6646 - (void) tableRowSelected:(NSNotification *)notification {
6647 int row = [[notification object] selectedRow];
6650 Package *package = [packages_ objectAtIndex:row];
6651 PackageView *view([delegate_ packageView]);
6652 [view setDelegate:delegate_];
6653 [view setPackage:package];
6654 [book_ pushPage:view];
6657 - (void) _leftButtonClicked {
6658 [(CYBook *)book_ update];
6659 [self reloadButtons];
6662 - (void) _rightButtonClicked {
6663 [delegate_ distUpgrade];
6666 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6667 if ((self = [super initWithBook:book]) != nil) {
6668 database_ = database;
6670 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6671 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6673 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6674 [self addSubview:list_];
6676 [list_ setShouldHideHeaderInShortLists:NO];
6677 [list_ setDataSource:self];
6678 //[list_ setSectionListStyle:1];
6680 UITableColumn *column = [[[UITableColumn alloc]
6681 initWithTitle:CYLocalize("NAME")
6683 width:[self frame].size.width
6686 UITable *table = [list_ table];
6687 [table setSeparatorStyle:1];
6688 [table addTableColumn:column];
6689 [table setDelegate:self];
6690 [table setReusesTableCells:YES];
6694 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6695 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6699 - (void) reloadData {
6700 NSArray *packages = [database_ packages];
6702 [packages_ removeAllObjects];
6703 [sections_ removeAllObjects];
6706 for (Package *package in packages)
6708 [package uninstalled] && [package valid] && [package visible] ||
6709 [package upgradableAndEssential:YES]
6711 [packages_ addObject:package];
6714 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6717 Section *upgradable = [[[Section alloc] initWithName:CYLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6718 Section *ignored = [[[Section alloc] initWithName:CYLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6719 Section *section = nil;
6723 bool unseens = false;
6725 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6727 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6728 Package *package = [packages_ objectAtIndex:offset];
6730 BOOL uae = [package upgradableAndEssential:YES];
6736 _profile(ChangesView$reloadData$Remember)
6737 seen = [package seen];
6740 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6745 name = CYLocalize("UNKNOWN");
6747 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6751 _profile(ChangesView$reloadData$Allocate)
6752 name = [NSString stringWithFormat:CYLocalize("NEW_AT"), name];
6753 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6754 [sections_ addObject:section];
6758 [section addToCount];
6759 } else if ([package ignored])
6760 [ignored addToCount];
6763 [upgradable addToCount];
6768 CFRelease(formatter);
6771 Section *last = [sections_ lastObject];
6772 size_t count = [last count];
6773 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6774 [sections_ removeLastObject];
6777 if ([ignored count] != 0)
6778 [sections_ insertObject:ignored atIndex:0];
6780 [sections_ insertObject:upgradable atIndex:0];
6783 [self reloadButtons];
6786 - (void) resetViewAnimated:(BOOL)animated {
6787 [list_ resetViewAnimated:animated];
6790 - (NSString *) leftButtonTitle {
6791 return [(CYBook *)book_ updating] ? nil : CYLocalize("REFRESH");
6794 - (id) rightButtonTitle {
6795 return upgrades_ == 0 ? nil : [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6798 - (NSString *) title {
6799 return CYLocalize("CHANGES");
6804 /* Search View {{{ */
6805 @protocol SearchViewDelegate
6806 - (void) showKeyboard:(BOOL)show;
6809 @interface SearchView : RVPage {
6811 UISearchField *field_;
6812 UITransitionView *transition_;
6813 FilteredPackageTable *table_;
6814 UIPreferencesTable *advanced_;
6820 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6821 - (void) reloadData;
6825 @implementation SearchView
6828 [field_ setDelegate:nil];
6830 [accessory_ release];
6832 [transition_ release];
6834 [advanced_ release];
6839 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6843 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6845 case 0: return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("ADVANCED_SEARCH"), CYLocalize("COMING_SOON")];
6847 default: _assert(false);
6851 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6855 default: _assert(false);
6859 - (void) _showKeyboard:(BOOL)show {
6860 CGSize keysize = [UIKeyboard defaultSize];
6861 CGRect keydown = [book_ pageBounds];
6862 CGRect keyup = keydown;
6863 keyup.size.height -= keysize.height - ButtonBarHeight_;
6865 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6867 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6868 [animation setSignificantRectFields:8];
6871 [animation setStartFrame:keydown];
6872 [animation setEndFrame:keyup];
6874 [animation setStartFrame:keyup];
6875 [animation setEndFrame:keydown];
6878 UIAnimator *animator = [UIAnimator sharedAnimator];
6881 addAnimations:[NSArray arrayWithObjects:animation, nil]
6882 withDuration:(KeyboardTime_ - delay)
6887 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6889 [delegate_ showKeyboard:show];
6892 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6893 [self _showKeyboard:YES];
6896 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
6897 [self _showKeyboard:NO];
6900 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
6902 NSString *text([field_ text]);
6903 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6909 - (void) textFieldClearButtonPressed:(UITextField *)field {
6913 - (void) keyboardInputShouldDelete:(id)input {
6917 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
6918 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6922 [field_ resignFirstResponder];
6927 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6928 if ((self = [super initWithBook:book]) != nil) {
6929 CGRect pageBounds = [book_ pageBounds];
6931 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6932 [self addSubview:transition_];
6934 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6936 [advanced_ setReusesTableCells:YES];
6937 [advanced_ setDataSource:self];
6938 [advanced_ reloadData];
6940 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6941 CGColor dimmed(space_, 0, 0, 0, 0.5);
6942 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
6944 table_ = [[FilteredPackageTable alloc]
6948 filter:@selector(isUnfilteredAndSearchedForBy:)
6952 [table_ setShouldHideHeaderInShortLists:NO];
6953 [transition_ transition:0 toView:table_];
6962 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
6969 [self bounds].size.width - area.origin.x - 18;
6971 area.size.height = [UISearchField defaultHeight];
6973 field_ = [[UISearchField alloc] initWithFrame:area];
6975 UIFont *font = [UIFont systemFontOfSize:16];
6976 [field_ setFont:font];
6978 [field_ setPlaceholder:CYLocalize("SEARCH_EX")];
6979 [field_ setDelegate:self];
6981 [field_ setPaddingTop:5];
6983 UITextInputTraits *traits([field_ textInputTraits]);
6984 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6985 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6986 [traits setReturnKeyType:UIReturnKeySearch];
6988 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
6990 accessory_ = [[UIView alloc] initWithFrame:accrect];
6991 [accessory_ addSubview:field_];
6993 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
6994 [configure setShowPressFeedback:YES];
6995 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
6996 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
6997 [accessory_ addSubview:configure];*/
6999 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7000 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
7006 LKAnimation *animation = [LKTransition animation];
7007 [animation setType:@"oglFlip"];
7008 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
7009 [animation setFillMode:@"extended"];
7010 [animation setTransitionFlags:3];
7011 [animation setDuration:10];
7012 [animation setSpeed:0.35];
7013 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
7014 [[transition_ _layer] addAnimation:animation forKey:0];
7015 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
7016 flipped_ = !flipped_;
7020 - (void) configurePushed {
7021 [field_ resignFirstResponder];
7025 - (void) resetViewAnimated:(BOOL)animated {
7028 [table_ resetViewAnimated:animated];
7031 - (void) _reloadData {
7034 - (void) reloadData {
7037 [table_ setObject:[field_ text]];
7038 _profile(SearchView$reloadData)
7039 [table_ reloadData];
7042 [table_ resetCursor];
7045 - (UIView *) accessoryView {
7049 - (NSString *) title {
7053 - (NSString *) backButtonTitle {
7054 return CYLocalize("SEARCH");
7057 - (void) setDelegate:(id)delegate {
7058 [table_ setDelegate:delegate];
7059 [super setDelegate:delegate];
7065 @interface SettingsView : RVPage {
7066 _transient Database *database_;
7069 UIPreferencesTable *table_;
7070 _UISwitchSlider *subscribedSwitch_;
7071 _UISwitchSlider *ignoredSwitch_;
7072 UIPreferencesControlTableCell *subscribedCell_;
7073 UIPreferencesControlTableCell *ignoredCell_;
7076 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7080 @implementation SettingsView
7083 [table_ setDataSource:nil];
7086 if (package_ != nil)
7089 [subscribedSwitch_ release];
7090 [ignoredSwitch_ release];
7091 [subscribedCell_ release];
7092 [ignoredCell_ release];
7096 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7097 if (package_ == nil)
7103 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7104 if (package_ == nil)
7111 default: _assert(false);
7117 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7118 if (package_ == nil)
7125 default: _assert(false);
7131 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7132 if (package_ == nil)
7139 default: _assert(false);
7145 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7146 if (package_ == nil)
7149 _UISwitchSlider *slider([cell control]);
7150 BOOL value([slider value] != 0);
7151 NSMutableDictionary *metadata([package_ metadata]);
7154 if (NSNumber *number = [metadata objectForKey:key])
7155 before = [number boolValue];
7159 if (value != before) {
7160 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7162 [delegate_ updateData];
7166 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7167 [self onSomething:cell withKey:@"IsSubscribed"];
7170 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7171 [self onSomething:cell withKey:@"IsIgnored"];
7174 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7175 if (package_ == nil)
7179 case 0: switch (row) {
7181 return subscribedCell_;
7183 return ignoredCell_;
7184 default: _assert(false);
7187 case 1: switch (row) {
7189 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7190 [cell setShowSelection:NO];
7191 [cell setTitle:CYLocalize("SHOW_ALL_CHANGES_EX")];
7195 default: _assert(false);
7198 default: _assert(false);
7204 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7205 if ((self = [super initWithBook:book])) {
7206 database_ = database;
7207 name_ = [package retain];
7209 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7210 [self addSubview:table_];
7212 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7213 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
7215 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7216 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
7218 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7219 [subscribedCell_ setShowSelection:NO];
7220 [subscribedCell_ setTitle:CYLocalize("SHOW_ALL_CHANGES")];
7221 [subscribedCell_ setControl:subscribedSwitch_];
7223 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7224 [ignoredCell_ setShowSelection:NO];
7225 [ignoredCell_ setTitle:CYLocalize("IGNORE_UPGRADES")];
7226 [ignoredCell_ setControl:ignoredSwitch_];
7228 [table_ setDataSource:self];
7233 - (void) resetViewAnimated:(BOOL)animated {
7234 [table_ resetViewAnimated:animated];
7237 - (void) reloadData {
7238 if (package_ != nil)
7239 [package_ autorelease];
7240 package_ = [database_ packageWithName:name_];
7241 if (package_ != nil) {
7243 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7244 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7247 [table_ reloadData];
7250 - (NSString *) title {
7251 return CYLocalize("SETTINGS");
7256 /* Signature View {{{ */
7257 @interface SignatureView : BrowserView {
7258 _transient Database *database_;
7262 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7266 @implementation SignatureView
7273 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7275 [super webView:sender didClearWindowObject:window forFrame:frame];
7278 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7279 if ((self = [super initWithBook:book]) != nil) {
7280 database_ = database;
7281 package_ = [package retain];
7286 - (void) resetViewAnimated:(BOOL)animated {
7289 - (void) reloadData {
7290 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7296 @interface Cydia : UIApplication <
7297 ConfirmationViewDelegate,
7298 ProgressViewDelegate,
7307 UIToolbar *buttonbar_;
7311 NSMutableArray *essential_;
7312 NSMutableArray *broken_;
7314 Database *database_;
7315 ProgressView *progress_;
7319 UIKeyboard *keyboard_;
7320 UIProgressHUD *hud_;
7322 SectionsView *sections_;
7323 ChangesView *changes_;
7324 ManageView *manage_;
7325 SearchView *search_;
7327 NSMutableArray *details_;
7332 @implementation Cydia
7335 if ([broken_ count] != 0) {
7336 int count = [broken_ count];
7338 UIActionSheet *sheet = [[[UIActionSheet alloc]
7339 initWithTitle:(count == 1 ? CYLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:CYLocalize("HALFINSTALLED_PACKAGES"), count])
7340 buttons:[NSArray arrayWithObjects:
7341 CYLocalize("FORCIBLY_CLEAR"),
7342 CYLocalize("TEMPORARY_IGNORE"),
7344 defaultButtonIndex:0
7349 [sheet setBodyText:CYLocalize("HALFINSTALLED_PACKAGE_EX")];
7350 [sheet popupAlertAnimated:YES];
7351 } else if (!Ignored_ && [essential_ count] != 0) {
7352 int count = [essential_ count];
7354 UIActionSheet *sheet = [[[UIActionSheet alloc]
7355 initWithTitle:(count == 1 ? CYLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:CYLocalize("ESSENTIAL_UPGRADES"), count])
7356 buttons:[NSArray arrayWithObjects:
7357 CYLocalize("UPGRADE_ESSENTIAL"),
7358 CYLocalize("COMPLETE_UPGRADE"),
7359 CYLocalize("TEMPORARY_IGNORE"),
7361 defaultButtonIndex:0
7366 [sheet setBodyText:CYLocalize("ESSENTIAL_UPGRADE_EX")];
7367 [sheet popupAlertAnimated:YES];
7371 - (void) _reloadData {
7374 static bool loaded(false);
7375 UIProgressHUD *hud([self addProgressHUD]);
7376 [hud setText:(loaded ? CYLocalize("RELOADING_DATA") : CYLocalize("LOADING_DATA"))];
7379 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7382 [self removeProgressHUD:hud];
7386 [essential_ removeAllObjects];
7387 [broken_ removeAllObjects];
7389 NSArray *packages = [database_ packages];
7390 for (Package *package in packages) {
7392 [broken_ addObject:package];
7393 if ([package upgradableAndEssential:NO]) {
7394 if ([package essential])
7395 [essential_ addObject:package];
7401 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7402 [buttonbar_ setBadgeValue:badge forButton:3];
7403 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7404 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7405 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7406 [self setApplicationBadge:badge];
7408 [self setApplicationBadgeString:badge];
7410 [buttonbar_ setBadgeValue:nil forButton:3];
7411 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7412 [buttonbar_ setBadgeAnimated:NO forButton:3];
7413 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7414 [self removeApplicationBadge];
7415 else // XXX: maybe use setApplicationBadgeString also?
7416 [self setApplicationIconBadgeNumber:0];
7420 [buttonbar_ setBadgeValue:nil forButton:4];
7424 // XXX: what is this line of code for?
7425 if ([packages count] == 0);
7426 else if (Loaded_ || ManualRefresh) loaded:
7431 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7432 NSTimeInterval interval([update timeIntervalSinceNow]);
7433 if (interval <= 0 && interval > -600)
7441 - (void) _saveConfig {
7444 NSString *error(nil);
7445 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7447 NSError *error(nil);
7448 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7449 NSLog(@"failure to save metadata data: %@", error);
7452 NSLog(@"failure to serialize metadata: %@", error);
7460 - (void) updateData {
7463 /* XXX: this is just stupid */
7464 if (tag_ != 2 && sections_ != nil)
7465 [sections_ reloadData];
7466 if (tag_ != 3 && changes_ != nil)
7467 [changes_ reloadData];
7468 if (tag_ != 5 && search_ != nil)
7469 [search_ reloadData];
7479 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7480 _assert(file != NULL);
7482 NSArray *keys = [Sources_ allKeys];
7484 for (NSString *key in keys) {
7485 NSDictionary *source = [Sources_ objectForKey:key];
7487 fprintf(file, "%s %s %s\n",
7488 [[source objectForKey:@"Type"] UTF8String],
7489 [[source objectForKey:@"URI"] UTF8String],
7490 [[source objectForKey:@"Distribution"] UTF8String]
7499 detachNewThreadSelector:@selector(update_)
7502 title:CYLocalize("UPDATING_SOURCES")
7506 - (void) reloadData {
7507 @synchronized (self) {
7508 if (confirm_ == nil)
7514 pkgProblemResolver *resolver = [database_ resolver];
7516 resolver->InstallProtect();
7517 if (!resolver->Resolve(true))
7521 - (void) popUpBook:(RVBook *)book {
7522 [underlay_ popSubview:book];
7525 - (CGRect) popUpBounds {
7526 return [underlay_ bounds];
7530 [database_ prepare];
7532 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7533 [confirm_ setDelegate:self];
7535 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7536 [page setDelegate:self];
7538 [confirm_ setPage:page];
7539 [self popUpBook:confirm_];
7543 @synchronized (self) {
7548 - (void) clearPackage:(Package *)package {
7549 @synchronized (self) {
7556 - (void) installPackage:(Package *)package {
7557 @synchronized (self) {
7564 - (void) removePackage:(Package *)package {
7565 @synchronized (self) {
7572 - (void) distUpgrade {
7573 @synchronized (self) {
7574 [database_ upgrade];
7580 [self slideUp:[[[UIActionSheet alloc]
7582 buttons:[NSArray arrayWithObjects:CYLocalize("CONTINUE_QUEUING"), CYLocalize("CANCEL_CLEAR"), nil]
7583 defaultButtonIndex:1
7590 @synchronized (self) {
7593 if (confirm_ != nil) {
7601 [overlay_ removeFromSuperview];
7605 detachNewThreadSelector:@selector(perform)
7608 title:CYLocalize("RUNNING")
7612 - (void) bootstrap_ {
7614 [database_ upgrade];
7615 [database_ prepare];
7616 [database_ perform];
7619 /* XXX: replace and localize */
7620 - (void) bootstrap {
7622 detachNewThreadSelector:@selector(bootstrap_)
7625 title:@"Bootstrap Install"
7629 - (void) progressViewIsComplete:(ProgressView *)progress {
7630 if (confirm_ != nil) {
7631 [underlay_ addSubview:overlay_];
7632 [confirm_ popFromSuperviewAnimated:NO];
7638 - (void) setPage:(RVPage *)page {
7639 [page resetViewAnimated:NO];
7640 [page setDelegate:self];
7641 [book_ setPage:page];
7644 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7645 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7646 [browser loadURL:url];
7650 - (void) _setHomePage {
7651 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7654 - (SectionsView *) sectionsView {
7655 if (sections_ == nil)
7656 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7660 - (void) buttonBarItemTapped:(id)sender {
7661 unsigned tag = [sender tag];
7663 [book_ resetViewAnimated:YES];
7665 } else if (tag_ == 2 && tag != 2)
7666 [[self sectionsView] resetView];
7669 case 1: [self _setHomePage]; break;
7671 case 2: [self setPage:[self sectionsView]]; break;
7672 case 3: [self setPage:changes_]; break;
7673 case 4: [self setPage:manage_]; break;
7674 case 5: [self setPage:search_]; break;
7676 default: _assert(false);
7682 - (void) applicationWillSuspend {
7684 [super applicationWillSuspend];
7687 - (void) askForSettings {
7688 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
7690 UIActionSheet *role = [[[UIActionSheet alloc]
7691 initWithTitle:CYLocalize("WHO_ARE_YOU")
7692 buttons:[NSArray arrayWithObjects:
7693 [NSString stringWithFormat:parenthetical, CYLocalize("USER"), CYLocalize("USER_EX")],
7694 [NSString stringWithFormat:parenthetical, CYLocalize("HACKER"), CYLocalize("HACKER_EX")],
7695 [NSString stringWithFormat:parenthetical, CYLocalize("DEVELOPER"), CYLocalize("DEVELOPER_EX")],
7697 defaultButtonIndex:-1
7702 [role setBodyText:CYLocalize("ROLE_EX")];
7703 [role popupAlertAnimated:YES];
7706 - (void) setPackageView:(PackageView *)view {
7708 [view setPackage:nil];
7709 if ([details_ count] < 3)
7710 [details_ addObject:view];
7714 - (PackageView *) _packageView {
7715 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7718 - (PackageView *) packageView {
7720 size_t count([details_ count]);
7723 view = [self _packageView];
7725 [details_ addObject:[self _packageView]];
7727 view = [[[details_ lastObject] retain] autorelease];
7728 [details_ removeLastObject];
7738 [self setStatusBarShowsProgress:NO];
7739 [self removeProgressHUD:hud_];
7744 pid_t pid = ExecFork();
7746 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7747 perror("launchctl stop");
7754 [self askForSettings];
7759 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7761 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7762 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7763 0, 0, screenrect.size.width, screenrect.size.height - 48
7764 ) database:database_];
7766 [book_ setDelegate:self];
7768 [overlay_ addSubview:book_];
7770 NSArray *buttonitems = [NSArray arrayWithObjects:
7771 [NSDictionary dictionaryWithObjectsAndKeys:
7772 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7773 @"home-up.png", kUIButtonBarButtonInfo,
7774 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7775 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7776 self, kUIButtonBarButtonTarget,
7777 @"Cydia", kUIButtonBarButtonTitle,
7778 @"0", kUIButtonBarButtonType,
7781 [NSDictionary dictionaryWithObjectsAndKeys:
7782 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7783 @"install-up.png", kUIButtonBarButtonInfo,
7784 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7785 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7786 self, kUIButtonBarButtonTarget,
7787 CYLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7788 @"0", kUIButtonBarButtonType,
7791 [NSDictionary dictionaryWithObjectsAndKeys:
7792 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7793 @"changes-up.png", kUIButtonBarButtonInfo,
7794 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7795 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7796 self, kUIButtonBarButtonTarget,
7797 CYLocalize("CHANGES"), kUIButtonBarButtonTitle,
7798 @"0", kUIButtonBarButtonType,
7801 [NSDictionary dictionaryWithObjectsAndKeys:
7802 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7803 @"manage-up.png", kUIButtonBarButtonInfo,
7804 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7805 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7806 self, kUIButtonBarButtonTarget,
7807 CYLocalize("MANAGE"), kUIButtonBarButtonTitle,
7808 @"0", kUIButtonBarButtonType,
7811 [NSDictionary dictionaryWithObjectsAndKeys:
7812 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7813 @"search-up.png", kUIButtonBarButtonInfo,
7814 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7815 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7816 self, kUIButtonBarButtonTarget,
7817 CYLocalize("SEARCH"), kUIButtonBarButtonTitle,
7818 @"0", kUIButtonBarButtonType,
7822 buttonbar_ = [[UIToolbar alloc]
7824 withFrame:CGRectMake(
7825 0, screenrect.size.height - ButtonBarHeight_,
7826 screenrect.size.width, ButtonBarHeight_
7828 withItemList:buttonitems
7831 [buttonbar_ setDelegate:self];
7832 [buttonbar_ setBarStyle:1];
7833 [buttonbar_ setButtonBarTrackingMode:2];
7835 int buttons[5] = {1, 2, 3, 4, 5};
7836 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7837 [buttonbar_ showButtonGroup:0 withDuration:0];
7839 for (int i = 0; i != 5; ++i)
7840 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7841 i * 64 + 2, 1, 60, ButtonBarHeight_
7844 [buttonbar_ showSelectionForButton:1];
7845 [overlay_ addSubview:buttonbar_];
7847 [UIKeyboard initImplementationNow];
7848 CGSize keysize = [UIKeyboard defaultSize];
7849 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7850 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7851 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
7852 [overlay_ addSubview:keyboard_];
7855 [underlay_ addSubview:overlay_];
7859 [self sectionsView];
7860 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7861 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7863 manage_ = (ManageView *) [[self
7864 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7865 withClass:[ManageView class]
7868 details_ = [[NSMutableArray alloc] initWithCapacity:4];
7869 [details_ addObject:[self _packageView]];
7870 [details_ addObject:[self _packageView]];
7877 [self _setHomePage];
7880 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7881 NSString *context([sheet context]);
7883 if ([context isEqualToString:@"missing"])
7885 else if ([context isEqualToString:@"cancel"]) {
7903 @synchronized (self) {
7908 [buttonbar_ setBadgeValue:CYLocalize("Q_D") forButton:4];
7912 if (confirm_ != nil) {
7917 } else if ([context isEqualToString:@"fixhalf"]) {
7920 @synchronized (self) {
7921 for (Package *broken in broken_) {
7924 NSString *id = [broken id];
7925 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7926 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7927 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7928 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7937 [broken_ removeAllObjects];
7946 } else if ([context isEqualToString:@"role"]) {
7948 case 1: Role_ = @"User"; break;
7949 case 2: Role_ = @"Hacker"; break;
7950 case 3: Role_ = @"Developer"; break;
7957 bool reset = Settings_ != nil;
7959 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7963 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7973 } else if ([context isEqualToString:@"upgrade"]) {
7976 @synchronized (self) {
7977 for (Package *essential in essential_)
7978 [essential install];
8001 - (void) reorganize { _pooled
8002 system("/usr/libexec/cydia/free.sh");
8003 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
8006 - (void) applicationSuspend:(__GSEvent *)event {
8007 if (hud_ == nil && ![progress_ isRunning])
8008 [super applicationSuspend:event];
8011 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8013 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8016 - (void) _setSuspended:(BOOL)value {
8018 [super _setSuspended:value];
8021 - (UIProgressHUD *) addProgressHUD {
8022 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8023 [window_ setUserInteractionEnabled:NO];
8025 [progress_ addSubview:hud];
8029 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8031 [hud removeFromSuperview];
8032 [window_ setUserInteractionEnabled:YES];
8035 - (void) openMailToURL:(NSURL *)url {
8036 // XXX: this makes me sad
8038 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
8040 [UIApp openURL:url];// asPanel:YES];
8044 - (void) clearFirstResponder {
8045 if (id responder = [window_ firstResponder])
8046 [responder resignFirstResponder];
8049 - (RVPage *) pageForPackage:(NSString *)name {
8050 if (Package *package = [database_ packageWithName:name]) {
8051 PackageView *view([self packageView]);
8052 [view setPackage:package];
8055 UIActionSheet *sheet = [[[UIActionSheet alloc]
8056 initWithTitle:CYLocalize("CANNOT_LOCATE_PACKAGE")
8057 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
8058 defaultButtonIndex:0
8063 [sheet setBodyText:[NSString stringWithFormat:CYLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
8065 [sheet popupAlertAnimated:YES];
8070 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8074 NSString *scheme([[url scheme] lowercaseString]);
8075 if (![scheme isEqualToString:@"cydia"])
8077 NSString *path([url absoluteString]);
8078 if ([path length] < 8)
8080 path = [path substringFromIndex:8];
8081 if (![path hasPrefix:@"/"])
8082 path = [@"/" stringByAppendingString:path];
8084 if ([path isEqualToString:@"/add-source"])
8085 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8086 else if ([path isEqualToString:@"/storage"])
8087 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[BrowserView class]];
8088 else if ([path isEqualToString:@"/sources"])
8089 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8090 else if ([path isEqualToString:@"/packages"])
8091 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8092 else if ([path hasPrefix:@"/url/"])
8093 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[BrowserView class]];
8094 else if ([path hasPrefix:@"/launch/"])
8095 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8096 else if ([path hasPrefix:@"/package-settings/"])
8097 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8098 else if ([path hasPrefix:@"/package-signature/"])
8099 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8100 else if ([path hasPrefix:@"/package/"])
8101 return [self pageForPackage:[path substringFromIndex:9]];
8102 else if ([path hasPrefix:@"/files/"]) {
8103 NSString *name = [path substringFromIndex:7];
8105 if (Package *package = [database_ packageWithName:name]) {
8106 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8107 [files setPackage:package];
8115 - (void) applicationOpenURL:(NSURL *)url {
8116 [super applicationOpenURL:url];
8118 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8119 [self setPage:page];
8120 [buttonbar_ showSelectionForButton:tag];
8125 - (void) applicationDidFinishLaunching:(id)unused {
8127 Font12_ = [[UIFont systemFontOfSize:12] retain];
8128 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8129 Font14_ = [[UIFont systemFontOfSize:14] retain];
8130 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8131 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8135 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8136 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8138 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8140 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8141 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
8143 [window_ orderFront:self];
8144 [window_ makeKey:self];
8145 [window_ setHidden:NO];
8147 database_ = [Database sharedInstance];
8148 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8149 [database_ setDelegate:progress_];
8150 [window_ setContentView:progress_];
8152 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8153 [progress_ setContentView:underlay_];
8155 [progress_ resetView];
8158 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8159 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8160 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL /*||
8161 readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL*/ ||
8162 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8163 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8164 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8165 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
8166 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
8168 [self setIdleTimerDisabled:YES];
8170 hud_ = [[self addProgressHUD] retain];
8171 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8173 [self setStatusBarShowsProgress:YES];
8176 detachNewThreadSelector:@selector(reorganize)
8184 - (void) showKeyboard:(BOOL)show {
8185 CGSize keysize = [UIKeyboard defaultSize];
8186 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8187 CGRect keyup = keydown;
8188 keyup.origin.y -= keysize.height;
8190 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
8191 [animation setSignificantRectFields:2];
8194 [animation setStartFrame:keydown];
8195 [animation setEndFrame:keyup];
8196 [keyboard_ activate];
8198 [animation setStartFrame:keyup];
8199 [animation setEndFrame:keydown];
8200 [keyboard_ deactivate];
8203 [[UIAnimator sharedAnimator]
8204 addAnimations:[NSArray arrayWithObjects:animation, nil]
8205 withDuration:KeyboardTime_
8210 - (void) slideUp:(UIActionSheet *)alert {
8212 [alert presentSheetFromButtonBar:buttonbar_];
8214 [alert presentSheetInView:overlay_];
8219 void AddPreferences(NSString *plist) { _pooled
8220 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
8221 _assert(settings != NULL);
8222 NSMutableArray *items = [settings objectForKey:@"items"];
8226 for (NSMutableDictionary *item in items) {
8227 NSString *label = [item objectForKey:@"label"];
8228 if (label != nil && [label isEqualToString:@"Cydia"]) {
8235 for (size_t i(0); i != [items count]; ++i) {
8236 NSDictionary *item([items objectAtIndex:i]);
8237 NSString *label = [item objectForKey:@"label"];
8238 if (label != nil && [label isEqualToString:@"General"]) {
8239 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
8240 @"CydiaSettings", @"bundle",
8241 @"PSLinkCell", @"cell",
8242 [NSNumber numberWithBool:YES], @"hasIcon",
8243 [NSNumber numberWithBool:YES], @"isController",
8245 nil] atIndex:(i + 1)];
8251 _assert([settings writeToFile:plist atomically:YES] == YES);
8256 id Alloc_(id self, SEL selector) {
8257 id object = alloc_(self, selector);
8258 lprintf("[%s]A-%p\n", self->isa->name, object);
8263 id Dealloc_(id self, SEL selector) {
8264 id object = dealloc_(self, selector);
8265 lprintf("[%s]D-%p\n", self->isa->name, object);
8269 Class $WebDefaultUIKitDelegate;
8271 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
8273 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
8274 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8275 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8276 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
8279 int main(int argc, char *argv[]) { _pooled
8282 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8284 /* Library Hacks {{{ */
8285 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8287 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8288 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8289 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8290 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8291 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8294 /* Set Locale {{{ */
8295 Locale_ = CFLocaleCopyCurrent();
8296 Languages_ = [NSLocale preferredLanguages];
8297 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8298 //NSLog(@"%@", [Languages_ description]);
8300 if (Languages_ == nil || [Languages_ count] == 0)
8303 lang = [[Languages_ objectAtIndex:0] UTF8String];
8304 setenv("LANG", lang, true);
8305 //std::setlocale(LC_ALL, lang);
8306 NSLog(@"Setting Language: %s", lang);
8309 // XXX: apr_app_initialize?
8312 /* Parse Arguments {{{ */
8313 bool substrate(false);
8319 for (int argi(1); argi != argc; ++argi)
8320 if (strcmp(argv[argi], "--") == 0) {
8322 argv[argi] = argv[0];
8328 for (int argi(1); argi != arge; ++argi)
8329 if (strcmp(args[argi], "--bootstrap") == 0)
8331 else if (strcmp(args[argi], "--substrate") == 0)
8334 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8339 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
8340 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
8341 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
8342 Sounds_Keyboard_ = [keyboard boolValue];
8345 App_ = [[NSBundle mainBundle] bundlePath];
8346 Home_ = NSHomeDirectory();
8351 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8352 alloc_ = alloc->method_imp;
8353 alloc->method_imp = (IMP) &Alloc_;*/
8355 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8356 dealloc_ = dealloc->method_imp;
8357 dealloc->method_imp = (IMP) &Dealloc_;*/
8362 size = sizeof(maxproc);
8363 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8364 perror("sysctlbyname(\"kern.maxproc\", ?)");
8365 else if (maxproc < 64) {
8367 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8368 perror("sysctlbyname(\"kern.maxproc\", #)");
8371 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8372 char *machine = new char[size];
8373 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8374 perror("sysctlbyname(\"hw.machine\", ?)");
8378 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8380 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8381 Build_ = [system objectForKey:@"ProductBuildVersion"];
8382 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8383 Product_ = [info objectForKey:@"SafariProductVersion"];
8384 Safari_ = [info objectForKey:@"CFBundleVersion"];
8387 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8388 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
8390 /* Load Database {{{ */
8392 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8394 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8397 if (Metadata_ == NULL)
8398 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8400 Settings_ = [Metadata_ objectForKey:@"Settings"];
8402 Packages_ = [Metadata_ objectForKey:@"Packages"];
8403 Sections_ = [Metadata_ objectForKey:@"Sections"];
8404 Sources_ = [Metadata_ objectForKey:@"Sources"];
8407 if (Settings_ != nil)
8408 Role_ = [Settings_ objectForKey:@"Role"];
8410 if (Packages_ == nil) {
8411 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8412 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8415 if (Sections_ == nil) {
8416 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8417 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8420 if (Sources_ == nil) {
8421 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8422 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8427 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8430 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8431 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8432 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8433 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8435 if (access("/User", F_OK) != 0) {
8437 system("/usr/libexec/cydia/firmware.sh");
8441 _assert([[NSFileManager defaultManager]
8442 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8443 withIntermediateDirectories:YES
8448 if (access("/tmp/cydia.chk", F_OK) == 0) {
8449 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8450 _assert(errno == ENOENT);
8451 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8452 _assert(errno == ENOENT);
8455 _assert(pkgInitConfig(*_config));
8456 _assert(pkgInitSystem(*_config, _system));
8459 _config->Set("APT::Acquire::Translation", lang);
8460 _config->Set("Acquire::http::Timeout", 15);
8461 _config->Set("Acquire::http::MaxParallel", 4);
8463 /* Color Choices {{{ */
8464 space_ = CGColorSpaceCreateDeviceRGB();
8466 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8467 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8468 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8469 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8470 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8471 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8472 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8473 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8474 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8475 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8476 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8477 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8478 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8479 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8480 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8483 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8484 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8487 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8489 /* UIKit Configuration {{{ */
8490 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8491 if ($GSFontSetUseLegacyFontMetrics != NULL)
8492 $GSFontSetUseLegacyFontMetrics(YES);
8494 UIKeyboardDisableAutomaticAppearance();
8498 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8500 CGColorSpaceRelease(space_);