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 NotifyConfig_ "/etc/notify.conf"
1056 static bool Queuing_;
1058 static CGColor Blue_;
1059 static CGColor Blueish_;
1060 static CGColor Black_;
1061 static CGColor Off_;
1062 static CGColor White_;
1063 static CGColor Gray_;
1064 static CGColor Green_;
1065 static CGColor Purple_;
1066 static CGColor Purplish_;
1068 static UIColor *InstallingColor_;
1069 static UIColor *RemovingColor_;
1071 static NSString *App_;
1072 static NSString *Home_;
1073 static BOOL Sounds_Keyboard_;
1075 static BOOL Advanced_;
1076 static BOOL Loaded_;
1077 static BOOL Ignored_;
1079 static UIFont *Font12_;
1080 static UIFont *Font12Bold_;
1081 static UIFont *Font14_;
1082 static UIFont *Font18Bold_;
1083 static UIFont *Font22Bold_;
1085 static const char *Machine_ = NULL;
1086 static const NSString *UniqueID_ = nil;
1087 static const NSString *Build_ = nil;
1088 static const NSString *Product_ = nil;
1089 static const NSString *Safari_ = nil;
1091 CFLocaleRef Locale_;
1092 NSArray *Languages_;
1093 CGColorSpaceRef space_;
1098 static NSDictionary *SectionMap_;
1099 static NSMutableDictionary *Metadata_;
1100 static _transient NSMutableDictionary *Settings_;
1101 static _transient NSString *Role_;
1102 static _transient NSMutableDictionary *Packages_;
1103 static _transient NSMutableDictionary *Sections_;
1104 static _transient NSMutableDictionary *Sources_;
1105 static bool Changed_;
1106 static NSDate *now_;
1109 static NSMutableArray *Documents_;
1112 NSString *GetLastUpdate() {
1113 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1116 return CYLocalize("NEVER_OR_UNKNOWN");
1118 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1119 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1121 CFRelease(formatter);
1123 return [(NSString *) formatted autorelease];
1126 /* Display Helpers {{{ */
1127 inline float Interpolate(float begin, float end, float fraction) {
1128 return (end - begin) * fraction + begin;
1131 /* XXX: localize this! */
1132 NSString *SizeString(double size) {
1133 bool negative = size < 0;
1138 while (size > 1024) {
1143 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1145 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1148 static _finline CFStringRef CFCString(const char *value) {
1149 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1152 const char *StripVersion_(const char *version) {
1153 const char *colon(strchr(version, ':'));
1155 version = colon + 1;
1159 CFStringRef StripVersion(const char *version) {
1160 const char *colon(strchr(version, ':'));
1162 version = colon + 1;
1163 return CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO);
1165 return CFCString(version);
1168 NSString *LocalizeSection(NSString *section) {
1169 static Pcre title_r("^(.*?) \\((.*)\\)$");
1170 if (title_r(section)) {
1171 NSString *parent(title_r[1]);
1172 NSString *child(title_r[2]);
1174 return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"),
1175 LocalizeSection(parent),
1176 LocalizeSection(child)
1180 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1183 NSString *Simplify(NSString *title) {
1184 const char *data = [title UTF8String];
1185 size_t size = [title length];
1187 static Pcre square_r("^\\[(.*)\\]$");
1188 if (square_r(data, size))
1189 return Simplify(square_r[1]);
1191 static Pcre paren_r("^\\((.*)\\)$");
1192 if (paren_r(data, size))
1193 return Simplify(paren_r[1]);
1195 static Pcre title_r("^(.*?) \\((.*)\\)$");
1196 if (title_r(data, size))
1197 return Simplify(title_r[1]);
1203 bool isSectionVisible(NSString *section) {
1204 NSDictionary *metadata([Sections_ objectForKey:section]);
1205 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1206 return hidden == nil || ![hidden boolValue];
1209 /* Delegate Prototypes {{{ */
1213 @interface NSObject (ProgressDelegate)
1216 @implementation NSObject(ProgressDelegate)
1218 - (void) _setProgressError:(NSArray *)args {
1219 [self performSelector:@selector(setProgressError:forPackage:)
1220 withObject:[args objectAtIndex:0]
1221 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1227 @protocol ProgressDelegate
1228 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1229 - (void) setProgressTitle:(NSString *)title;
1230 - (void) setProgressPercent:(float)percent;
1231 - (void) startProgress;
1232 - (void) addProgressOutput:(NSString *)output;
1233 - (bool) isCancelling:(size_t)received;
1236 @protocol ConfigurationDelegate
1237 - (void) repairWithSelector:(SEL)selector;
1238 - (void) setConfigurationData:(NSString *)data;
1243 @protocol CydiaDelegate
1244 - (void) setPackageView:(PackageView *)view;
1245 - (void) clearPackage:(Package *)package;
1246 - (void) installPackage:(Package *)package;
1247 - (void) removePackage:(Package *)package;
1248 - (void) slideUp:(UIActionSheet *)alert;
1249 - (void) distUpgrade;
1250 - (void) updateData;
1252 - (void) askForSettings;
1253 - (UIProgressHUD *) addProgressHUD;
1254 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1255 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag;
1256 - (RVPage *) pageForPackage:(NSString *)name;
1257 - (void) openMailToURL:(NSURL *)url;
1258 - (void) clearFirstResponder;
1259 - (PackageView *) packageView;
1263 /* Status Delegation {{{ */
1265 public pkgAcquireStatus
1268 _transient NSObject<ProgressDelegate> *delegate_;
1276 void setDelegate(id delegate) {
1277 delegate_ = delegate;
1280 virtual bool MediaChange(std::string media, std::string drive) {
1284 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1287 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1288 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1289 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
1292 virtual void Done(pkgAcquire::ItemDesc &item) {
1295 virtual void Fail(pkgAcquire::ItemDesc &item) {
1297 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1298 item.Owner->Status == pkgAcquire::Item::StatDone
1302 std::string &error(item.Owner->ErrorText);
1306 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1307 NSArray *fields([description componentsSeparatedByString:@" "]);
1308 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1310 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1311 withObject:[NSArray arrayWithObjects:
1312 [NSString stringWithUTF8String:error.c_str()],
1319 virtual bool Pulse(pkgAcquire *Owner) {
1320 bool value = pkgAcquireStatus::Pulse(Owner);
1323 double(CurrentBytes + CurrentItems) /
1324 double(TotalBytes + TotalItems)
1327 [delegate_ setProgressPercent:percent];
1328 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1331 virtual void Start() {
1332 [delegate_ startProgress];
1335 virtual void Stop() {
1339 /* Progress Delegation {{{ */
1344 _transient id<ProgressDelegate> delegate_;
1347 virtual void Update() {
1348 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1349 [delegate_ setProgressPercent:(Percent / 100)];*/
1358 void setDelegate(id delegate) {
1359 delegate_ = delegate;
1362 virtual void Done() {
1363 //[delegate_ setProgressPercent:1];
1368 /* Database Interface {{{ */
1369 typedef std::map< unsigned long, _H<Source> > SourceMap;
1371 @interface Database : NSObject {
1377 pkgCacheFile cache_;
1378 pkgDepCache::Policy *policy_;
1379 pkgRecords *records_;
1380 pkgProblemResolver *resolver_;
1381 pkgAcquire *fetcher_;
1383 SPtr<pkgPackageManager> manager_;
1384 pkgSourceList *list_;
1387 NSMutableArray *packages_;
1389 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1398 + (Database *) sharedInstance;
1401 - (void) _readCydia:(NSNumber *)fd;
1402 - (void) _readStatus:(NSNumber *)fd;
1403 - (void) _readOutput:(NSNumber *)fd;
1407 - (Package *) packageWithName:(NSString *)name;
1409 - (pkgCacheFile &) cache;
1410 - (pkgDepCache::Policy *) policy;
1411 - (pkgRecords *) records;
1412 - (pkgProblemResolver *) resolver;
1413 - (pkgAcquire &) fetcher;
1414 - (pkgSourceList &) list;
1415 - (NSArray *) packages;
1416 - (NSArray *) sources;
1417 - (void) reloadData;
1425 - (NSString *) updateWithStatus:(Status &)status;
1427 - (void) setDelegate:(id)delegate;
1428 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1432 /* Source Class {{{ */
1433 @interface Source : NSObject {
1434 CYString depiction_;
1435 CYString description_;
1441 CYString distribution_;
1447 CYString defaultIcon_;
1449 NSDictionary *record_;
1453 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1455 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1457 - (NSString *) depictionForPackage:(NSString *)package;
1458 - (NSString *) supportForPackage:(NSString *)package;
1460 - (NSDictionary *) record;
1464 - (NSString *) distribution;
1465 - (NSString *) type;
1467 - (NSString *) host;
1469 - (NSString *) name;
1470 - (NSString *) description;
1471 - (NSString *) label;
1472 - (NSString *) origin;
1473 - (NSString *) version;
1475 - (NSString *) defaultIcon;
1479 @implementation Source
1483 distribution_.clear();
1486 description_.clear();
1492 defaultIcon_.clear();
1494 if (record_ != nil) {
1510 + (NSArray *) _attributeKeys {
1511 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1514 - (NSArray *) attributeKeys {
1515 return [[self class] _attributeKeys];
1518 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1519 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1522 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1525 trusted_ = index->IsTrusted();
1527 uri_.set(pool, index->GetURI());
1528 distribution_.set(pool, index->GetDist());
1529 type_.set(pool, index->GetType());
1531 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1532 if (dindex != NULL) {
1534 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1537 pkgTagFile tags(&fd);
1539 pkgTagSection section;
1546 {"default-icon", &defaultIcon_},
1547 {"depiction", &depiction_},
1548 {"description", &description_},
1550 {"origin", &origin_},
1551 {"support", &support_},
1552 {"version", &version_},
1555 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1556 const char *start, *end;
1558 if (section.Find(names[i].name_, start, end)) {
1559 CYString &value(*names[i].value_);
1560 value.set(pool, start, end - start);
1566 record_ = [Sources_ objectForKey:[self key]];
1568 record_ = [record_ retain];
1570 host_ = [[[[NSURL URLWithString:uri_] host] lowercaseString] retain];
1573 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1574 if ((self = [super init]) != nil) {
1575 [self setMetaIndex:index inPool:pool];
1579 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1580 NSDictionary *lhr = [self record];
1581 NSDictionary *rhr = [source record];
1584 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1586 NSString *lhs = [self name];
1587 NSString *rhs = [source name];
1589 if ([lhs length] != 0 && [rhs length] != 0) {
1590 unichar lhc = [lhs characterAtIndex:0];
1591 unichar rhc = [rhs characterAtIndex:0];
1593 if (isalpha(lhc) && !isalpha(rhc))
1594 return NSOrderedAscending;
1595 else if (!isalpha(lhc) && isalpha(rhc))
1596 return NSOrderedDescending;
1599 return [lhs compare:rhs options:LaxCompareOptions_];
1602 - (NSString *) depictionForPackage:(NSString *)package {
1603 return depiction_.empty() ? nil : [depiction_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1606 - (NSString *) supportForPackage:(NSString *)package {
1607 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1610 - (NSDictionary *) record {
1618 - (NSString *) uri {
1622 - (NSString *) distribution {
1623 return distribution_;
1626 - (NSString *) type {
1630 - (NSString *) key {
1631 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1634 - (NSString *) host {
1638 - (NSString *) name {
1639 return origin_.empty() ? host_ : origin_;
1642 - (NSString *) description {
1643 return description_;
1646 - (NSString *) label {
1647 return label_.empty() ? host_ : label_;
1650 - (NSString *) origin {
1654 - (NSString *) version {
1658 - (NSString *) defaultIcon {
1659 return defaultIcon_;
1664 /* Relationship Class {{{ */
1665 @interface Relationship : NSObject {
1670 - (NSString *) type;
1672 - (NSString *) name;
1676 @implementation Relationship
1684 - (NSString *) type {
1692 - (NSString *) name {
1699 /* Package Class {{{ */
1700 @interface Package : NSObject {
1704 pkgCache::VerIterator version_;
1705 pkgCache::PkgIterator iterator_;
1706 _transient Database *database_;
1707 pkgCache::VerFileIterator file_;
1714 NSString *section$_;
1719 CYString installed_;
1725 CYString depiction_;
1735 NSMutableArray *tags_;
1738 NSArray *relationships_;
1740 NSMutableDictionary *metadata_;
1741 _transient NSDate *firstSeen_;
1742 _transient NSDate *lastSeen_;
1746 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1747 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1749 - (pkgCache::PkgIterator) iterator;
1752 - (NSString *) section;
1753 - (NSString *) simpleSection;
1755 - (NSString *) longSection;
1756 - (NSString *) shortSection;
1760 - (Address *) maintainer;
1762 - (NSString *) longDescription;
1763 - (NSString *) shortDescription;
1766 - (NSMutableDictionary *) metadata;
1768 - (BOOL) subscribed;
1771 - (NSString *) latest;
1772 - (NSString *) installed;
1773 - (BOOL) uninstalled;
1776 - (BOOL) upgradableAndEssential:(BOOL)essential;
1779 - (BOOL) unfiltered;
1783 - (BOOL) halfConfigured;
1784 - (BOOL) halfInstalled;
1786 - (NSString *) mode;
1789 - (NSString *) name;
1791 - (NSString *) homepage;
1792 - (NSString *) depiction;
1793 - (Address *) author;
1795 - (NSString *) support;
1797 - (NSArray *) files;
1798 - (NSArray *) relationships;
1799 - (NSArray *) warnings;
1800 - (NSArray *) applications;
1802 - (Source *) source;
1803 - (NSString *) role;
1805 - (BOOL) matches:(NSString *)text;
1807 - (bool) hasSupportingRole;
1808 - (BOOL) hasTag:(NSString *)tag;
1809 - (NSString *) primaryPurpose;
1810 - (NSArray *) purposes;
1811 - (bool) isCommercial;
1813 - (CYString &) cyname;
1815 - (uint32_t) compareBySection:(NSArray *)sections;
1817 - (uint32_t) compareForChanges;
1822 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1823 - (bool) isInstalledAndVisible:(NSNumber *)number;
1824 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1825 - (bool) isVisibleInSource:(Source *)source;
1829 uint32_t PackageChangesRadix(Package *self, void *) {
1834 uint32_t timestamp : 30;
1835 uint32_t ignored : 1;
1836 uint32_t upgradable : 1;
1840 bool upgradable([self upgradableAndEssential:YES]);
1841 value.bits.upgradable = upgradable ? 1 : 0;
1844 value.bits.timestamp = 0;
1845 value.bits.ignored = [self ignored] ? 0 : 1;
1846 value.bits.upgradable = 1;
1848 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1849 value.bits.ignored = 0;
1850 value.bits.upgradable = 0;
1853 return _not(uint32_t) - value.key;
1856 _finline static void Stifle(uint8_t &value) {
1859 uint32_t PackagePrefixRadix(Package *self, void *context) {
1860 size_t offset(reinterpret_cast<size_t>(context));
1861 CYString &name([self cyname]);
1863 size_t size(name.size());
1866 char *text(name.data());
1869 if (!isdigit(text[0]))
1873 while (size != digits && isdigit(text[digits]))
1883 if (offset == 0 && zeros != 0) {
1884 memset(data, '0', zeros);
1885 memcpy(data + zeros, text, 4 - zeros);
1887 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1888 if (size <= offset - zeros)
1891 text += offset - zeros;
1892 size -= offset - zeros;
1895 memcpy(data, text, 4);
1897 memcpy(data, text, size);
1898 memset(data + size, 0, 4 - size);
1901 for (size_t i(0); i != 4; ++i)
1902 if (isalpha(data[i]))
1907 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1909 /* XXX: ntohl may be more honest */
1910 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1913 CYString &(*PackageName)(Package *self, SEL sel);
1915 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1916 _profile(PackageNameCompare)
1917 CYString &lhi(PackageName(lhs, @selector(cyname)));
1918 CYString &rhi(PackageName(rhs, @selector(cyname)));
1919 CFStringRef lhn(lhi), rhn(rhi);
1921 _profile(PackageNameCompare$NumbersLast)
1922 if (!lhi.empty() && !rhi.empty()) {
1923 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1924 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1925 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1926 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1927 return lha ? NSOrderedAscending : NSOrderedDescending;
1931 CFIndex length = CFStringGetLength(lhn);
1933 _profile(PackageNameCompare$Compare)
1934 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1939 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1940 return PackageNameCompare(*lhs, *rhs, context);
1943 struct PackageNameOrdering :
1944 std::binary_function<Package *, Package *, bool>
1946 _finline bool operator ()(Package *lhs, Package *rhs) const {
1947 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1951 @implementation Package
1953 - (NSString *) description {
1954 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1960 if (section$_ != nil)
1961 [section$_ release];
1966 if (sponsor$_ != nil)
1967 [sponsor$_ release];
1968 if (author$_ != nil)
1975 if (relationships_ != nil)
1976 [relationships_ release];
1977 if (metadata_ != nil)
1978 [metadata_ release];
1983 + (NSString *) webScriptNameForSelector:(SEL)selector {
1984 if (selector == @selector(hasTag:))
1990 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1991 return [self webScriptNameForSelector:selector] == nil;
1994 + (NSArray *) _attributeKeys {
1995 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];
1998 - (NSArray *) attributeKeys {
1999 return [[self class] _attributeKeys];
2002 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2003 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2013 _profile(Package$parse)
2014 pkgRecords::Parser *parser;
2016 _profile(Package$parse$Lookup)
2017 parser = &[database_ records]->Lookup(file_);
2022 _profile(Package$parse$Find)
2028 {"depiction", &depiction_},
2029 {"homepage", &homepage_},
2030 {"website", &website},
2031 {"support", &support_},
2032 {"sponsor", &sponsor_},
2033 {"author", &author_},
2036 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2037 const char *start, *end;
2039 if (parser->Find(names[i].name_, start, end)) {
2040 CYString &value(*names[i].value_);
2041 _profile(Package$parse$Value)
2042 value.set(pool_, start, end - start);
2048 _profile(Package$parse$Tagline)
2049 const char *start, *end;
2050 if (parser->ShortDesc(start, end)) {
2051 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2054 while (stop != start && stop[-1] == '\r')
2056 tagline_.set(pool_, start, stop - start);
2060 _profile(Package$parse$Retain)
2061 if (!homepage_.empty())
2062 homepage_ = website;
2063 if (homepage_ == depiction_)
2069 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2070 if ((self = [super init]) != nil) {
2071 _profile(Package$initWithVersion)
2072 @synchronized (database) {
2073 era_ = [database era];
2077 iterator_ = version.ParentPkg();
2078 database_ = database;
2080 _profile(Package$initWithVersion$Latest)
2081 latest_ = (NSString *) StripVersion(version_.VerStr());
2084 pkgCache::VerIterator current;
2085 _profile(Package$initWithVersion$Versions)
2086 current = iterator_.CurrentVer();
2088 installed_.set(pool_, StripVersion_(current.VerStr()));
2090 if (!version_.end())
2091 file_ = version_.FileList();
2093 pkgCache &cache([database_ cache]);
2094 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2098 _profile(Package$initWithVersion$Name)
2099 id_.set(pool_, iterator_.Name());
2100 name_.set(pool, iterator_.Display());
2104 _profile(Package$initWithVersion$Source)
2105 source_ = [database_ getSource:file_.File()];
2114 _profile(Package$initWithVersion$Tags)
2115 pkgCache::TagIterator tag(iterator_.TagList());
2117 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2119 const char *name(tag.Name());
2120 [tags_ addObject:(NSString *)CFCString(name)];
2121 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2122 role_ = (NSString *) CFCString(name + 6);
2123 if (visible_ && strncmp(name, "require::", 9) == 0 && (
2128 } while (!tag.end());
2132 bool changed(false);
2133 NSString *key([id_ lowercaseString]);
2135 _profile(Package$initWithVersion$Metadata)
2136 metadata_ = [Packages_ objectForKey:key];
2138 if (metadata_ == nil) {
2141 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2142 firstSeen_, @"FirstSeen",
2143 latest_, @"LastVersion",
2148 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2149 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2151 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2152 subscribed_ = [subscribed boolValue];
2154 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2156 if (firstSeen_ == nil) {
2157 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2158 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2162 if (version == nil) {
2163 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2166 if (![version isEqualToString:latest_]) {
2167 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2169 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2174 metadata_ = [metadata_ retain];
2177 [Packages_ setObject:metadata_ forKey:key];
2182 _profile(Package$initWithVersion$Section)
2183 section_.set(pool_, iterator_.Section());
2186 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2187 visible_ = visible_ && [self hasSupportingRole] && [self unfiltered];
2188 } _end } return self;
2191 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2192 pkgCache::VerIterator version;
2194 _profile(Package$packageWithIterator$GetCandidateVer)
2195 version = [database policy]->GetCandidateVer(iterator);
2201 return [[[Package alloc]
2202 initWithVersion:version
2209 - (pkgCache::PkgIterator) iterator {
2213 - (NSString *) section {
2214 if (section$_ == nil) {
2215 if (section_.empty())
2218 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2219 NSString *name(section_);
2222 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2223 if (NSString *rename = [value objectForKey:@"Rename"]) {
2228 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2232 - (NSString *) simpleSection {
2233 if (NSString *section = [self section])
2234 return Simplify(section);
2239 - (NSString *) longSection {
2240 return LocalizeSection([self section]);
2243 - (NSString *) shortSection {
2244 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2247 - (NSString *) uri {
2250 pkgIndexFile *index;
2251 pkgCache::PkgFileIterator file(file_.File());
2252 if (![database_ list].FindIndex(file, index))
2254 return [NSString stringWithUTF8String:iterator_->Path];
2255 //return [NSString stringWithUTF8String:file.Site()];
2256 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2260 - (Address *) maintainer {
2263 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2264 const std::string &maintainer(parser->Maintainer());
2265 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2269 return version_.end() ? 0 : version_->InstalledSize;
2272 - (NSString *) longDescription {
2275 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2276 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2278 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2279 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2280 if ([lines count] < 2)
2283 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2284 for (size_t i(1), e([lines count]); i != e; ++i) {
2285 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2286 [trimmed addObject:trim];
2289 return [trimmed componentsJoinedByString:@"\n"];
2292 - (NSString *) shortDescription {
2297 _profile(Package$index)
2298 CFStringRef name((CFStringRef) [self name]);
2299 if (CFStringGetLength(name) == 0)
2301 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2302 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2304 return toupper(character);
2308 - (NSMutableDictionary *) metadata {
2313 if (subscribed_ && lastSeen_ != nil)
2318 - (BOOL) subscribed {
2323 NSDictionary *metadata([self metadata]);
2324 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2325 return [ignored boolValue];
2330 - (NSString *) latest {
2334 - (NSString *) installed {
2338 - (BOOL) uninstalled {
2339 return installed_.empty();
2343 return !version_.end();
2346 - (BOOL) upgradableAndEssential:(BOOL)essential {
2347 _profile(Package$upgradableAndEssential)
2348 pkgCache::VerIterator current(iterator_.CurrentVer());
2350 return essential && essential_ && visible_;
2352 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2356 - (BOOL) essential {
2361 return [database_ cache][iterator_].InstBroken();
2364 - (BOOL) unfiltered {
2365 NSString *section([self section]);
2366 return section == nil || isSectionVisible(section);
2374 unsigned char current(iterator_->CurrentState);
2375 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2378 - (BOOL) halfConfigured {
2379 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2382 - (BOOL) halfInstalled {
2383 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2387 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2388 return state.Mode != pkgDepCache::ModeKeep;
2391 - (NSString *) mode {
2392 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2394 switch (state.Mode) {
2395 case pkgDepCache::ModeDelete:
2396 if ((state.iFlags & pkgDepCache::Purge) != 0)
2400 case pkgDepCache::ModeKeep:
2401 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2402 return @"REINSTALL";
2403 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2407 case pkgDepCache::ModeInstall:
2408 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2409 return @"REINSTALL";
2410 else*/ switch (state.Status) {
2412 return @"DOWNGRADE";
2418 return @"NEW_INSTALL";
2431 - (NSString *) name {
2432 return name_.empty() ? id_ : name_;
2435 - (UIImage *) icon {
2436 NSString *section = [self simpleSection];
2440 if ([icon_ hasPrefix:@"file:///"])
2441 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2442 if (icon == nil) if (section != nil)
2443 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2444 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2445 if ([dicon hasPrefix:@"file:///"])
2446 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2448 icon = [UIImage applicationImageNamed:@"unknown.png"];
2452 - (NSString *) homepage {
2456 - (NSString *) depiction {
2457 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2460 - (Address *) sponsor {
2461 if (sponsor$_ == nil) {
2462 if (sponsor_.empty())
2464 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2468 - (Address *) author {
2469 if (author$_ == nil) {
2470 if (author_.empty())
2472 author$_ = [[Address addressWithString:author_] retain];
2476 - (NSString *) support {
2477 return !support_.empty() ? support_ : [[self source] supportForPackage:id_];
2480 - (NSArray *) files {
2481 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2482 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2485 fin.open([path UTF8String]);
2490 while (std::getline(fin, line))
2491 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2496 - (NSArray *) relationships {
2497 return relationships_;
2500 - (NSArray *) warnings {
2501 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2502 const char *name(iterator_.Name());
2504 size_t length(strlen(name));
2505 if (length < 2) invalid:
2506 [warnings addObject:CYLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2507 else for (size_t i(0); i != length; ++i)
2509 /* XXX: technically this is not allowed */
2510 (name[i] < 'A' || name[i] > 'Z') &&
2511 (name[i] < 'a' || name[i] > 'z') &&
2512 (name[i] < '0' || name[i] > '9') &&
2513 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2516 if (strcmp(name, "cydia") != 0) {
2518 bool _private = false;
2521 bool repository = [[self section] isEqualToString:@"Repositories"];
2523 if (NSArray *files = [self files])
2524 for (NSString *file in files)
2525 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2527 else if (!_private && [file isEqualToString:@"/private"])
2529 else if (!stash && [file isEqualToString:@"/var/stash"])
2532 /* XXX: this is not sensitive enough. only some folders are valid. */
2533 if (cydia && !repository)
2534 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2536 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/private"]];
2538 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2541 return [warnings count] == 0 ? nil : warnings;
2544 - (NSArray *) applications {
2545 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2547 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2549 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2550 if (NSArray *files = [self files])
2551 for (NSString *file in files)
2552 if (application_r(file)) {
2553 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2554 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2555 if ([id isEqualToString:me])
2558 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2560 display = application_r[1];
2562 NSString *bundle([file stringByDeletingLastPathComponent]);
2563 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2564 if (icon == nil || [icon length] == 0)
2566 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2568 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2569 [applications addObject:application];
2571 [application addObject:id];
2572 [application addObject:display];
2573 [application addObject:url];
2576 return [applications count] == 0 ? nil : applications;
2579 - (Source *) source {
2581 @synchronized (database_) {
2582 if ([database_ era] != era_ || file_.end())
2585 source_ = [database_ getSource:file_.File()];
2597 - (NSString *) role {
2601 - (BOOL) matches:(NSString *)text {
2607 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2608 if (range.location != NSNotFound)
2611 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2612 if (range.location != NSNotFound)
2615 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2616 if (range.location != NSNotFound)
2622 - (bool) hasSupportingRole {
2625 if ([role_ isEqualToString:@"enduser"])
2627 if ([Role_ isEqualToString:@"User"])
2629 if ([role_ isEqualToString:@"hacker"])
2631 if ([Role_ isEqualToString:@"Hacker"])
2633 if ([role_ isEqualToString:@"developer"])
2635 if ([Role_ isEqualToString:@"Developer"])
2640 - (BOOL) hasTag:(NSString *)tag {
2641 return tags_ == nil ? NO : [tags_ containsObject:tag];
2644 - (NSString *) primaryPurpose {
2645 for (NSString *tag in tags_)
2646 if ([tag hasPrefix:@"purpose::"])
2647 return [tag substringFromIndex:9];
2651 - (NSArray *) purposes {
2652 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2653 for (NSString *tag in tags_)
2654 if ([tag hasPrefix:@"purpose::"])
2655 [purposes addObject:[tag substringFromIndex:9]];
2656 return [purposes count] == 0 ? nil : purposes;
2659 - (bool) isCommercial {
2660 return [self hasTag:@"cydia::commercial"];
2663 - (CYString &) cyname {
2664 return name_.empty() ? id_ : name_;
2667 - (uint32_t) compareBySection:(NSArray *)sections {
2668 NSString *section([self section]);
2669 for (size_t i(0), e([sections count]); i != e; ++i) {
2670 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2674 return _not(uint32_t);
2677 - (uint32_t) compareForChanges {
2682 uint32_t timestamp : 30;
2683 uint32_t ignored : 1;
2684 uint32_t upgradable : 1;
2688 bool upgradable([self upgradableAndEssential:YES]);
2689 value.bits.upgradable = upgradable ? 1 : 0;
2692 value.bits.timestamp = 0;
2693 value.bits.ignored = [self ignored] ? 0 : 1;
2694 value.bits.upgradable = 1;
2696 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2697 value.bits.ignored = 0;
2698 value.bits.upgradable = 0;
2701 return _not(uint32_t) - value.key;
2705 pkgProblemResolver *resolver = [database_ resolver];
2706 resolver->Clear(iterator_);
2707 resolver->Protect(iterator_);
2711 pkgProblemResolver *resolver = [database_ resolver];
2712 resolver->Clear(iterator_);
2713 resolver->Protect(iterator_);
2714 pkgCacheFile &cache([database_ cache]);
2715 cache->MarkInstall(iterator_, false);
2716 pkgDepCache::StateCache &state((*cache)[iterator_]);
2717 if (!state.Install())
2718 cache->SetReInstall(iterator_, true);
2722 pkgProblemResolver *resolver = [database_ resolver];
2723 resolver->Clear(iterator_);
2724 resolver->Protect(iterator_);
2725 resolver->Remove(iterator_);
2726 [database_ cache]->MarkDelete(iterator_, true);
2729 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2730 _profile(Package$isUnfilteredAndSearchedForBy)
2733 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2734 value &= [self unfiltered];
2737 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2738 value &= [self matches:search];
2745 - (bool) isInstalledAndVisible:(NSNumber *)number {
2746 return (![number boolValue] || [self visible]) && ![self uninstalled];
2749 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2750 NSString *section = [self section];
2754 [self uninstalled] && (
2756 section == nil && [name length] == 0 ||
2757 [name isEqualToString:section]
2761 - (bool) isVisibleInSource:(Source *)source {
2762 return [self source] == source && [self visible];
2767 /* Section Class {{{ */
2768 @interface Section : NSObject {
2773 NSString *localized_;
2776 - (NSComparisonResult) compareByLocalized:(Section *)section;
2777 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2778 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2779 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2780 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2781 - (NSString *) name;
2788 - (void) addToCount;
2790 - (void) setCount:(size_t)count;
2791 - (NSString *) localized;
2795 @implementation Section
2799 if (localized_ != nil)
2800 [localized_ release];
2804 - (NSComparisonResult) compareByLocalized:(Section *)section {
2805 NSString *lhs(localized_);
2806 NSString *rhs([section localized]);
2808 /*if ([lhs length] != 0 && [rhs length] != 0) {
2809 unichar lhc = [lhs characterAtIndex:0];
2810 unichar rhc = [rhs characterAtIndex:0];
2812 if (isalpha(lhc) && !isalpha(rhc))
2813 return NSOrderedAscending;
2814 else if (!isalpha(lhc) && isalpha(rhc))
2815 return NSOrderedDescending;
2818 return [lhs compare:rhs options:LaxCompareOptions_];
2821 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2822 if ((self = [self initWithName:name localize:NO]) != nil) {
2823 if (localized != nil)
2824 localized_ = [localized retain];
2828 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2829 return [self initWithName:name row:0 localize:localize];
2832 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2833 if ((self = [super init]) != nil) {
2834 name_ = [name retain];
2838 localized_ = [LocalizeSection(name_) retain];
2842 /* XXX: localize the index thingees */
2843 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2844 if ((self = [super init]) != nil) {
2845 name_ = [(index == '#' ? @"123" : [NSString stringWithCharacters:&index length:1]) retain];
2851 - (NSString *) name {
2871 - (void) addToCount {
2875 - (void) setCount:(size_t)count {
2879 - (NSString *) localized {
2887 static NSArray *Finishes_;
2889 /* Database Implementation {{{ */
2890 @implementation Database
2892 + (Database *) sharedInstance {
2893 static Database *instance;
2894 if (instance == nil)
2895 instance = [[Database alloc] init];
2905 NSRecycleZone(zone_);
2906 // XXX: malloc_destroy_zone(zone_);
2907 apr_pool_destroy(pool_);
2911 - (void) _readCydia:(NSNumber *)fd { _pooled
2912 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2913 std::istream is(&ib);
2916 static Pcre finish_r("^finish:([^:]*)$");
2918 while (std::getline(is, line)) {
2919 const char *data(line.c_str());
2920 size_t size = line.size();
2921 lprintf("C:%s\n", data);
2923 if (finish_r(data, size)) {
2924 NSString *finish = finish_r[1];
2925 int index = [Finishes_ indexOfObject:finish];
2926 if (index != INT_MAX && index > Finish_)
2934 - (void) _readStatus:(NSNumber *)fd { _pooled
2935 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2936 std::istream is(&ib);
2939 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2940 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2942 while (std::getline(is, line)) {
2943 const char *data(line.c_str());
2944 size_t size = line.size();
2945 lprintf("S:%s\n", data);
2947 if (conffile_r(data, size)) {
2948 [delegate_ setConfigurationData:conffile_r[1]];
2949 } else if (strncmp(data, "status: ", 8) == 0) {
2950 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2951 [delegate_ setProgressTitle:string];
2952 } else if (pmstatus_r(data, size)) {
2953 std::string type([pmstatus_r[1] UTF8String]);
2954 NSString *id = pmstatus_r[2];
2956 float percent([pmstatus_r[3] floatValue]);
2957 [delegate_ setProgressPercent:(percent / 100)];
2959 NSString *string = pmstatus_r[4];
2961 if (type == "pmerror")
2962 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2963 withObject:[NSArray arrayWithObjects:string, id, nil]
2966 else if (type == "pmstatus") {
2967 [delegate_ setProgressTitle:string];
2968 } else if (type == "pmconffile")
2969 [delegate_ setConfigurationData:string];
2970 else _assert(false);
2971 } else _assert(false);
2977 - (void) _readOutput:(NSNumber *)fd { _pooled
2978 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2979 std::istream is(&ib);
2982 while (std::getline(is, line)) {
2983 lprintf("O:%s\n", line.c_str());
2984 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2994 - (Package *) packageWithName:(NSString *)name {
2995 if (static_cast<pkgDepCache *>(cache_) == NULL)
2997 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
2998 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3001 - (Database *) init {
3002 if ((self = [super init]) != nil) {
3009 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3010 apr_pool_create(&pool_, NULL);
3012 packages_ = [[NSMutableArray alloc] init];
3016 _assert(pipe(fds) != -1);
3019 _config->Set("APT::Keep-Fds::", cydiafd_);
3020 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3023 detachNewThreadSelector:@selector(_readCydia:)
3025 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3028 _assert(pipe(fds) != -1);
3032 detachNewThreadSelector:@selector(_readStatus:)
3034 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3037 _assert(pipe(fds) != -1);
3038 _assert(dup2(fds[0], 0) != -1);
3039 _assert(close(fds[0]) != -1);
3041 input_ = fdopen(fds[1], "a");
3043 _assert(pipe(fds) != -1);
3044 _assert(dup2(fds[1], 1) != -1);
3045 _assert(close(fds[1]) != -1);
3048 detachNewThreadSelector:@selector(_readOutput:)
3050 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3055 - (pkgCacheFile &) cache {
3059 - (pkgDepCache::Policy *) policy {
3063 - (pkgRecords *) records {
3067 - (pkgProblemResolver *) resolver {
3071 - (pkgAcquire &) fetcher {
3075 - (pkgSourceList &) list {
3079 - (NSArray *) packages {
3083 - (NSArray *) sources {
3084 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3085 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3086 [sources addObject:i->second];
3090 - (NSArray *) issues {
3091 if (cache_->BrokenCount() == 0)
3094 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3096 for (Package *package in packages_) {
3097 if (![package broken])
3099 pkgCache::PkgIterator pkg([package iterator]);
3101 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3102 [entry addObject:[package name]];
3103 [issues addObject:entry];
3105 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3109 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3110 pkgCache::DepIterator start;
3111 pkgCache::DepIterator end;
3112 dep.GlobOr(start, end); // ++dep
3114 if (!cache_->IsImportantDep(end))
3116 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3119 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3120 [entry addObject:failure];
3121 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3123 Package *package([self packageWithName:[NSString stringWithUTF8String:start.TargetPkg().Name()]]);
3124 [failure addObject:[package name]];
3126 pkgCache::PkgIterator target(start.TargetPkg());
3127 if (target->ProvidesList != 0)
3128 [failure addObject:@"?"];
3130 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3132 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3133 else if (!cache_[target].CandidateVerIter(cache_).end())
3134 [failure addObject:@"-"];
3135 else if (target->ProvidesList == 0)
3136 [failure addObject:@"!"];
3138 [failure addObject:@"%"];
3142 if (start.TargetVer() != 0)
3143 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3154 - (void) reloadData { _pooled
3155 @synchronized (self) {
3159 [packages_ removeAllObjects];
3185 apr_pool_clear(pool_);
3186 NSRecycleZone(zone_);
3188 int chk(creat("/tmp/cydia.chk", 0644));
3193 if (!cache_.Open(progress_, true)) {
3195 if (!_error->PopMessage(error))
3198 lprintf("cache_.Open():[%s]\n", error.c_str());
3200 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3201 [delegate_ repairWithSelector:@selector(configure)];
3202 else if (error == "The package lists or status file could not be parsed or opened.")
3203 [delegate_ repairWithSelector:@selector(update)];
3204 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3205 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3206 // else if (error == "The list of sources could not be read.")
3207 else _assert(false);
3213 unlink("/tmp/cydia.chk");
3215 now_ = [[NSDate date] retain];
3217 policy_ = new pkgDepCache::Policy();
3218 records_ = new pkgRecords(cache_);
3219 resolver_ = new pkgProblemResolver(cache_);
3220 fetcher_ = new pkgAcquire(&status_);
3223 list_ = new pkgSourceList();
3224 _assert(list_->ReadMainList());
3226 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3227 _assert(pkgApplyStatus(cache_));
3229 if (cache_->BrokenCount() != 0) {
3230 _assert(pkgFixBroken(cache_));
3231 _assert(cache_->BrokenCount() == 0);
3232 _assert(pkgMinimizeUpgrade(cache_));
3237 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3238 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3239 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3240 // XXX: this could be more intelligent
3241 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3242 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3244 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3251 /*std::vector<Package *> packages;
3252 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3253 [packages_ release];
3258 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3259 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3260 //packages.push_back(package);
3261 [packages_ addObject:package];
3265 /*if (packages.empty())
3266 packages_ = [[NSArray alloc] init];
3268 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3271 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3272 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3273 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3281 /*if (!packages.empty())
3282 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3283 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3285 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3287 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3289 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3295 - (void) configure {
3296 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3297 system([dpkg UTF8String]);
3305 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3306 _assert(!_error->PendingError());
3309 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3312 public pkgArchiveCleaner
3315 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3320 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3322 while (_error->PopMessage(error))
3323 lprintf("ArchiveCleaner: %s\n", error.c_str());
3328 pkgRecords records(cache_);
3330 lock_ = new FileFd();
3331 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3332 _assert(!_error->PendingError());
3335 // XXX: explain this with an error message
3336 _assert(list.ReadMainList());
3338 manager_ = (_system->CreatePM(cache_));
3339 _assert(manager_->GetArchives(fetcher_, &list, &records));
3340 _assert(!_error->PendingError());
3344 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3346 _assert(list.ReadMainList());
3347 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3348 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3351 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3356 bool failed = false;
3357 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3358 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3360 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3363 std::string uri = (*item)->DescURI();
3364 std::string error = (*item)->ErrorText;
3366 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3369 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3370 withObject:[NSArray arrayWithObjects:
3371 [NSString stringWithUTF8String:error.c_str()],
3383 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3385 if (_error->PendingError()) {
3390 if (result == pkgPackageManager::Failed) {
3395 if (result != pkgPackageManager::Completed) {
3400 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3402 _assert(list.ReadMainList());
3403 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3404 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3407 if (![before isEqualToArray:after])
3412 _assert(pkgDistUpgrade(cache_));
3416 [self updateWithStatus:status_];
3419 - (NSString *) updateWithStatus:(Status &)status {
3421 _assert(list.ReadMainList());
3424 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3426 if (_error->PendingError()) {
3428 if (!_error->PopMessage(error))
3431 return [NSString stringWithUTF8String:error.c_str()];
3434 pkgAcquire fetcher(&status);
3435 _assert(list.GetIndexes(&fetcher));
3437 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3438 bool failed = false;
3439 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3440 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3441 (*item)->Finished();
3445 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3446 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3447 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3450 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3457 - (void) setDelegate:(id)delegate {
3458 delegate_ = delegate;
3459 status_.setDelegate(delegate);
3460 progress_.setDelegate(delegate);
3463 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3464 SourceMap::const_iterator i(sources_.find(file->ID));
3465 return i == sources_.end() ? nil : i->second;
3471 /* PopUp Windows {{{ */
3472 @interface PopUpView : UIView {
3473 _transient id delegate_;
3474 UITransitionView *transition_;
3479 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3483 @implementation PopUpView
3486 [transition_ setDelegate:nil];
3487 [transition_ release];
3493 [transition_ transition:UITransitionPushFromTop toView:nil];
3496 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3497 if (from != nil && to == nil)
3498 [self removeFromSuperview];
3501 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3502 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3503 delegate_ = delegate;
3505 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3506 [self addSubview:transition_];
3508 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3510 [view addSubview:self];
3512 [transition_ setDelegate:self];
3514 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3515 [transition_ transition:UITransitionNone toView:blank];
3516 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3524 /* Mail Composition {{{ */
3525 @interface MailToView : PopUpView {
3526 MailComposeController *controller_;
3529 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
3533 @implementation MailToView
3536 [controller_ release];
3540 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
3544 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
3545 NSLog(@"did:%@", delivery);
3546 // [UIApp setStatusBarShowsProgress:NO];
3547 if ([controller error]){
3548 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3549 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3550 [mailAlertSheet setBodyText:[controller error]];
3551 [mailAlertSheet popupAlertAnimated:YES];
3555 - (void) showError {
3556 NSLog(@"%@", [controller_ error]);
3557 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3558 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3559 [mailAlertSheet setBodyText:[controller_ error]];
3560 [mailAlertSheet popupAlertAnimated:YES];
3563 - (void) deliverMessage { _pooled
3567 if (![controller_ deliverMessage])
3568 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
3571 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
3572 if ([controller_ needsDelivery])
3573 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
3578 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
3579 if ((self = [super initWithView:view delegate:delegate]) != nil) {
3580 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
3581 [controller_ setDelegate:self];
3582 [controller_ initializeUI];
3583 [controller_ setupForURL:url];
3585 UIView *view([controller_ view]);
3586 [overlay_ addSubview:view];
3594 /* Confirmation View {{{ */
3595 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3596 if (!iterator.end())
3597 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3598 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3600 pkgCache::PkgIterator package(dep.TargetPkg());
3603 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3610 @protocol ConfirmationViewDelegate
3616 @interface ConfirmationView : BrowserView {
3617 _transient Database *database_;
3618 UIActionSheet *essential_;
3625 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3629 @implementation ConfirmationView
3636 if (essential_ != nil)
3637 [essential_ release];
3643 [book_ popFromSuperviewAnimated:YES];
3646 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3647 NSString *context([sheet context]);
3649 if ([context isEqualToString:@"remove"]) {
3657 [delegate_ confirm];
3664 } else if ([context isEqualToString:@"unable"]) {
3668 [super alertSheet:sheet buttonClicked:button];
3671 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3672 [super webView:sender didClearWindowObject:window forFrame:frame];
3673 [window setValue:changes_ forKey:@"changes"];
3674 [window setValue:issues_ forKey:@"issues"];
3675 [window setValue:sizes_ forKey:@"sizes"];
3678 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3679 if ((self = [super initWithBook:book]) != nil) {
3680 database_ = database;
3682 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3683 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3684 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3685 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3686 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3690 pkgDepCache::Policy *policy([database_ policy]);
3692 pkgCacheFile &cache([database_ cache]);
3693 NSArray *packages = [database_ packages];
3694 for (Package *package in packages) {
3695 pkgCache::PkgIterator iterator = [package iterator];
3696 pkgDepCache::StateCache &state(cache[iterator]);
3698 NSString *name([package name]);
3700 if (state.NewInstall())
3701 [installing addObject:name];
3702 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3703 [reinstalling addObject:name];
3704 else if (state.Upgrade())
3705 [upgrading addObject:name];
3706 else if (state.Downgrade())
3707 [downgrading addObject:name];
3708 else if (state.Delete()) {
3709 if ([package essential])
3711 [removing addObject:name];
3714 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3715 substrate_ |= DepSubstrate(iterator.CurrentVer());
3720 else if (Advanced_ || true) {
3721 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
3723 essential_ = [[UIActionSheet alloc]
3724 initWithTitle:CYLocalize("REMOVING_ESSENTIALS")
3725 buttons:[NSArray arrayWithObjects:
3726 [NSString stringWithFormat:parenthetical, CYLocalize("CANCEL_OPERATION"), CYLocalize("SAFE")],
3727 [NSString stringWithFormat:parenthetical, CYLocalize("FORCE_REMOVAL"), CYLocalize("UNSAFE")],
3729 defaultButtonIndex:0
3735 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3737 [essential_ setBodyText:CYLocalize("REMOVING_ESSENTIALS_EX")];
3739 essential_ = [[UIActionSheet alloc]
3740 initWithTitle:CYLocalize("UNABLE_TO_COMPLY")
3741 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3742 defaultButtonIndex:0
3747 [essential_ setBodyText:CYLocalize("UNABLE_TO_COMPLY_EX")];
3750 changes_ = [[NSArray alloc] initWithObjects:
3758 issues_ = [database_ issues];
3760 issues_ = [issues_ retain];
3762 sizes_ = [[NSArray alloc] initWithObjects:
3763 SizeString([database_ fetcher].FetchNeeded()),
3764 SizeString([database_ fetcher].PartialPresent()),
3765 SizeString([database_ cache]->UsrSize()),
3768 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3772 - (NSString *) backButtonTitle {
3773 return CYLocalize("CONFIRM");
3776 - (NSString *) leftButtonTitle {
3777 return [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("CANCEL"), CYLocalize("QUEUE")];
3780 - (id) rightButtonTitle {
3781 return issues_ != nil ? nil : [super rightButtonTitle];
3784 - (id) _rightButtonTitle {
3785 #if AlwaysReload || IgnoreInstall
3786 return [super _rightButtonTitle];
3788 return CYLocalize("CONFIRM");
3792 - (void) _leftButtonClicked {
3797 - (void) _rightButtonClicked {
3799 return [super _rightButtonClicked];
3801 if (essential_ != nil)
3802 [essential_ popupAlertAnimated:YES];
3806 [delegate_ confirm];
3814 /* Progress Data {{{ */
3815 @interface ProgressData : NSObject {
3821 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3828 @implementation ProgressData
3830 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3831 if ((self = [super init]) != nil) {
3832 selector_ = selector;
3852 /* Progress View {{{ */
3853 @interface ProgressView : UIView <
3854 ConfigurationDelegate,
3857 _transient Database *database_;
3859 UIView *background_;
3860 UITransitionView *transition_;
3862 UINavigationBar *navbar_;
3863 UIProgressBar *progress_;
3864 UITextView *output_;
3865 UITextLabel *status_;
3866 UIPushButton *close_;
3869 SHA1SumValue springlist_;
3870 SHA1SumValue notifyconf_;
3871 SHA1SumValue sandplate_;
3874 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
3876 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
3877 - (void) setContentView:(UIView *)view;
3880 - (void) _retachThread;
3881 - (void) _detachNewThreadData:(ProgressData *)data;
3882 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
3888 @protocol ProgressViewDelegate
3889 - (void) progressViewIsComplete:(ProgressView *)sender;
3892 @implementation ProgressView
3895 [transition_ setDelegate:nil];
3896 [navbar_ setDelegate:nil];
3899 if (background_ != nil)
3900 [background_ release];
3901 [transition_ release];
3904 [progress_ release];
3911 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3912 if (bootstrap_ && from == overlay_ && to == view_)
3916 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
3917 if ((self = [super initWithFrame:frame]) != nil) {
3918 database_ = database;
3919 delegate_ = delegate;
3921 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3922 [transition_ setDelegate:self];
3924 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3927 [overlay_ setBackgroundColor:[UIColor blackColor]];
3929 background_ = [[UIView alloc] initWithFrame:[self bounds]];
3930 [background_ setBackgroundColor:[UIColor blackColor]];
3931 [self addSubview:background_];
3934 [self addSubview:transition_];
3936 CGSize navsize = [UINavigationBar defaultSize];
3937 CGRect navrect = {{0, 0}, navsize};
3939 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
3940 [overlay_ addSubview:navbar_];
3942 [navbar_ setBarStyle:1];
3943 [navbar_ setDelegate:self];
3945 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
3946 [navbar_ pushNavigationItem:navitem];
3948 CGRect bounds = [overlay_ bounds];
3949 CGSize prgsize = [UIProgressBar defaultSize];
3952 (bounds.size.width - prgsize.width) / 2,
3953 bounds.size.height - prgsize.height - 20
3956 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3957 [progress_ setStyle:0];
3959 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3961 bounds.size.height - prgsize.height - 50,
3962 bounds.size.width - 20,
3966 [status_ setColor:[UIColor whiteColor]];
3967 [status_ setBackgroundColor:[UIColor clearColor]];
3969 [status_ setCentersHorizontally:YES];
3970 //[status_ setFont:font];
3973 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3975 navrect.size.height + 20,
3976 bounds.size.width - 20,
3977 bounds.size.height - navsize.height - 62 - navrect.size.height
3981 //[output_ setTextFont:@"Courier New"];
3982 [output_ setTextSize:12];
3984 [output_ setTextColor:[UIColor whiteColor]];
3985 [output_ setBackgroundColor:[UIColor clearColor]];
3987 [output_ setMarginTop:0];
3988 [output_ setAllowsRubberBanding:YES];
3989 [output_ setEditable:NO];
3991 [overlay_ addSubview:output_];
3993 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3995 bounds.size.height - prgsize.height - 50,
3996 bounds.size.width - 20,
4000 [close_ setAutosizesToFit:NO];
4001 [close_ setDrawsShadow:YES];
4002 [close_ setStretchBackground:YES];
4003 [close_ setEnabled:YES];
4005 UIFont *bold = [UIFont boldSystemFontOfSize:22];
4006 [close_ setTitleFont:bold];
4008 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
4009 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4010 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4014 - (void) setContentView:(UIView *)view {
4015 view_ = [view retain];
4018 - (void) resetView {
4019 [transition_ transition:6 toView:view_];
4022 - (void) _checkError {
4023 if (_error->PendingError()) {
4025 if (!_error->PopMessage(error))
4028 UIActionSheet *sheet = [[[UIActionSheet alloc]
4029 initWithTitle:CYLocalize("ERROR")
4030 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
4031 defaultButtonIndex:0
4036 [sheet setBodyText:[NSString stringWithUTF8String:error.c_str()]];
4037 [sheet popupAlertAnimated:YES];
4042 [delegate_ progressViewIsComplete:self];
4046 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4049 MMap mmap(file, MMap::ReadOnly);
4051 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4052 if (!(notifyconf_ == sha1.Result()))
4059 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4062 MMap mmap(file, MMap::ReadOnly);
4064 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4065 if (!(springlist_ == sha1.Result()))
4071 case 0: [close_ setTitle:CYLocalize("RETURN_TO_CYDIA")]; break;
4072 case 1: [close_ setTitle:CYLocalize("CLOSE_CYDIA")]; break;
4073 case 2: [close_ setTitle:CYLocalize("RESTART_SPRINGBOARD")]; break;
4074 case 3: [close_ setTitle:CYLocalize("RELOAD_SPRINGBOARD")]; break;
4075 case 4: [close_ setTitle:CYLocalize("REBOOT_DEVICE")]; break;
4078 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4080 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
4081 [cache autorelease];
4083 NSFileManager *manager = [NSFileManager defaultManager];
4084 NSError *error = nil;
4086 id system = [cache objectForKey:@"System"];
4091 if (stat(Cache_, &info) == -1)
4094 [system removeAllObjects];
4096 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4097 for (NSString *app in apps)
4098 if ([app hasSuffix:@".app"]) {
4099 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4100 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4101 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4103 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4104 [info setObject:path forKey:@"Path"];
4105 [info setObject:@"System" forKey:@"ApplicationType"];
4106 [system addInfoDictionary:info];
4112 [cache writeToFile:@Cache_ atomically:YES];
4114 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
4116 if (chmod(Cache_, info.st_mode) == -1)
4120 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4123 notify_post("com.apple.mobile.application_installed");
4125 [delegate_ setStatusBarShowsProgress:NO];
4128 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4129 NSString *context([sheet context]);
4131 if ([context isEqualToString:@"error"])
4133 else if ([context isEqualToString:@"_error"]) {
4136 } else if ([context isEqualToString:@"conffile"]) {
4137 FILE *input = [database_ input];
4141 fprintf(input, "N\n");
4145 fprintf(input, "Y\n");
4156 - (void) closeButtonPushed {
4165 [delegate_ suspendWithAnimation:YES];
4169 system("launchctl stop com.apple.SpringBoard");
4173 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4182 - (void) _retachThread {
4183 UINavigationItem *item = [navbar_ topItem];
4184 [item setTitle:CYLocalize("COMPLETE")];
4186 [overlay_ addSubview:close_];
4187 [progress_ removeFromSuperview];
4188 [status_ removeFromSuperview];
4193 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4194 [[data target] performSelector:[data selector] withObject:[data object]];
4197 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4200 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4201 UINavigationItem *item = [navbar_ topItem];
4202 [item setTitle:title];
4204 [status_ setText:nil];
4205 [output_ setText:@""];
4206 [progress_ setProgress:0];
4208 [close_ removeFromSuperview];
4209 [overlay_ addSubview:progress_];
4210 [overlay_ addSubview:status_];
4212 [delegate_ setStatusBarShowsProgress:YES];
4217 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4220 MMap mmap(file, MMap::ReadOnly);
4222 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4223 notifyconf_ = sha1.Result();
4229 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4232 MMap mmap(file, MMap::ReadOnly);
4234 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4235 springlist_ = sha1.Result();
4239 [transition_ transition:6 toView:overlay_];
4242 detachNewThreadSelector:@selector(_detachNewThreadData:)
4244 withObject:[[ProgressData alloc]
4245 initWithSelector:selector
4252 - (void) repairWithSelector:(SEL)selector {
4254 detachNewThreadSelector:selector
4257 title:CYLocalize("REPAIRING")
4261 - (void) setConfigurationData:(NSString *)data {
4263 performSelectorOnMainThread:@selector(_setConfigurationData:)
4269 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4270 Package *package = id == nil ? nil : [database_ packageWithName:id];
4272 UIActionSheet *sheet = [[[UIActionSheet alloc]
4273 initWithTitle:(package == nil ? id : [package name])
4274 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
4275 defaultButtonIndex:0
4280 [sheet setBodyText:error];
4281 [sheet popupAlertAnimated:YES];
4284 - (void) setProgressTitle:(NSString *)title {
4286 performSelectorOnMainThread:@selector(_setProgressTitle:)
4292 - (void) setProgressPercent:(float)percent {
4294 performSelectorOnMainThread:@selector(_setProgressPercent:)
4295 withObject:[NSNumber numberWithFloat:percent]
4300 - (void) startProgress {
4303 - (void) addProgressOutput:(NSString *)output {
4305 performSelectorOnMainThread:@selector(_addProgressOutput:)
4311 - (bool) isCancelling:(size_t)received {
4315 - (void) _setConfigurationData:(NSString *)data {
4316 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4318 _assert(conffile_r(data));
4320 NSString *ofile = conffile_r[1];
4321 //NSString *nfile = conffile_r[2];
4323 UIActionSheet *sheet = [[[UIActionSheet alloc]
4324 initWithTitle:CYLocalize("CONFIGURATION_UPGRADE")
4325 buttons:[NSArray arrayWithObjects:
4326 CYLocalize("KEEP_OLD_COPY"),
4327 CYLocalize("ACCEPT_NEW_COPY"),
4328 // XXX: CYLocalize("SEE_WHAT_CHANGED"),
4330 defaultButtonIndex:0
4335 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", CYLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4336 [sheet popupAlertAnimated:YES];
4339 - (void) _setProgressTitle:(NSString *)title {
4340 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4341 for (size_t i(0), e([words count]); i != e; ++i) {
4342 NSString *word([words objectAtIndex:i]);
4343 if (Package *package = [database_ packageWithName:word])
4344 [words replaceObjectAtIndex:i withObject:[package name]];
4347 [status_ setText:[words componentsJoinedByString:@" "]];
4350 - (void) _setProgressPercent:(NSNumber *)percent {
4351 [progress_ setProgress:[percent floatValue]];
4354 - (void) _addProgressOutput:(NSString *)output {
4355 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4356 CGSize size = [output_ contentSize];
4357 CGRect rect = {{0, size.height}, {size.width, 0}};
4358 [output_ scrollRectToVisible:rect animated:YES];
4361 - (BOOL) isRunning {
4368 /* Package Cell {{{ */
4369 @interface PackageCell : UITableCell {
4372 NSString *description_;
4379 UITextLabel *status_;
4383 - (PackageCell *) init;
4384 - (void) setPackage:(Package *)package;
4386 + (int) heightForPackage:(Package *)package;
4390 @implementation PackageCell
4392 - (void) clearPackage {
4403 if (description_ != nil) {
4404 [description_ release];
4408 if (source_ != nil) {
4413 if (badge_ != nil) {
4423 [self clearPackage];
4430 - (PackageCell *) init {
4431 if ((self = [super init]) != nil) {
4433 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4434 [status_ setBackgroundColor:[UIColor clearColor]];
4435 [status_ setFont:small];
4440 - (void) setPackage:(Package *)package {
4441 [self clearPackage];
4444 Source *source = [package source];
4446 icon_ = [[package icon] retain];
4447 name_ = [[package name] retain];
4448 description_ = [[package shortDescription] retain];
4449 commercial_ = [package isCommercial];
4451 package_ = [package retain];
4453 NSString *label = nil;
4454 bool trusted = false;
4456 if (source != nil) {
4457 label = [source label];
4458 trusted = [source trusted];
4459 } else if ([[package id] isEqualToString:@"firmware"])
4460 label = CYLocalize("APPLE");
4462 label = [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("UNKNOWN"), CYLocalize("LOCAL")];
4464 NSString *from(label);
4466 NSString *section = [package simpleSection];
4467 if (section != nil && ![section isEqualToString:label]) {
4468 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4469 from = [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), from, section];
4472 from = [NSString stringWithFormat:CYLocalize("FROM"), from];
4473 source_ = [from retain];
4475 if (NSString *purpose = [package primaryPurpose])
4476 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4477 badge_ = [badge_ retain];
4480 if (NSString *mode = [package mode]) {
4481 [badge_ setImage:[UIImage applicationImageNamed:
4482 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4485 [status_ setText:[NSString stringWithFormat:CYLocalize("QUEUED_FOR"), CYLocalize(mode)]];
4486 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4487 } else if ([package half]) {
4488 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4489 [status_ setText:CYLocalize("PACKAGE_DAMAGED")];
4490 [status_ setColor:[UIColor redColor]];
4492 [badge_ setImage:nil];
4493 [status_ setText:nil];
4500 - (void) drawRect:(CGRect)rect {
4504 if (NSString *mode = [package_ mode]) {
4505 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4506 color = remove ? RemovingColor_ : InstallingColor_;
4508 color = [UIColor whiteColor];
4510 [self setBackgroundColor:color];
4514 [super drawRect:rect];
4517 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4519 CGContextRef context(UIGraphicsGetCurrentContext());
4520 [[self backgroundColor] set];
4522 back.size.height -= 1;
4523 CGContextFillRect(context, back);
4526 [super drawBackgroundInRect:rect withFade:fade];
4529 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4532 rect.size = [icon_ size];
4534 rect.size.width /= 2;
4535 rect.size.height /= 2;
4537 rect.origin.x = 25 - rect.size.width / 2;
4538 rect.origin.y = 25 - rect.size.height / 2;
4540 [icon_ drawInRect:rect];
4543 if (badge_ != nil) {
4544 CGSize size = [badge_ size];
4546 [badge_ drawAtPoint:CGPointMake(
4547 36 - size.width / 2,
4548 36 - size.height / 2
4556 UISetColor(commercial_ ? Purple_ : Black_);
4557 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4558 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4561 UISetColor(commercial_ ? Purplish_ : Gray_);
4562 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4564 [super drawContentInRect:rect selected:selected];
4567 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4569 [super setSelected:selected withFade:fade];
4572 + (int) heightForPackage:(Package *)package {
4578 /* Section Cell {{{ */
4579 @interface SectionCell : UISimpleTableCell {
4584 _UISwitchSlider *switch_;
4589 - (void) setSection:(Section *)section editing:(BOOL)editing;
4593 @implementation SectionCell
4595 - (void) clearSection {
4596 if (section_ != nil) {
4606 if (count_ != nil) {
4613 [self clearSection];
4620 if ((self = [super init]) != nil) {
4621 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4623 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4624 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4628 - (void) onSwitch:(id)sender {
4629 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4630 if (metadata == nil) {
4631 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4632 [Sections_ setObject:metadata forKey:section_];
4636 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4639 - (void) setSection:(Section *)section editing:(BOOL)editing {
4640 if (editing != editing_) {
4642 [switch_ removeFromSuperview];
4644 [self addSubview:switch_];
4648 [self clearSection];
4650 if (section == nil) {
4651 name_ = [CYLocalize("ALL_PACKAGES") retain];
4654 section_ = [section localized];
4655 if (section_ != nil)
4656 section_ = [section_ retain];
4657 name_ = [(section_ == nil || [section_ length] == 0 ? CYLocalize("NO_SECTION") : section_) retain];
4658 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4661 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4665 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4666 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4673 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4675 CGSize size = [count_ sizeWithFont:Font14_];
4679 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4681 [super drawContentInRect:rect selected:selected];
4687 /* File Table {{{ */
4688 @interface FileTable : RVPage {
4689 _transient Database *database_;
4692 NSMutableArray *files_;
4696 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4697 - (void) setPackage:(Package *)package;
4701 @implementation FileTable
4704 if (package_ != nil)
4713 - (int) numberOfRowsInTable:(UITable *)table {
4714 return files_ == nil ? 0 : [files_ count];
4717 - (float) table:(UITable *)table heightForRow:(int)row {
4721 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4722 if (reusing == nil) {
4723 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4724 UIFont *font = [UIFont systemFontOfSize:16];
4725 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4727 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4731 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4735 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4736 if ((self = [super initWithBook:book]) != nil) {
4737 database_ = database;
4739 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4741 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4742 [self addSubview:list_];
4744 UITableColumn *column = [[[UITableColumn alloc]
4745 initWithTitle:CYLocalize("NAME")
4747 width:[self frame].size.width
4750 [list_ setDataSource:self];
4751 [list_ setSeparatorStyle:1];
4752 [list_ addTableColumn:column];
4753 [list_ setDelegate:self];
4754 [list_ setReusesTableCells:YES];
4758 - (void) setPackage:(Package *)package {
4759 if (package_ != nil) {
4760 [package_ autorelease];
4769 [files_ removeAllObjects];
4771 if (package != nil) {
4772 package_ = [package retain];
4773 name_ = [[package id] retain];
4775 if (NSArray *files = [package files])
4776 [files_ addObjectsFromArray:files];
4778 if ([files_ count] != 0) {
4779 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4780 [files_ removeObjectAtIndex:0];
4781 [files_ sortUsingSelector:@selector(compareByPath:)];
4783 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4784 [stack addObject:@"/"];
4786 for (int i(0), e([files_ count]); i != e; ++i) {
4787 NSString *file = [files_ objectAtIndex:i];
4788 while (![file hasPrefix:[stack lastObject]])
4789 [stack removeLastObject];
4790 NSString *directory = [stack lastObject];
4791 [stack addObject:[file stringByAppendingString:@"/"]];
4792 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4793 ([stack count] - 2) * 3, "",
4794 [file substringFromIndex:[directory length]]
4803 - (void) resetViewAnimated:(BOOL)animated {
4804 [list_ resetViewAnimated:animated];
4807 - (void) reloadData {
4808 [self setPackage:[database_ packageWithName:name_]];
4809 [self reloadButtons];
4812 - (NSString *) title {
4813 return CYLocalize("INSTALLED_FILES");
4816 - (NSString *) backButtonTitle {
4817 return CYLocalize("FILES");
4822 /* Package View {{{ */
4823 @interface PackageView : BrowserView {
4824 _transient Database *database_;
4828 NSMutableArray *buttons_;
4831 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4832 - (void) setPackage:(Package *)package;
4836 @implementation PackageView
4839 if (package_ != nil)
4848 if ([self retainCount] == 1)
4849 [delegate_ setPackageView:self];
4853 /* XXX: this is not safe at all... localization of /fail/ */
4854 - (void) _clickButtonWithName:(NSString *)name {
4855 if ([name isEqualToString:CYLocalize("CLEAR")])
4856 [delegate_ clearPackage:package_];
4857 else if ([name isEqualToString:CYLocalize("INSTALL")])
4858 [delegate_ installPackage:package_];
4859 else if ([name isEqualToString:CYLocalize("REINSTALL")])
4860 [delegate_ installPackage:package_];
4861 else if ([name isEqualToString:CYLocalize("REMOVE")])
4862 [delegate_ removePackage:package_];
4863 else if ([name isEqualToString:CYLocalize("UPGRADE")])
4864 [delegate_ installPackage:package_];
4865 else _assert(false);
4868 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4869 NSString *context([sheet context]);
4871 if ([context isEqualToString:@"modify"]) {
4872 int count = [buttons_ count];
4873 _assert(count != 0);
4874 _assert(button <= count + 1);
4876 if (count != button - 1)
4877 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
4881 [super alertSheet:sheet buttonClicked:button];
4884 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
4885 return [super webView:sender didFinishLoadForFrame:frame];
4888 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4889 [super webView:sender didClearWindowObject:window forFrame:frame];
4890 [window setValue:package_ forKey:@"package"];
4893 - (bool) _allowJavaScriptPanel {
4898 - (void) __rightButtonClicked {
4899 int count = [buttons_ count];
4900 _assert(count != 0);
4903 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
4905 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
4906 [buttons addObjectsFromArray:buttons_];
4907 [buttons addObject:CYLocalize("CANCEL")];
4909 [delegate_ slideUp:[[[UIActionSheet alloc]
4912 defaultButtonIndex:([buttons count] - 1)
4919 - (void) _rightButtonClicked {
4921 [super _rightButtonClicked];
4923 [self __rightButtonClicked];
4927 - (id) _rightButtonTitle {
4928 int count = [buttons_ count];
4929 return count == 0 ? nil : count != 1 ? CYLocalize("MODIFY") : [buttons_ objectAtIndex:0];
4932 - (NSString *) backButtonTitle {
4936 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4937 if ((self = [super initWithBook:book]) != nil) {
4938 database_ = database;
4939 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
4940 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
4944 - (void) setPackage:(Package *)package {
4945 if (package_ != nil) {
4946 [package_ autorelease];
4955 [buttons_ removeAllObjects];
4957 if (package != nil) {
4960 package_ = [package retain];
4961 name_ = [[package id] retain];
4962 commercial_ = [package isCommercial];
4964 if ([package_ mode] != nil)
4965 [buttons_ addObject:CYLocalize("CLEAR")];
4966 if ([package_ source] == nil);
4967 else if ([package_ upgradableAndEssential:NO])
4968 [buttons_ addObject:CYLocalize("UPGRADE")];
4969 else if ([package_ uninstalled])
4970 [buttons_ addObject:CYLocalize("INSTALL")];
4972 [buttons_ addObject:CYLocalize("REINSTALL")];
4973 if (![package_ uninstalled])
4974 [buttons_ addObject:CYLocalize("REMOVE")];
4976 if (special_ != NULL) {
4977 CGRect frame([webview_ frame]);
4978 frame.size.width = 320;
4979 frame.size.height = 0;
4980 [webview_ setFrame:frame];
4982 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
4985 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
4987 [self setButtonTitle:nil withStyle:nil toFunction:nil];
4989 [self setFinishHook:nil];
4990 [self setPopupHook:nil];
4993 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
4994 [super callFunction:special_];
4998 [self reloadButtons];
5001 - (bool) isLoading {
5002 return commercial_ ? [super isLoading] : false;
5005 - (void) reloadData {
5006 [self setPackage:[database_ packageWithName:name_]];
5011 /* Package Table {{{ */
5012 @interface PackageTable : RVPage {
5013 _transient Database *database_;
5015 NSMutableArray *packages_;
5016 NSMutableArray *sections_;
5017 UISectionList *list_;
5020 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
5022 - (void) setDelegate:(id)delegate;
5024 - (void) reloadData;
5025 - (void) resetCursor;
5027 - (UISectionList *) list;
5029 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5033 @implementation PackageTable
5036 [list_ setDataSource:nil];
5039 [packages_ release];
5040 [sections_ release];
5045 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5046 return [sections_ count];
5049 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5050 return [[sections_ objectAtIndex:section] name];
5053 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5054 return [[sections_ objectAtIndex:section] row];
5057 - (int) numberOfRowsInTable:(UITable *)table {
5058 return [packages_ count];
5061 - (float) table:(UITable *)table heightForRow:(int)row {
5062 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
5065 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
5067 reusing = [[[PackageCell alloc] init] autorelease];
5068 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
5072 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5076 - (void) tableRowSelected:(NSNotification *)notification {
5077 int row = [[notification object] selectedRow];
5081 Package *package = [packages_ objectAtIndex:row];
5082 package = [database_ packageWithName:[package id]];
5083 PackageView *view([delegate_ packageView]);
5084 [view setPackage:package];
5085 [view setDelegate:delegate_];
5086 [book_ pushPage:view];
5089 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5090 if ((self = [super initWithBook:book]) != nil) {
5091 database_ = database;
5092 title_ = [title retain];
5094 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5095 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5097 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
5098 [list_ setDataSource:self];
5100 UITableColumn *column = [[[UITableColumn alloc]
5101 initWithTitle:CYLocalize("NAME")
5103 width:[self frame].size.width
5106 UITable *table = [list_ table];
5107 [table setSeparatorStyle:1];
5108 [table addTableColumn:column];
5109 [table setDelegate:self];
5110 [table setReusesTableCells:YES];
5112 [self addSubview:list_];
5114 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5115 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5119 - (void) setDelegate:(id)delegate {
5120 delegate_ = delegate;
5123 - (bool) hasPackage:(Package *)package {
5127 - (void) reloadData {
5128 NSArray *packages = [database_ packages];
5130 [packages_ removeAllObjects];
5131 [sections_ removeAllObjects];
5133 _profile(PackageTable$reloadData$Filter)
5134 for (Package *package in packages)
5135 if ([self hasPackage:package])
5136 [packages_ addObject:package];
5139 Section *section = nil;
5141 _profile(PackageTable$reloadData$Section)
5142 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5146 _profile(PackageTable$reloadData$Section$Package)
5147 package = [packages_ objectAtIndex:offset];
5148 index = [package index];
5151 if (section == nil || [section index] != index) {
5152 _profile(PackageTable$reloadData$Section$Allocate)
5153 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5156 _profile(PackageTable$reloadData$Section$Add)
5157 [sections_ addObject:section];
5161 [section addToCount];
5165 _profile(PackageTable$reloadData$List)
5170 - (NSString *) title {
5174 - (void) resetViewAnimated:(BOOL)animated {
5175 [list_ resetViewAnimated:animated];
5178 - (void) resetCursor {
5179 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
5182 - (UISectionList *) list {
5186 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5187 [list_ setShouldHideHeaderInShortLists:hide];
5192 /* Filtered Package Table {{{ */
5193 @interface FilteredPackageTable : PackageTable {
5199 - (void) setObject:(id)object;
5201 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5205 @implementation FilteredPackageTable
5213 - (void) setObject:(id)object {
5219 object_ = [object retain];
5222 - (bool) hasPackage:(Package *)package {
5223 _profile(FilteredPackageTable$hasPackage)
5224 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5228 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5229 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5231 object_ = object == nil ? nil : [object retain];
5233 /* XXX: this is an unsafe optimization of doomy hell */
5234 Method method = class_getInstanceMethod([Package class], filter);
5235 _assert(method != NULL);
5236 imp_ = method_getImplementation(method);
5237 _assert(imp_ != NULL);
5246 /* Add Source View {{{ */
5247 @interface AddSourceView : RVPage {
5248 _transient Database *database_;
5251 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5255 @implementation AddSourceView
5257 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5258 if ((self = [super initWithBook:book]) != nil) {
5259 database_ = database;
5265 /* Source Cell {{{ */
5266 @interface SourceCell : UITableCell {
5269 NSString *description_;
5275 - (SourceCell *) initWithSource:(Source *)source;
5279 @implementation SourceCell
5284 [description_ release];
5289 - (SourceCell *) initWithSource:(Source *)source {
5290 if ((self = [super init]) != nil) {
5292 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5294 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5295 icon_ = [icon_ retain];
5297 origin_ = [[source name] retain];
5298 label_ = [[source uri] retain];
5299 description_ = [[source description] retain];
5303 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5305 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5312 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5316 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5320 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5322 [super drawContentInRect:rect selected:selected];
5327 /* Source Table {{{ */
5328 @interface SourceTable : RVPage {
5329 _transient Database *database_;
5330 UISectionList *list_;
5331 NSMutableArray *sources_;
5332 UIActionSheet *alert_;
5336 UIProgressHUD *hud_;
5339 //NSURLConnection *installer_;
5340 NSURLConnection *trivial_bz2_;
5341 NSURLConnection *trivial_gz_;
5342 //NSURLConnection *automatic_;
5347 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5351 @implementation SourceTable
5353 - (void) _deallocConnection:(NSURLConnection *)connection {
5354 if (connection != nil) {
5355 [connection cancel];
5356 //[connection setDelegate:nil];
5357 [connection release];
5362 [[list_ table] setDelegate:nil];
5363 [list_ setDataSource:nil];
5372 //[self _deallocConnection:installer_];
5373 [self _deallocConnection:trivial_gz_];
5374 [self _deallocConnection:trivial_bz2_];
5375 //[self _deallocConnection:automatic_];
5382 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5383 return offset_ == 0 ? 1 : 2;
5386 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5387 switch (section + (offset_ == 0 ? 1 : 0)) {
5388 case 0: return CYLocalize("ENTERED_BY_USER");
5389 case 1: return CYLocalize("INSTALLED_BY_PACKAGE");
5397 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5398 switch (section + (offset_ == 0 ? 1 : 0)) {
5400 case 1: return offset_;
5408 - (int) numberOfRowsInTable:(UITable *)table {
5409 return [sources_ count];
5412 - (float) table:(UITable *)table heightForRow:(int)row {
5413 Source *source = [sources_ objectAtIndex:row];
5414 return [source description] == nil ? 56 : 73;
5417 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5418 Source *source = [sources_ objectAtIndex:row];
5419 // XXX: weird warning, stupid selectors ;P
5420 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5423 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5427 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5431 - (void) tableRowSelected:(NSNotification*)notification {
5432 UITable *table([list_ table]);
5433 int row([table selectedRow]);
5437 Source *source = [sources_ objectAtIndex:row];
5439 PackageTable *packages = [[[FilteredPackageTable alloc]
5442 title:[source label]
5443 filter:@selector(isVisibleInSource:)
5447 [packages setDelegate:delegate_];
5449 [book_ pushPage:packages];
5452 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5453 Source *source = [sources_ objectAtIndex:row];
5454 return [source record] != nil;
5457 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5458 [[list_ table] setDeleteConfirmationRow:row];
5461 - (void) table:(UITable *)table deleteRow:(int)row {
5462 Source *source = [sources_ objectAtIndex:row];
5463 [Sources_ removeObjectForKey:[source key]];
5464 [delegate_ syncData];
5468 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5471 @"./", @"Distribution",
5472 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5474 [delegate_ syncData];
5477 - (NSString *) getWarning {
5478 NSString *href(href_);
5479 NSRange colon([href rangeOfString:@"://"]);
5480 if (colon.location != NSNotFound)
5481 href = [href substringFromIndex:(colon.location + 3)];
5482 href = [href stringByAddingPercentEscapes];
5483 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5484 href = [href stringByCachingURLWithCurrentCDN];
5486 NSURL *url([NSURL URLWithString:href]);
5488 NSStringEncoding encoding;
5489 NSError *error(nil);
5491 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5492 return [warning length] == 0 ? nil : warning;
5496 - (void) _endConnection:(NSURLConnection *)connection {
5497 NSURLConnection **field = NULL;
5498 if (connection == trivial_bz2_)
5499 field = &trivial_bz2_;
5500 else if (connection == trivial_gz_)
5501 field = &trivial_gz_;
5502 _assert(field != NULL);
5503 [connection release];
5507 trivial_bz2_ == nil &&
5513 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5516 UIActionSheet *sheet = [[[UIActionSheet alloc]
5517 initWithTitle:CYLocalize("SOURCE_WARNING")
5518 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_ANYWAY"), CYLocalize("CANCEL"), nil]
5519 defaultButtonIndex:0
5524 [sheet setNumberOfRows:1];
5526 [sheet setBodyText:warning];
5527 [sheet popupAlertAnimated:YES];
5530 } else if (error_ != nil) {
5531 UIActionSheet *sheet = [[[UIActionSheet alloc]
5532 initWithTitle:CYLocalize("VERIFICATION_ERROR")
5533 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5534 defaultButtonIndex:0
5539 [sheet setBodyText:[error_ localizedDescription]];
5540 [sheet popupAlertAnimated:YES];
5542 UIActionSheet *sheet = [[[UIActionSheet alloc]
5543 initWithTitle:CYLocalize("NOT_REPOSITORY")
5544 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5545 defaultButtonIndex:0
5550 [sheet setBodyText:CYLocalize("NOT_REPOSITORY_EX")];
5551 [sheet popupAlertAnimated:YES];
5554 [delegate_ setStatusBarShowsProgress:NO];
5555 [delegate_ removeProgressHUD:hud_];
5565 if (error_ != nil) {
5572 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5573 switch ([response statusCode]) {
5579 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5580 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5582 error_ = [error retain];
5583 [self _endConnection:connection];
5586 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5587 [self _endConnection:connection];
5590 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5591 NSMutableURLRequest *request = [NSMutableURLRequest
5592 requestWithURL:[NSURL URLWithString:href]
5593 cachePolicy:NSURLRequestUseProtocolCachePolicy
5594 timeoutInterval:20.0
5597 [request setHTTPMethod:method];
5599 if (Machine_ != NULL)
5600 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5601 if (UniqueID_ != nil)
5602 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5605 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5607 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5610 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5611 NSString *context([sheet context]);
5613 if ([context isEqualToString:@"source"]) {
5616 NSString *href = [[sheet textField] text];
5618 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5620 if (![href hasSuffix:@"/"])
5621 href_ = [href stringByAppendingString:@"/"];
5624 href_ = [href_ retain];
5626 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5627 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5628 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5632 hud_ = [[delegate_ addProgressHUD] retain];
5633 [hud_ setText:CYLocalize("VERIFYING_URL")];
5644 } else if ([context isEqualToString:@"trivial"])
5646 else if ([context isEqualToString:@"urlerror"])
5648 else if ([context isEqualToString:@"warning"]) {
5668 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5669 if ((self = [super initWithBook:book]) != nil) {
5670 database_ = database;
5671 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5673 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5674 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5675 [list_ setShouldHideHeaderInShortLists:NO];
5677 [self addSubview:list_];
5678 [list_ setDataSource:self];
5680 UITableColumn *column = [[UITableColumn alloc]
5681 initWithTitle:CYLocalize("NAME")
5683 width:[self frame].size.width
5686 UITable *table = [list_ table];
5687 [table setSeparatorStyle:1];
5688 [table addTableColumn:column];
5689 [table setDelegate:self];
5693 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5694 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5698 - (void) reloadData {
5700 _assert(list.ReadMainList());
5702 [sources_ removeAllObjects];
5703 [sources_ addObjectsFromArray:[database_ sources]];
5705 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5708 int count = [sources_ count];
5709 for (offset_ = 0; offset_ != count; ++offset_) {
5710 Source *source = [sources_ objectAtIndex:offset_];
5711 if ([source record] == nil)
5718 - (void) resetViewAnimated:(BOOL)animated {
5719 [list_ resetViewAnimated:animated];
5722 - (void) _leftButtonClicked {
5723 /*[book_ pushPage:[[[AddSourceView alloc]
5728 UIActionSheet *sheet = [[[UIActionSheet alloc]
5729 initWithTitle:CYLocalize("ENTER_APT_URL")
5730 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_SOURCE"), CYLocalize("CANCEL"), nil]
5731 defaultButtonIndex:0
5736 [sheet setNumberOfRows:1];
5738 [sheet addTextFieldWithValue:@"http://" label:@""];
5740 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5741 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5742 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5743 [traits setKeyboardType:UIKeyboardTypeURL];
5744 // XXX: UIReturnKeyDone
5745 [traits setReturnKeyType:UIReturnKeyNext];
5747 [sheet popupAlertAnimated:YES];
5750 - (void) _rightButtonClicked {
5751 UITable *table = [list_ table];
5752 BOOL editing = [table isRowDeletionEnabled];
5753 [table enableRowDeletion:!editing animated:YES];
5754 [book_ reloadButtonsForPage:self];
5757 - (NSString *) title {
5758 return CYLocalize("SOURCES");
5761 - (NSString *) leftButtonTitle {
5762 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("ADD") : nil;
5765 - (id) rightButtonTitle {
5766 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("DONE") : CYLocalize("EDIT");
5769 - (UINavigationButtonStyle) rightButtonStyle {
5770 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5776 /* Installed View {{{ */
5777 @interface InstalledView : RVPage {
5778 _transient Database *database_;
5779 FilteredPackageTable *packages_;
5783 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5787 @implementation InstalledView
5790 [packages_ release];
5794 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5795 if ((self = [super initWithBook:book]) != nil) {
5796 database_ = database;
5798 packages_ = [[FilteredPackageTable alloc]
5802 filter:@selector(isInstalledAndVisible:)
5803 with:[NSNumber numberWithBool:YES]
5806 [self addSubview:packages_];
5808 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5809 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5813 - (void) resetViewAnimated:(BOOL)animated {
5814 [packages_ resetViewAnimated:animated];
5817 - (void) reloadData {
5818 [packages_ reloadData];
5821 - (void) _rightButtonClicked {
5822 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5823 [packages_ reloadData];
5825 [book_ reloadButtonsForPage:self];
5828 - (NSString *) title {
5829 return CYLocalize("INSTALLED");
5832 - (NSString *) backButtonTitle {
5833 return CYLocalize("PACKAGES");
5836 - (id) rightButtonTitle {
5837 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? CYLocalize("EXPERT") : CYLocalize("SIMPLE");
5840 - (UINavigationButtonStyle) rightButtonStyle {
5841 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5844 - (void) setDelegate:(id)delegate {
5845 [super setDelegate:delegate];
5846 [packages_ setDelegate:delegate];
5853 @interface HomeView : BrowserView {
5858 @implementation HomeView
5860 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5861 NSString *context([sheet context]);
5863 if ([context isEqualToString:@"about"])
5866 [super alertSheet:sheet buttonClicked:button];
5869 - (void) _leftButtonClicked {
5870 UIActionSheet *sheet = [[[UIActionSheet alloc]
5871 initWithTitle:CYLocalize("ABOUT_CYDIA")
5872 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
5873 defaultButtonIndex:0
5879 @"Copyright (C) 2008-2009\n"
5880 "Jay Freeman (saurik)\n"
5881 "saurik@saurik.com\n"
5882 "http://www.saurik.com/\n"
5885 "http://www.theokorigroup.com/\n"
5887 "College of Creative Studies,\n"
5888 "University of California,\n"
5890 "http://www.ccs.ucsb.edu/"
5893 [sheet popupAlertAnimated:YES];
5896 - (NSString *) leftButtonTitle {
5897 return CYLocalize("ABOUT");
5902 /* Manage View {{{ */
5903 @interface ManageView : BrowserView {
5908 @implementation ManageView
5910 - (NSString *) title {
5911 return CYLocalize("MANAGE");
5914 - (void) _leftButtonClicked {
5915 [delegate_ askForSettings];
5918 - (NSString *) leftButtonTitle {
5919 return CYLocalize("SETTINGS");
5923 - (id) _rightButtonTitle {
5924 return Queuing_ ? CYLocalize("QUEUE") : nil;
5927 - (UINavigationButtonStyle) rightButtonStyle {
5928 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5931 - (void) _rightButtonClicked {
5936 - (bool) isLoading {
5943 #include <BrowserView.m>
5945 /* Cydia Book {{{ */
5946 @interface CYBook : RVBook <
5949 _transient Database *database_;
5950 UINavigationBar *overlay_;
5951 UINavigationBar *underlay_;
5952 UIProgressIndicator *indicator_;
5953 UITextLabel *prompt_;
5954 UIProgressBar *progress_;
5955 UINavigationButton *cancel_;
5959 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
5965 @implementation CYBook
5969 [indicator_ release];
5971 [progress_ release];
5976 - (NSString *) getTitleForPage:(RVPage *)page {
5977 return [super getTitleForPage:page];
5985 [UIView beginAnimations:nil context:NULL];
5987 CGRect ovrframe = [overlay_ frame];
5988 ovrframe.origin.y = 0;
5989 [overlay_ setFrame:ovrframe];
5991 CGRect barframe = [navbar_ frame];
5992 barframe.origin.y += ovrframe.size.height;
5993 [navbar_ setFrame:barframe];
5995 CGRect trnframe = [transition_ frame];
5996 trnframe.origin.y += ovrframe.size.height;
5997 trnframe.size.height -= ovrframe.size.height;
5998 [transition_ setFrame:trnframe];
6000 [UIView endAnimations];
6002 [indicator_ startAnimation];
6003 [prompt_ setText:CYLocalize("UPDATING_DATABASE")];
6004 [progress_ setProgress:0];
6007 [overlay_ addSubview:cancel_];
6010 detachNewThreadSelector:@selector(_update)
6016 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6017 NSString *context([sheet context]);
6019 if ([context isEqualToString:@"refresh"])
6023 - (void) _update_:(NSString *)error {
6026 [indicator_ stopAnimation];
6028 [UIView beginAnimations:nil context:NULL];
6030 CGRect ovrframe = [overlay_ frame];
6031 ovrframe.origin.y = -ovrframe.size.height;
6032 [overlay_ setFrame:ovrframe];
6034 CGRect barframe = [navbar_ frame];
6035 barframe.origin.y -= ovrframe.size.height;
6036 [navbar_ setFrame:barframe];
6038 CGRect trnframe = [transition_ frame];
6039 trnframe.origin.y -= ovrframe.size.height;
6040 trnframe.size.height += ovrframe.size.height;
6041 [transition_ setFrame:trnframe];
6043 [UIView commitAnimations];
6046 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
6048 UIActionSheet *sheet = [[[UIActionSheet alloc]
6049 initWithTitle:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), CYLocalize("REFRESH")]
6050 buttons:[NSArray arrayWithObjects:
6053 defaultButtonIndex:0
6058 [sheet setBodyText:error];
6059 [sheet popupAlertAnimated:YES];
6061 [self reloadButtons];
6065 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6066 if ((self = [super initWithFrame:frame]) != nil) {
6067 database_ = database;
6069 CGRect ovrrect = [navbar_ bounds];
6070 ovrrect.size.height = [UINavigationBar defaultSize].height;
6071 ovrrect.origin.y = -ovrrect.size.height;
6073 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6074 [self addSubview:overlay_];
6076 ovrrect.origin.y = frame.size.height;
6077 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6078 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6079 [self addSubview:underlay_];
6081 [overlay_ setBarStyle:1];
6082 [underlay_ setBarStyle:1];
6084 int barstyle = [overlay_ _barStyle:NO];
6085 bool ugly = barstyle == 0;
6087 UIProgressIndicatorStyle style = ugly ?
6088 UIProgressIndicatorStyleMediumBrown :
6089 UIProgressIndicatorStyleMediumWhite;
6091 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
6092 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6093 CGRect indrect = {{indoffset, indoffset}, indsize};
6095 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6096 [indicator_ setStyle:style];
6097 [overlay_ addSubview:indicator_];
6099 CGSize prmsize = {215, indsize.height + 4};
6102 indoffset * 2 + indsize.width,
6106 unsigned(ovrrect.size.height - prmsize.height) / 2
6109 UIFont *font = [UIFont systemFontOfSize:15];
6111 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6113 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6114 [prompt_ setBackgroundColor:[UIColor clearColor]];
6115 [prompt_ setFont:font];
6117 [overlay_ addSubview:prompt_];
6119 CGSize prgsize = {75, 100};
6122 ovrrect.size.width - prgsize.width - 10,
6123 (ovrrect.size.height - prgsize.height) / 2
6126 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6127 [progress_ setStyle:0];
6128 [overlay_ addSubview:progress_];
6130 cancel_ = [[UINavigationButton alloc] initWithTitle:CYLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6131 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6133 CGRect frame = [cancel_ frame];
6134 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6135 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6136 [cancel_ setFrame:frame];
6138 [cancel_ setBarStyle:barstyle];
6142 - (void) _onCancel {
6144 [cancel_ removeFromSuperview];
6147 - (void) _update { _pooled
6149 status.setDelegate(self);
6151 NSString *error([database_ updateWithStatus:status]);
6154 performSelectorOnMainThread:@selector(_update_:)
6160 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
6161 [prompt_ setText:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), error]];
6164 - (void) setProgressTitle:(NSString *)title {
6166 performSelectorOnMainThread:@selector(_setProgressTitle:)
6172 - (void) setProgressPercent:(float)percent {
6174 performSelectorOnMainThread:@selector(_setProgressPercent:)
6175 withObject:[NSNumber numberWithFloat:percent]
6180 - (void) startProgress {
6183 - (void) addProgressOutput:(NSString *)output {
6185 performSelectorOnMainThread:@selector(_addProgressOutput:)
6191 - (bool) isCancelling:(size_t)received {
6195 - (void) _setProgressTitle:(NSString *)title {
6196 [prompt_ setText:title];
6199 - (void) _setProgressPercent:(NSNumber *)percent {
6200 [progress_ setProgress:[percent floatValue]];
6203 - (void) _addProgressOutput:(NSString *)output {
6208 /* Cydia:// Protocol {{{ */
6209 @interface CydiaURLProtocol : NSURLProtocol {
6214 @implementation CydiaURLProtocol
6216 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6217 NSURL *url([request URL]);
6220 NSString *scheme([[url scheme] lowercaseString]);
6221 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6226 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6230 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6231 id<NSURLProtocolClient> client([self client]);
6233 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6235 NSData *data(UIImagePNGRepresentation(icon));
6237 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6238 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6239 [client URLProtocol:self didLoadData:data];
6240 [client URLProtocolDidFinishLoading:self];
6244 - (void) startLoading {
6245 id<NSURLProtocolClient> client([self client]);
6246 NSURLRequest *request([self request]);
6248 NSURL *url([request URL]);
6249 NSString *href([url absoluteString]);
6251 NSString *path([href substringFromIndex:8]);
6252 NSRange slash([path rangeOfString:@"/"]);
6255 if (slash.location == NSNotFound) {
6259 command = [path substringToIndex:slash.location];
6260 path = [path substringFromIndex:(slash.location + 1)];
6263 Database *database([Database sharedInstance]);
6265 if ([command isEqualToString:@"package-icon"]) {
6268 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6269 Package *package([database packageWithName:path]);
6272 UIImage *icon([package icon]);
6273 [self _returnPNGWithImage:icon forRequest:request];
6274 } else if ([command isEqualToString:@"source-icon"]) {
6277 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6278 NSString *source(Simplify(path));
6279 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6281 icon = [UIImage applicationImageNamed:@"unknown.png"];
6282 [self _returnPNGWithImage:icon forRequest:request];
6283 } else if ([command isEqualToString:@"uikit-image"]) {
6286 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6287 UIImage *icon(_UIImageWithName(path));
6288 [self _returnPNGWithImage:icon forRequest:request];
6289 } else if ([command isEqualToString:@"section-icon"]) {
6292 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6293 NSString *section(Simplify(path));
6294 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6296 icon = [UIImage applicationImageNamed:@"unknown.png"];
6297 [self _returnPNGWithImage:icon forRequest:request];
6299 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6303 - (void) stopLoading {
6309 /* Sections View {{{ */
6310 @interface SectionsView : RVPage {
6311 _transient Database *database_;
6312 NSMutableArray *sections_;
6313 NSMutableArray *filtered_;
6314 UITransitionView *transition_;
6320 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6321 - (void) reloadData;
6326 @implementation SectionsView
6329 [list_ setDataSource:nil];
6330 [list_ setDelegate:nil];
6332 [sections_ release];
6333 [filtered_ release];
6334 [transition_ release];
6336 [accessory_ release];
6340 - (int) numberOfRowsInTable:(UITable *)table {
6341 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6344 - (float) table:(UITable *)table heightForRow:(int)row {
6348 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6350 reusing = [[[SectionCell alloc] init] autorelease];
6351 [(SectionCell *)reusing setSection:(editing_ ?
6352 [sections_ objectAtIndex:row] :
6353 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6354 ) editing:editing_];
6358 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6362 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6366 - (void) tableRowSelected:(NSNotification *)notification {
6367 int row = [[notification object] selectedRow];
6378 title = CYLocalize("ALL_PACKAGES");
6380 section = [filtered_ objectAtIndex:(row - 1)];
6381 name = [section name];
6384 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6387 title = CYLocalize("NO_SECTION");
6391 PackageTable *table = [[[FilteredPackageTable alloc]
6395 filter:@selector(isVisiblyUninstalledInSection:)
6399 [table setDelegate:delegate_];
6401 [book_ pushPage:table];
6404 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6405 if ((self = [super initWithBook:book]) != nil) {
6406 database_ = database;
6408 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6409 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6411 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6412 [self addSubview:transition_];
6414 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6415 [transition_ transition:0 toView:list_];
6417 UITableColumn *column = [[[UITableColumn alloc]
6418 initWithTitle:CYLocalize("NAME")
6420 width:[self frame].size.width
6423 [list_ setDataSource:self];
6424 [list_ setSeparatorStyle:1];
6425 [list_ addTableColumn:column];
6426 [list_ setDelegate:self];
6427 [list_ setReusesTableCells:YES];
6431 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6432 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6436 - (void) reloadData {
6437 NSArray *packages = [database_ packages];
6439 [sections_ removeAllObjects];
6440 [filtered_ removeAllObjects];
6443 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6444 SectionMap sections;
6445 sections.resize(64);
6447 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6451 for (Package *package in packages) {
6452 NSString *name([package section]);
6453 NSString *key(name == nil ? @"" : name);
6458 _profile(SectionsView$reloadData$Section)
6459 section = §ions[key];
6460 if (*section == nil) {
6461 _profile(SectionsView$reloadData$Section$Allocate)
6462 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6467 [*section addToCount];
6469 _profile(SectionsView$reloadData$Filter)
6470 if (![package valid] || ![package uninstalled] || ![package visible])
6474 [*section addToRow];
6478 _profile(SectionsView$reloadData$Section)
6479 section = [sections objectForKey:key];
6480 if (section == nil) {
6481 _profile(SectionsView$reloadData$Section$Allocate)
6482 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6483 [sections setObject:section forKey:key];
6488 [section addToCount];
6490 _profile(SectionsView$reloadData$Filter)
6491 if (![package valid] || ![package uninstalled] || ![package visible])
6501 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6502 [sections_ addObject:i->second];
6504 [sections_ addObjectsFromArray:[sections allValues]];
6507 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6509 for (Section *section in sections_) {
6510 size_t count([section row]);
6514 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6515 [section setCount:count];
6516 [filtered_ addObject:section];
6523 - (void) resetView {
6525 [self _rightButtonClicked];
6528 - (void) resetViewAnimated:(BOOL)animated {
6529 [list_ resetViewAnimated:animated];
6532 - (void) _rightButtonClicked {
6533 if ((editing_ = !editing_))
6536 [delegate_ updateData];
6537 [book_ reloadTitleForPage:self];
6538 [book_ reloadButtonsForPage:self];
6541 - (NSString *) title {
6542 return editing_ ? CYLocalize("SECTION_VISIBILITY") : CYLocalize("INSTALL_BY_SECTION");
6545 - (NSString *) backButtonTitle {
6546 return CYLocalize("SECTIONS");
6549 - (id) rightButtonTitle {
6550 return [sections_ count] == 0 ? nil : editing_ ? CYLocalize("DONE") : CYLocalize("EDIT");
6553 - (UINavigationButtonStyle) rightButtonStyle {
6554 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6557 - (UIView *) accessoryView {
6563 /* Changes View {{{ */
6564 @interface ChangesView : RVPage {
6565 _transient Database *database_;
6566 NSMutableArray *packages_;
6567 NSMutableArray *sections_;
6568 UISectionList *list_;
6572 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6573 - (void) reloadData;
6577 @implementation ChangesView
6580 [[list_ table] setDelegate:nil];
6581 [list_ setDataSource:nil];
6583 [packages_ release];
6584 [sections_ release];
6589 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6590 return [sections_ count];
6593 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6594 return [[sections_ objectAtIndex:section] name];
6597 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6598 return [[sections_ objectAtIndex:section] row];
6601 - (int) numberOfRowsInTable:(UITable *)table {
6602 return [packages_ count];
6605 - (float) table:(UITable *)table heightForRow:(int)row {
6606 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6609 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6611 reusing = [[[PackageCell alloc] init] autorelease];
6612 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6616 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6620 - (void) tableRowSelected:(NSNotification *)notification {
6621 int row = [[notification object] selectedRow];
6624 Package *package = [packages_ objectAtIndex:row];
6625 PackageView *view([delegate_ packageView]);
6626 [view setDelegate:delegate_];
6627 [view setPackage:package];
6628 [book_ pushPage:view];
6631 - (void) _leftButtonClicked {
6632 [(CYBook *)book_ update];
6633 [self reloadButtons];
6636 - (void) _rightButtonClicked {
6637 [delegate_ distUpgrade];
6640 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6641 if ((self = [super initWithBook:book]) != nil) {
6642 database_ = database;
6644 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6645 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6647 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6648 [self addSubview:list_];
6650 [list_ setShouldHideHeaderInShortLists:NO];
6651 [list_ setDataSource:self];
6652 //[list_ setSectionListStyle:1];
6654 UITableColumn *column = [[[UITableColumn alloc]
6655 initWithTitle:CYLocalize("NAME")
6657 width:[self frame].size.width
6660 UITable *table = [list_ table];
6661 [table setSeparatorStyle:1];
6662 [table addTableColumn:column];
6663 [table setDelegate:self];
6664 [table setReusesTableCells:YES];
6668 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6669 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6673 - (void) reloadData {
6674 NSArray *packages = [database_ packages];
6676 [packages_ removeAllObjects];
6677 [sections_ removeAllObjects];
6680 for (Package *package in packages)
6682 [package uninstalled] && [package valid] && [package visible] ||
6683 [package upgradableAndEssential:YES]
6685 [packages_ addObject:package];
6688 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6691 Section *upgradable = [[[Section alloc] initWithName:CYLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6692 Section *ignored = [[[Section alloc] initWithName:CYLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6693 Section *section = nil;
6697 bool unseens = false;
6699 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6701 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6702 Package *package = [packages_ objectAtIndex:offset];
6704 BOOL uae = [package upgradableAndEssential:YES];
6710 _profile(ChangesView$reloadData$Remember)
6711 seen = [package seen];
6714 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6719 name = CYLocalize("UNKNOWN");
6721 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6725 _profile(ChangesView$reloadData$Allocate)
6726 name = [NSString stringWithFormat:CYLocalize("NEW_AT"), name];
6727 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6728 [sections_ addObject:section];
6732 [section addToCount];
6733 } else if ([package ignored])
6734 [ignored addToCount];
6737 [upgradable addToCount];
6742 CFRelease(formatter);
6745 Section *last = [sections_ lastObject];
6746 size_t count = [last count];
6747 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6748 [sections_ removeLastObject];
6751 if ([ignored count] != 0)
6752 [sections_ insertObject:ignored atIndex:0];
6754 [sections_ insertObject:upgradable atIndex:0];
6757 [self reloadButtons];
6760 - (void) resetViewAnimated:(BOOL)animated {
6761 [list_ resetViewAnimated:animated];
6764 - (NSString *) leftButtonTitle {
6765 return [(CYBook *)book_ updating] ? nil : CYLocalize("REFRESH");
6768 - (id) rightButtonTitle {
6769 return upgrades_ == 0 ? nil : [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6772 - (NSString *) title {
6773 return CYLocalize("CHANGES");
6778 /* Search View {{{ */
6779 @protocol SearchViewDelegate
6780 - (void) showKeyboard:(BOOL)show;
6783 @interface SearchView : RVPage {
6785 UISearchField *field_;
6786 UITransitionView *transition_;
6787 FilteredPackageTable *table_;
6788 UIPreferencesTable *advanced_;
6794 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6795 - (void) reloadData;
6799 @implementation SearchView
6802 [field_ setDelegate:nil];
6804 [accessory_ release];
6806 [transition_ release];
6808 [advanced_ release];
6813 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6817 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6819 case 0: return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("ADVANCED_SEARCH"), CYLocalize("COMING_SOON")];
6821 default: _assert(false);
6825 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6829 default: _assert(false);
6833 - (void) _showKeyboard:(BOOL)show {
6834 CGSize keysize = [UIKeyboard defaultSize];
6835 CGRect keydown = [book_ pageBounds];
6836 CGRect keyup = keydown;
6837 keyup.size.height -= keysize.height - ButtonBarHeight_;
6839 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6841 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6842 [animation setSignificantRectFields:8];
6845 [animation setStartFrame:keydown];
6846 [animation setEndFrame:keyup];
6848 [animation setStartFrame:keyup];
6849 [animation setEndFrame:keydown];
6852 UIAnimator *animator = [UIAnimator sharedAnimator];
6855 addAnimations:[NSArray arrayWithObjects:animation, nil]
6856 withDuration:(KeyboardTime_ - delay)
6861 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6863 [delegate_ showKeyboard:show];
6866 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6867 [self _showKeyboard:YES];
6870 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
6871 [self _showKeyboard:NO];
6874 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
6876 NSString *text([field_ text]);
6877 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6883 - (void) textFieldClearButtonPressed:(UITextField *)field {
6887 - (void) keyboardInputShouldDelete:(id)input {
6891 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
6892 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6896 [field_ resignFirstResponder];
6901 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6902 if ((self = [super initWithBook:book]) != nil) {
6903 CGRect pageBounds = [book_ pageBounds];
6905 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6906 [self addSubview:transition_];
6908 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6910 [advanced_ setReusesTableCells:YES];
6911 [advanced_ setDataSource:self];
6912 [advanced_ reloadData];
6914 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6915 CGColor dimmed(space_, 0, 0, 0, 0.5);
6916 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
6918 table_ = [[FilteredPackageTable alloc]
6922 filter:@selector(isUnfilteredAndSearchedForBy:)
6926 [table_ setShouldHideHeaderInShortLists:NO];
6927 [transition_ transition:0 toView:table_];
6936 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
6943 [self bounds].size.width - area.origin.x - 18;
6945 area.size.height = [UISearchField defaultHeight];
6947 field_ = [[UISearchField alloc] initWithFrame:area];
6949 UIFont *font = [UIFont systemFontOfSize:16];
6950 [field_ setFont:font];
6952 [field_ setPlaceholder:CYLocalize("SEARCH_EX")];
6953 [field_ setDelegate:self];
6955 [field_ setPaddingTop:5];
6957 UITextInputTraits *traits([field_ textInputTraits]);
6958 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6959 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6960 [traits setReturnKeyType:UIReturnKeySearch];
6962 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
6964 accessory_ = [[UIView alloc] initWithFrame:accrect];
6965 [accessory_ addSubview:field_];
6967 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
6968 [configure setShowPressFeedback:YES];
6969 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
6970 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
6971 [accessory_ addSubview:configure];*/
6973 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6974 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6980 LKAnimation *animation = [LKTransition animation];
6981 [animation setType:@"oglFlip"];
6982 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
6983 [animation setFillMode:@"extended"];
6984 [animation setTransitionFlags:3];
6985 [animation setDuration:10];
6986 [animation setSpeed:0.35];
6987 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
6988 [[transition_ _layer] addAnimation:animation forKey:0];
6989 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
6990 flipped_ = !flipped_;
6994 - (void) configurePushed {
6995 [field_ resignFirstResponder];
6999 - (void) resetViewAnimated:(BOOL)animated {
7002 [table_ resetViewAnimated:animated];
7005 - (void) _reloadData {
7008 - (void) reloadData {
7011 [table_ setObject:[field_ text]];
7012 _profile(SearchView$reloadData)
7013 [table_ reloadData];
7016 [table_ resetCursor];
7019 - (UIView *) accessoryView {
7023 - (NSString *) title {
7027 - (NSString *) backButtonTitle {
7028 return CYLocalize("SEARCH");
7031 - (void) setDelegate:(id)delegate {
7032 [table_ setDelegate:delegate];
7033 [super setDelegate:delegate];
7039 @interface SettingsView : RVPage {
7040 _transient Database *database_;
7043 UIPreferencesTable *table_;
7044 _UISwitchSlider *subscribedSwitch_;
7045 _UISwitchSlider *ignoredSwitch_;
7046 UIPreferencesControlTableCell *subscribedCell_;
7047 UIPreferencesControlTableCell *ignoredCell_;
7050 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7054 @implementation SettingsView
7057 [table_ setDataSource:nil];
7060 if (package_ != nil)
7063 [subscribedSwitch_ release];
7064 [ignoredSwitch_ release];
7065 [subscribedCell_ release];
7066 [ignoredCell_ release];
7070 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7071 if (package_ == nil)
7077 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7078 if (package_ == nil)
7085 default: _assert(false);
7091 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7092 if (package_ == nil)
7099 default: _assert(false);
7105 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7106 if (package_ == nil)
7113 default: _assert(false);
7119 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7120 if (package_ == nil)
7123 _UISwitchSlider *slider([cell control]);
7124 BOOL value([slider value] != 0);
7125 NSMutableDictionary *metadata([package_ metadata]);
7128 if (NSNumber *number = [metadata objectForKey:key])
7129 before = [number boolValue];
7133 if (value != before) {
7134 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7136 [delegate_ updateData];
7140 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7141 [self onSomething:cell withKey:@"IsSubscribed"];
7144 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7145 [self onSomething:cell withKey:@"IsIgnored"];
7148 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7149 if (package_ == nil)
7153 case 0: switch (row) {
7155 return subscribedCell_;
7157 return ignoredCell_;
7158 default: _assert(false);
7161 case 1: switch (row) {
7163 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7164 [cell setShowSelection:NO];
7165 [cell setTitle:CYLocalize("SHOW_ALL_CHANGES_EX")];
7169 default: _assert(false);
7172 default: _assert(false);
7178 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7179 if ((self = [super initWithBook:book])) {
7180 database_ = database;
7181 name_ = [package retain];
7183 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7184 [self addSubview:table_];
7186 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7187 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
7189 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7190 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
7192 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7193 [subscribedCell_ setShowSelection:NO];
7194 [subscribedCell_ setTitle:CYLocalize("SHOW_ALL_CHANGES")];
7195 [subscribedCell_ setControl:subscribedSwitch_];
7197 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7198 [ignoredCell_ setShowSelection:NO];
7199 [ignoredCell_ setTitle:CYLocalize("IGNORE_UPGRADES")];
7200 [ignoredCell_ setControl:ignoredSwitch_];
7202 [table_ setDataSource:self];
7207 - (void) resetViewAnimated:(BOOL)animated {
7208 [table_ resetViewAnimated:animated];
7211 - (void) reloadData {
7212 if (package_ != nil)
7213 [package_ autorelease];
7214 package_ = [database_ packageWithName:name_];
7215 if (package_ != nil) {
7217 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7218 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7221 [table_ reloadData];
7224 - (NSString *) title {
7225 return CYLocalize("SETTINGS");
7230 /* Signature View {{{ */
7231 @interface SignatureView : BrowserView {
7232 _transient Database *database_;
7236 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7240 @implementation SignatureView
7247 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7249 [super webView:sender didClearWindowObject:window forFrame:frame];
7252 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7253 if ((self = [super initWithBook:book]) != nil) {
7254 database_ = database;
7255 package_ = [package retain];
7260 - (void) resetViewAnimated:(BOOL)animated {
7263 - (void) reloadData {
7264 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7270 @interface Cydia : UIApplication <
7271 ConfirmationViewDelegate,
7272 ProgressViewDelegate,
7281 UIToolbar *buttonbar_;
7285 NSMutableArray *essential_;
7286 NSMutableArray *broken_;
7288 Database *database_;
7289 ProgressView *progress_;
7293 UIKeyboard *keyboard_;
7294 UIProgressHUD *hud_;
7296 SectionsView *sections_;
7297 ChangesView *changes_;
7298 ManageView *manage_;
7299 SearchView *search_;
7301 NSMutableArray *details_;
7306 @implementation Cydia
7309 if ([broken_ count] != 0) {
7310 int count = [broken_ count];
7312 UIActionSheet *sheet = [[[UIActionSheet alloc]
7313 initWithTitle:(count == 1 ? CYLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:CYLocalize("HALFINSTALLED_PACKAGES"), count])
7314 buttons:[NSArray arrayWithObjects:
7315 CYLocalize("FORCIBLY_CLEAR"),
7316 CYLocalize("TEMPORARY_IGNORE"),
7318 defaultButtonIndex:0
7323 [sheet setBodyText:CYLocalize("HALFINSTALLED_PACKAGE_EX")];
7324 [sheet popupAlertAnimated:YES];
7325 } else if (!Ignored_ && [essential_ count] != 0) {
7326 int count = [essential_ count];
7328 UIActionSheet *sheet = [[[UIActionSheet alloc]
7329 initWithTitle:(count == 1 ? CYLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:CYLocalize("ESSENTIAL_UPGRADES"), count])
7330 buttons:[NSArray arrayWithObjects:
7331 CYLocalize("UPGRADE_ESSENTIAL"),
7332 CYLocalize("COMPLETE_UPGRADE"),
7333 CYLocalize("TEMPORARY_IGNORE"),
7335 defaultButtonIndex:0
7340 [sheet setBodyText:CYLocalize("ESSENTIAL_UPGRADE_EX")];
7341 [sheet popupAlertAnimated:YES];
7345 - (void) _reloadData {
7348 static bool loaded(false);
7349 UIProgressHUD *hud([self addProgressHUD]);
7350 [hud setText:(loaded ? CYLocalize("RELOADING_DATA") : CYLocalize("LOADING_DATA"))];
7353 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7356 [self removeProgressHUD:hud];
7360 [essential_ removeAllObjects];
7361 [broken_ removeAllObjects];
7363 NSArray *packages = [database_ packages];
7364 for (Package *package in packages) {
7366 [broken_ addObject:package];
7367 if ([package upgradableAndEssential:NO]) {
7368 if ([package essential])
7369 [essential_ addObject:package];
7375 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7376 [buttonbar_ setBadgeValue:badge forButton:3];
7377 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7378 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7379 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7380 [self setApplicationBadge:badge];
7382 [self setApplicationBadgeString:badge];
7384 [buttonbar_ setBadgeValue:nil forButton:3];
7385 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7386 [buttonbar_ setBadgeAnimated:NO forButton:3];
7387 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7388 [self removeApplicationBadge];
7389 else // XXX: maybe use setApplicationBadgeString also?
7390 [self setApplicationIconBadgeNumber:0];
7394 [buttonbar_ setBadgeValue:nil forButton:4];
7398 // XXX: what is this line of code for?
7399 if ([packages count] == 0);
7400 else if (Loaded_ || ManualRefresh) loaded:
7405 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7406 NSTimeInterval interval([update timeIntervalSinceNow]);
7407 if (interval <= 0 && interval > -600)
7415 - (void) _saveConfig {
7418 NSString *error(nil);
7419 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7421 NSError *error(nil);
7422 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7423 NSLog(@"failure to save metadata data: %@", error);
7426 NSLog(@"failure to serialize metadata: %@", error);
7434 - (void) updateData {
7437 /* XXX: this is just stupid */
7438 if (tag_ != 2 && sections_ != nil)
7439 [sections_ reloadData];
7440 if (tag_ != 3 && changes_ != nil)
7441 [changes_ reloadData];
7442 if (tag_ != 5 && search_ != nil)
7443 [search_ reloadData];
7453 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7454 _assert(file != NULL);
7456 NSArray *keys = [Sources_ allKeys];
7458 for (NSString *key in keys) {
7459 NSDictionary *source = [Sources_ objectForKey:key];
7461 fprintf(file, "%s %s %s\n",
7462 [[source objectForKey:@"Type"] UTF8String],
7463 [[source objectForKey:@"URI"] UTF8String],
7464 [[source objectForKey:@"Distribution"] UTF8String]
7473 detachNewThreadSelector:@selector(update_)
7476 title:CYLocalize("UPDATING_SOURCES")
7480 - (void) reloadData {
7481 @synchronized (self) {
7482 if (confirm_ == nil)
7488 pkgProblemResolver *resolver = [database_ resolver];
7490 resolver->InstallProtect();
7491 if (!resolver->Resolve(true))
7495 - (void) popUpBook:(RVBook *)book {
7496 [underlay_ popSubview:book];
7499 - (CGRect) popUpBounds {
7500 return [underlay_ bounds];
7504 [database_ prepare];
7506 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7507 [confirm_ setDelegate:self];
7509 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7510 [page setDelegate:self];
7512 [confirm_ setPage:page];
7513 [self popUpBook:confirm_];
7517 @synchronized (self) {
7522 - (void) clearPackage:(Package *)package {
7523 @synchronized (self) {
7530 - (void) installPackage:(Package *)package {
7531 @synchronized (self) {
7538 - (void) removePackage:(Package *)package {
7539 @synchronized (self) {
7546 - (void) distUpgrade {
7547 @synchronized (self) {
7548 [database_ upgrade];
7554 [self slideUp:[[[UIActionSheet alloc]
7556 buttons:[NSArray arrayWithObjects:CYLocalize("CONTINUE_QUEUING"), CYLocalize("CANCEL_CLEAR"), nil]
7557 defaultButtonIndex:1
7564 @synchronized (self) {
7567 if (confirm_ != nil) {
7575 [overlay_ removeFromSuperview];
7579 detachNewThreadSelector:@selector(perform)
7582 title:CYLocalize("RUNNING")
7586 - (void) bootstrap_ {
7588 [database_ upgrade];
7589 [database_ prepare];
7590 [database_ perform];
7593 /* XXX: replace and localize */
7594 - (void) bootstrap {
7596 detachNewThreadSelector:@selector(bootstrap_)
7599 title:@"Bootstrap Install"
7603 - (void) progressViewIsComplete:(ProgressView *)progress {
7604 if (confirm_ != nil) {
7605 [underlay_ addSubview:overlay_];
7606 [confirm_ popFromSuperviewAnimated:NO];
7612 - (void) setPage:(RVPage *)page {
7613 [page resetViewAnimated:NO];
7614 [page setDelegate:self];
7615 [book_ setPage:page];
7618 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7619 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7620 [browser loadURL:url];
7624 - (void) _setHomePage {
7625 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7628 - (SectionsView *) sectionsView {
7629 if (sections_ == nil)
7630 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7634 - (void) buttonBarItemTapped:(id)sender {
7635 unsigned tag = [sender tag];
7637 [book_ resetViewAnimated:YES];
7639 } else if (tag_ == 2 && tag != 2)
7640 [[self sectionsView] resetView];
7643 case 1: [self _setHomePage]; break;
7645 case 2: [self setPage:[self sectionsView]]; break;
7646 case 3: [self setPage:changes_]; break;
7647 case 4: [self setPage:manage_]; break;
7648 case 5: [self setPage:search_]; break;
7650 default: _assert(false);
7656 - (void) applicationWillSuspend {
7658 [super applicationWillSuspend];
7661 - (void) askForSettings {
7662 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
7664 UIActionSheet *role = [[[UIActionSheet alloc]
7665 initWithTitle:CYLocalize("WHO_ARE_YOU")
7666 buttons:[NSArray arrayWithObjects:
7667 [NSString stringWithFormat:parenthetical, CYLocalize("USER"), CYLocalize("USER_EX")],
7668 [NSString stringWithFormat:parenthetical, CYLocalize("HACKER"), CYLocalize("HACKER_EX")],
7669 [NSString stringWithFormat:parenthetical, CYLocalize("DEVELOPER"), CYLocalize("DEVELOPER_EX")],
7671 defaultButtonIndex:-1
7676 [role setBodyText:CYLocalize("ROLE_EX")];
7677 [role popupAlertAnimated:YES];
7680 - (void) setPackageView:(PackageView *)view {
7682 [view setPackage:nil];
7683 if ([details_ count] < 3)
7684 [details_ addObject:view];
7688 - (PackageView *) _packageView {
7689 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7692 - (PackageView *) packageView {
7694 size_t count([details_ count]);
7697 view = [self _packageView];
7699 [details_ addObject:[self _packageView]];
7701 view = [[[details_ lastObject] retain] autorelease];
7702 [details_ removeLastObject];
7712 [self setStatusBarShowsProgress:NO];
7713 [self removeProgressHUD:hud_];
7718 pid_t pid = ExecFork();
7720 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7721 perror("launchctl stop");
7728 [self askForSettings];
7733 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7735 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7736 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7737 0, 0, screenrect.size.width, screenrect.size.height - 48
7738 ) database:database_];
7740 [book_ setDelegate:self];
7742 [overlay_ addSubview:book_];
7744 NSArray *buttonitems = [NSArray arrayWithObjects:
7745 [NSDictionary dictionaryWithObjectsAndKeys:
7746 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7747 @"home-up.png", kUIButtonBarButtonInfo,
7748 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7749 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7750 self, kUIButtonBarButtonTarget,
7751 @"Cydia", kUIButtonBarButtonTitle,
7752 @"0", kUIButtonBarButtonType,
7755 [NSDictionary dictionaryWithObjectsAndKeys:
7756 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7757 @"install-up.png", kUIButtonBarButtonInfo,
7758 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7759 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7760 self, kUIButtonBarButtonTarget,
7761 CYLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7762 @"0", kUIButtonBarButtonType,
7765 [NSDictionary dictionaryWithObjectsAndKeys:
7766 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7767 @"changes-up.png", kUIButtonBarButtonInfo,
7768 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7769 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7770 self, kUIButtonBarButtonTarget,
7771 CYLocalize("CHANGES"), kUIButtonBarButtonTitle,
7772 @"0", kUIButtonBarButtonType,
7775 [NSDictionary dictionaryWithObjectsAndKeys:
7776 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7777 @"manage-up.png", kUIButtonBarButtonInfo,
7778 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7779 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7780 self, kUIButtonBarButtonTarget,
7781 CYLocalize("MANAGE"), kUIButtonBarButtonTitle,
7782 @"0", kUIButtonBarButtonType,
7785 [NSDictionary dictionaryWithObjectsAndKeys:
7786 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7787 @"search-up.png", kUIButtonBarButtonInfo,
7788 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7789 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7790 self, kUIButtonBarButtonTarget,
7791 CYLocalize("SEARCH"), kUIButtonBarButtonTitle,
7792 @"0", kUIButtonBarButtonType,
7796 buttonbar_ = [[UIToolbar alloc]
7798 withFrame:CGRectMake(
7799 0, screenrect.size.height - ButtonBarHeight_,
7800 screenrect.size.width, ButtonBarHeight_
7802 withItemList:buttonitems
7805 [buttonbar_ setDelegate:self];
7806 [buttonbar_ setBarStyle:1];
7807 [buttonbar_ setButtonBarTrackingMode:2];
7809 int buttons[5] = {1, 2, 3, 4, 5};
7810 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7811 [buttonbar_ showButtonGroup:0 withDuration:0];
7813 for (int i = 0; i != 5; ++i)
7814 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7815 i * 64 + 2, 1, 60, ButtonBarHeight_
7818 [buttonbar_ showSelectionForButton:1];
7819 [overlay_ addSubview:buttonbar_];
7821 [UIKeyboard initImplementationNow];
7822 CGSize keysize = [UIKeyboard defaultSize];
7823 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7824 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7825 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
7826 [overlay_ addSubview:keyboard_];
7829 [underlay_ addSubview:overlay_];
7833 [self sectionsView];
7834 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7835 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7837 manage_ = (ManageView *) [[self
7838 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7839 withClass:[ManageView class]
7842 details_ = [[NSMutableArray alloc] initWithCapacity:4];
7843 [details_ addObject:[self _packageView]];
7844 [details_ addObject:[self _packageView]];
7851 [self _setHomePage];
7854 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7855 NSString *context([sheet context]);
7857 if ([context isEqualToString:@"missing"])
7859 else if ([context isEqualToString:@"cancel"]) {
7877 @synchronized (self) {
7882 [buttonbar_ setBadgeValue:CYLocalize("Q_D") forButton:4];
7886 if (confirm_ != nil) {
7891 } else if ([context isEqualToString:@"fixhalf"]) {
7894 @synchronized (self) {
7895 for (Package *broken in broken_) {
7898 NSString *id = [broken id];
7899 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7900 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7901 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7902 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7911 [broken_ removeAllObjects];
7920 } else if ([context isEqualToString:@"role"]) {
7922 case 1: Role_ = @"User"; break;
7923 case 2: Role_ = @"Hacker"; break;
7924 case 3: Role_ = @"Developer"; break;
7931 bool reset = Settings_ != nil;
7933 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7937 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7947 } else if ([context isEqualToString:@"upgrade"]) {
7950 @synchronized (self) {
7951 for (Package *essential in essential_)
7952 [essential install];
7975 - (void) reorganize { _pooled
7976 system("/usr/libexec/cydia/free.sh");
7977 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
7980 - (void) applicationSuspend:(__GSEvent *)event {
7981 if (hud_ == nil && ![progress_ isRunning])
7982 [super applicationSuspend:event];
7985 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7987 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7990 - (void) _setSuspended:(BOOL)value {
7992 [super _setSuspended:value];
7995 - (UIProgressHUD *) addProgressHUD {
7996 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
7997 [window_ setUserInteractionEnabled:NO];
7999 [progress_ addSubview:hud];
8003 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8005 [hud removeFromSuperview];
8006 [window_ setUserInteractionEnabled:YES];
8009 - (void) openMailToURL:(NSURL *)url {
8010 // XXX: this makes me sad
8012 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
8014 [UIApp openURL:url];// asPanel:YES];
8018 - (void) clearFirstResponder {
8019 if (id responder = [window_ firstResponder])
8020 [responder resignFirstResponder];
8023 - (RVPage *) pageForPackage:(NSString *)name {
8024 if (Package *package = [database_ packageWithName:name]) {
8025 PackageView *view([self packageView]);
8026 [view setPackage:package];
8029 UIActionSheet *sheet = [[[UIActionSheet alloc]
8030 initWithTitle:CYLocalize("CANNOT_LOCATE_PACKAGE")
8031 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
8032 defaultButtonIndex:0
8037 [sheet setBodyText:[NSString stringWithFormat:CYLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
8039 [sheet popupAlertAnimated:YES];
8044 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8048 NSString *scheme([[url scheme] lowercaseString]);
8049 if (![scheme isEqualToString:@"cydia"])
8051 NSString *path([url absoluteString]);
8052 if ([path length] < 8)
8054 path = [path substringFromIndex:8];
8055 if (![path hasPrefix:@"/"])
8056 path = [@"/" stringByAppendingString:path];
8058 if ([path isEqualToString:@"/add-source"])
8059 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8060 else if ([path isEqualToString:@"/storage"])
8061 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[BrowserView class]];
8062 else if ([path isEqualToString:@"/sources"])
8063 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8064 else if ([path isEqualToString:@"/packages"])
8065 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8066 else if ([path hasPrefix:@"/url/"])
8067 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[BrowserView class]];
8068 else if ([path hasPrefix:@"/launch/"])
8069 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8070 else if ([path hasPrefix:@"/package-settings/"])
8071 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8072 else if ([path hasPrefix:@"/package-signature/"])
8073 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8074 else if ([path hasPrefix:@"/package/"])
8075 return [self pageForPackage:[path substringFromIndex:9]];
8076 else if ([path hasPrefix:@"/files/"]) {
8077 NSString *name = [path substringFromIndex:7];
8079 if (Package *package = [database_ packageWithName:name]) {
8080 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8081 [files setPackage:package];
8089 - (void) applicationOpenURL:(NSURL *)url {
8090 [super applicationOpenURL:url];
8092 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8093 [self setPage:page];
8094 [buttonbar_ showSelectionForButton:tag];
8099 - (void) applicationDidFinishLaunching:(id)unused {
8101 Font12_ = [[UIFont systemFontOfSize:12] retain];
8102 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8103 Font14_ = [[UIFont systemFontOfSize:14] retain];
8104 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8105 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8109 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8110 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8112 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8114 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8115 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
8117 [window_ orderFront:self];
8118 [window_ makeKey:self];
8119 [window_ setHidden:NO];
8121 database_ = [Database sharedInstance];
8122 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8123 [database_ setDelegate:progress_];
8124 [window_ setContentView:progress_];
8126 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8127 [progress_ setContentView:underlay_];
8129 [progress_ resetView];
8132 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8133 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8134 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL /*||
8135 readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL*/ ||
8136 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8137 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8138 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8139 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
8140 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
8142 [self setIdleTimerDisabled:YES];
8144 hud_ = [[self addProgressHUD] retain];
8145 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8147 [self setStatusBarShowsProgress:YES];
8150 detachNewThreadSelector:@selector(reorganize)
8158 - (void) showKeyboard:(BOOL)show {
8159 CGSize keysize = [UIKeyboard defaultSize];
8160 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8161 CGRect keyup = keydown;
8162 keyup.origin.y -= keysize.height;
8164 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
8165 [animation setSignificantRectFields:2];
8168 [animation setStartFrame:keydown];
8169 [animation setEndFrame:keyup];
8170 [keyboard_ activate];
8172 [animation setStartFrame:keyup];
8173 [animation setEndFrame:keydown];
8174 [keyboard_ deactivate];
8177 [[UIAnimator sharedAnimator]
8178 addAnimations:[NSArray arrayWithObjects:animation, nil]
8179 withDuration:KeyboardTime_
8184 - (void) slideUp:(UIActionSheet *)alert {
8186 [alert presentSheetFromButtonBar:buttonbar_];
8188 [alert presentSheetInView:overlay_];
8193 void AddPreferences(NSString *plist) { _pooled
8194 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
8195 _assert(settings != NULL);
8196 NSMutableArray *items = [settings objectForKey:@"items"];
8200 for (NSMutableDictionary *item in items) {
8201 NSString *label = [item objectForKey:@"label"];
8202 if (label != nil && [label isEqualToString:@"Cydia"]) {
8209 for (size_t i(0); i != [items count]; ++i) {
8210 NSDictionary *item([items objectAtIndex:i]);
8211 NSString *label = [item objectForKey:@"label"];
8212 if (label != nil && [label isEqualToString:@"General"]) {
8213 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
8214 @"CydiaSettings", @"bundle",
8215 @"PSLinkCell", @"cell",
8216 [NSNumber numberWithBool:YES], @"hasIcon",
8217 [NSNumber numberWithBool:YES], @"isController",
8219 nil] atIndex:(i + 1)];
8225 _assert([settings writeToFile:plist atomically:YES] == YES);
8230 id Alloc_(id self, SEL selector) {
8231 id object = alloc_(self, selector);
8232 lprintf("[%s]A-%p\n", self->isa->name, object);
8237 id Dealloc_(id self, SEL selector) {
8238 id object = dealloc_(self, selector);
8239 lprintf("[%s]D-%p\n", self->isa->name, object);
8243 Class $WebDefaultUIKitDelegate;
8245 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
8247 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
8248 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8249 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8250 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
8253 int main(int argc, char *argv[]) { _pooled
8256 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8258 /* Library Hacks {{{ */
8259 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8261 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8262 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8263 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8264 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8265 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8268 /* Set Locale {{{ */
8269 Locale_ = CFLocaleCopyCurrent();
8270 Languages_ = [NSLocale preferredLanguages];
8271 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8272 //NSLog(@"%@", [Languages_ description]);
8274 if (Languages_ == nil || [Languages_ count] == 0)
8277 lang = [[Languages_ objectAtIndex:0] UTF8String];
8278 setenv("LANG", lang, true);
8279 //std::setlocale(LC_ALL, lang);
8280 NSLog(@"Setting Language: %s", lang);
8283 // XXX: apr_app_initialize?
8286 /* Parse Arguments {{{ */
8287 bool substrate(false);
8293 for (int argi(1); argi != argc; ++argi)
8294 if (strcmp(argv[argi], "--") == 0) {
8296 argv[argi] = argv[0];
8302 for (int argi(1); argi != arge; ++argi)
8303 if (strcmp(args[argi], "--bootstrap") == 0)
8305 else if (strcmp(args[argi], "--substrate") == 0)
8308 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8313 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
8314 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
8315 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
8316 Sounds_Keyboard_ = [keyboard boolValue];
8319 App_ = [[NSBundle mainBundle] bundlePath];
8320 Home_ = NSHomeDirectory();
8325 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8326 alloc_ = alloc->method_imp;
8327 alloc->method_imp = (IMP) &Alloc_;*/
8329 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8330 dealloc_ = dealloc->method_imp;
8331 dealloc->method_imp = (IMP) &Dealloc_;*/
8336 size = sizeof(maxproc);
8337 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8338 perror("sysctlbyname(\"kern.maxproc\", ?)");
8339 else if (maxproc < 64) {
8341 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8342 perror("sysctlbyname(\"kern.maxproc\", #)");
8345 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8346 char *machine = new char[size];
8347 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8348 perror("sysctlbyname(\"hw.machine\", ?)");
8352 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8354 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8355 Build_ = [system objectForKey:@"ProductBuildVersion"];
8356 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8357 Product_ = [info objectForKey:@"SafariProductVersion"];
8358 Safari_ = [info objectForKey:@"CFBundleVersion"];
8361 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8362 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
8364 /* Load Database {{{ */
8366 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8368 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8371 if (Metadata_ == NULL)
8372 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8374 Settings_ = [Metadata_ objectForKey:@"Settings"];
8376 Packages_ = [Metadata_ objectForKey:@"Packages"];
8377 Sections_ = [Metadata_ objectForKey:@"Sections"];
8378 Sources_ = [Metadata_ objectForKey:@"Sources"];
8381 if (Settings_ != nil)
8382 Role_ = [Settings_ objectForKey:@"Role"];
8384 if (Packages_ == nil) {
8385 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8386 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8389 if (Sections_ == nil) {
8390 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8391 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8394 if (Sources_ == nil) {
8395 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8396 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8401 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8404 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8405 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8406 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8407 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8409 if (access("/User", F_OK) != 0) {
8411 system("/usr/libexec/cydia/firmware.sh");
8415 _assert([[NSFileManager defaultManager]
8416 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8417 withIntermediateDirectories:YES
8422 if (access("/tmp/cydia.chk", F_OK) == 0) {
8423 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8424 _assert(errno == ENOENT);
8425 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8426 _assert(errno == ENOENT);
8429 _assert(pkgInitConfig(*_config));
8430 _assert(pkgInitSystem(*_config, _system));
8433 _config->Set("APT::Acquire::Translation", lang);
8434 _config->Set("Acquire::http::Timeout", 15);
8435 _config->Set("Acquire::http::MaxParallel", 4);
8437 /* Color Choices {{{ */
8438 space_ = CGColorSpaceCreateDeviceRGB();
8440 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8441 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8442 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8443 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8444 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8445 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8446 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8447 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8448 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8449 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8450 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8451 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8452 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8453 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8454 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8457 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8458 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8461 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8463 /* UIKit Configuration {{{ */
8464 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8465 if ($GSFontSetUseLegacyFontMetrics != NULL)
8466 $GSFontSetUseLegacyFontMetrics(YES);
8468 UIKeyboardDisableAutomaticAppearance();
8472 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8474 CGColorSpaceRelease(space_);