1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008 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>
91 #include <apr-1/apr_pools.h>
93 #include <sys/types.h>
95 #include <sys/sysctl.h>
96 #include <sys/param.h>
97 #include <sys/mount.h>
103 #include <mach-o/nlist.h>
113 #include <ext/hash_map>
115 #import "BrowserView.h"
116 #import "ResetView.h"
118 #import "substrate.h"
121 //#define _finline __attribute__((force_inline))
122 #define _finline inline
127 #define _limit(count) do { \
128 static size_t _count(0); \
129 if (++_count == count) \
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
199 /* Objective-C Handle<> {{{ */
200 template <typename Type_>
202 typedef _H<Type_> This_;
207 _finline void Retain_() {
212 _finline void Clear_() {
218 _finline _H(Type_ *value = NULL, bool mended = false) :
229 _finline operator Type_ *() const {
233 _finline This_ &operator =(Type_ *value) {
234 if (value_ != value) {
245 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
247 void NSLogPoint(const char *fix, const CGPoint &point) {
248 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
251 void NSLogRect(const char *fix, const CGRect &rect) {
252 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
255 @interface NSObject (Cydia)
256 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
257 - (id) yieldToSelector:(SEL)selector;
260 @implementation NSObject (Cydia)
265 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
266 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
267 id object([[context objectAtIndex:1] nonretainedObjectValue]);
268 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
270 /* XXX: deal with exceptions */
271 id value([self performSelector:selector withObject:object]);
273 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
274 [context removeAllObjects];
275 if ([signature methodReturnLength] != 0 && value != nil)
276 [context addObject:value];
281 performSelectorOnMainThread:@selector(doNothing)
287 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
288 /*return [self performSelector:selector withObject:object];*/
290 volatile bool stopped(false);
292 NSMutableArray *context([NSMutableArray arrayWithObjects:
293 [NSValue valueWithPointer:selector],
294 [NSValue valueWithNonretainedObject:object],
295 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
298 NSThread *thread([[[NSThread alloc]
300 selector:@selector(_yieldToContext:)
306 NSRunLoop *loop([NSRunLoop currentRunLoop]);
307 NSDate *future([NSDate distantFuture]);
309 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
311 return [context count] == 0 ? nil : [context objectAtIndex:0];
314 - (id) yieldToSelector:(SEL)selector {
315 return [self yieldToSelector:selector withObject:nil];
320 /* NSForcedOrderingSearch doesn't work on the iPhone */
321 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
322 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
323 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
325 /* iPhoneOS 2.0 Compatibility {{{ */
327 @interface UITextView (iPhoneOS)
328 - (void) setTextSize:(float)size;
331 @implementation UITextView (iPhoneOS)
333 - (void) setTextSize:(float)size {
334 [self setFont:[[self font] fontWithSize:size]];
341 extern NSString * const kCAFilterNearest;
343 /* Information Dictionaries {{{ */
344 @interface NSMutableArray (Cydia)
345 - (void) addInfoDictionary:(NSDictionary *)info;
348 @implementation NSMutableArray (Cydia)
350 - (void) addInfoDictionary:(NSDictionary *)info {
351 [self addObject:info];
356 @interface NSMutableDictionary (Cydia)
357 - (void) addInfoDictionary:(NSDictionary *)info;
360 @implementation NSMutableDictionary (Cydia)
362 - (void) addInfoDictionary:(NSDictionary *)info {
363 NSString *bundle = [info objectForKey:@"CFBundleIdentifier"];
364 [self setObject:info forKey:bundle];
369 /* Pop Transitions {{{ */
370 @interface PopTransitionView : UITransitionView {
375 @implementation PopTransitionView
377 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
378 if (from != nil && to == nil)
379 [self removeFromSuperview];
384 @implementation UIView (PopUpView)
386 - (void) popFromSuperviewAnimated:(BOOL)animated {
387 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
390 - (void) popSubview:(UIView *)view {
391 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
392 [transition setDelegate:transition];
393 [self addSubview:transition];
395 UIView *blank = [[[UIView alloc] initWithFrame:[transition bounds]] autorelease];
396 [transition transition:UITransitionNone toView:blank];
397 [transition transition:UITransitionPushFromBottom toView:view];
403 #define lprintf(args...) fprintf(stderr, args)
406 #define TraceLogging (1 && !ForRelease)
407 #define HistogramInsertionSort (0 && !ForRelease)
408 #define ProfileTimes (1 && !ForRelease)
409 #define ForSaurik (0 && !ForRelease)
410 #define LogBrowser (0 && !ForRelease)
411 #define TrackResize (0 && !ForRelease)
412 #define ManualRefresh (1 && !ForRelease)
413 #define ShowInternals (0 && !ForRelease)
414 #define IgnoreInstall (0 && !ForRelease)
415 #define RecycleWebViews 0
416 #define AlwaysReload (1 && !ForRelease)
420 #define _trace(args...)
425 #define _profile(name) {
428 #define PrintTimes() do {} while (false)
432 typedef uint32_t (*SKRadixFunction)(id, void *);
434 @interface NSMutableArray (Radix)
435 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
436 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
444 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
445 struct RadixItem_ *lhs(swap), *rhs(swap + count);
447 static const size_t width = 32;
448 static const size_t bits = 11;
449 static const size_t slots = 1 << bits;
450 static const size_t passes = (width + (bits - 1)) / bits;
452 size_t *hist(new size_t[slots]);
454 for (size_t pass(0); pass != passes; ++pass) {
455 memset(hist, 0, sizeof(size_t) * slots);
457 for (size_t i(0); i != count; ++i) {
458 uint32_t key(lhs[i].key);
460 key &= _not(uint32_t) >> width - bits;
465 for (size_t i(0); i != slots; ++i) {
466 size_t local(offset);
471 for (size_t i(0); i != count; ++i) {
472 uint32_t key(lhs[i].key);
474 key &= _not(uint32_t) >> width - bits;
475 rhs[hist[key]++] = lhs[i];
478 RadixItem_ *tmp(lhs);
485 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
486 for (size_t i(0); i != count; ++i)
487 [values addObject:[self objectAtIndex:lhs[i].index]];
488 [self setArray:values];
493 @implementation NSMutableArray (Radix)
495 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
496 size_t count([self count]);
501 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
502 [invocation setSelector:selector];
503 [invocation setArgument:&object atIndex:2];
505 /* XXX: this is an unsafe optimization of doomy hell */
506 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
507 _assert(method != NULL);
508 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
509 _assert(imp != NULL);
512 struct RadixItem_ *swap(new RadixItem_[count * 2]);
514 for (size_t i(0); i != count; ++i) {
515 RadixItem_ &item(swap[i]);
518 id object([self objectAtIndex:i]);
521 [invocation setTarget:object];
523 [invocation getReturnValue:&item.key];
525 item.key = imp(object, selector, object);
529 RadixSort_(self, count, swap);
532 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
533 size_t count([self count]);
534 struct RadixItem_ *swap(new RadixItem_[count * 2]);
536 for (size_t i(0); i != count; ++i) {
537 RadixItem_ &item(swap[i]);
540 id object([self objectAtIndex:i]);
541 item.key = function(object, argument);
544 RadixSort_(self, count, swap);
549 /* Insertion Sort {{{ */
551 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
552 const char *ptr = (const char *)list;
554 CFIndex half = count / 2;
555 const char *probe = ptr + elementSize * half;
556 CFComparisonResult cr = comparator(element, probe, context);
557 if (0 == cr) return (probe - (const char *)list) / elementSize;
558 ptr = (cr < 0) ? ptr : probe + elementSize;
559 count = (cr < 0) ? half : (half + (count & 1) - 1);
561 return (ptr - (const char *)list) / elementSize;
564 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
565 const char *ptr = (const char *)list;
567 CFIndex half = count / 2;
568 const char *probe = ptr + elementSize * half;
569 CFComparisonResult cr = comparator(element, probe, context);
570 if (0 == cr) return (probe - (const char *)list) / elementSize;
571 ptr = (cr < 0) ? ptr : probe + elementSize;
572 count = (cr < 0) ? half : (half + (count & 1) - 1);
574 return (ptr - (const char *)list) / elementSize;
577 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
578 if (range.length == 0)
580 const void **values(new const void *[range.length]);
581 CFArrayGetValues(array, range, values);
583 #if HistogramInsertionSort
584 uint32_t total(0), *offsets(new uint32_t[range.length]);
587 for (CFIndex index(1); index != range.length; ++index) {
588 const void *value(values[index]);
589 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
590 CFIndex correct(index);
591 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
594 if (correct != index) {
595 size_t offset(index - correct);
596 #if HistogramInsertionSort
600 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
602 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
603 values[correct] = value;
607 CFArrayReplaceValues(array, range, values, range.length);
610 #if HistogramInsertionSort
611 for (CFIndex index(0); index != range.length; ++index)
612 if (offsets[index] != 0)
613 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
614 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
621 /* Apple Bug Fixes {{{ */
622 @implementation UIWebDocumentView (Cydia)
624 - (void) _setScrollerOffset:(CGPoint)offset {
625 UIScroller *scroller([self _scroller]);
627 CGSize size([scroller contentSize]);
628 CGSize bounds([scroller bounds].size);
631 max.x = size.width - bounds.width;
632 max.y = size.height - bounds.height;
640 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
641 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
643 [scroller setOffset:offset];
650 kUIControlEventMouseDown = 1 << 0,
651 kUIControlEventMouseMovedInside = 1 << 2, // mouse moved inside control target
652 kUIControlEventMouseMovedOutside = 1 << 3, // mouse moved outside control target
653 kUIControlEventMouseUpInside = 1 << 6, // mouse up inside control target
654 kUIControlEventMouseUpOutside = 1 << 7, // mouse up outside control target
655 kUIControlAllEvents = (kUIControlEventMouseDown | kUIControlEventMouseMovedInside | kUIControlEventMouseMovedOutside | kUIControlEventMouseUpInside | kUIControlEventMouseUpOutside)
656 } UIControlEventMasks;
658 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
659 size_t length([self length] - state->state);
662 else if (length > count)
664 for (size_t i(0); i != length; ++i)
665 objects[i] = [self item:state->state++];
666 state->itemsPtr = objects;
667 state->mutationsPtr = (unsigned long *) self;
671 @interface NSString (UIKit)
672 - (NSString *) stringByAddingPercentEscapes;
673 - (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
676 @interface NSString (Cydia)
677 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
678 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
679 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
680 - (NSComparisonResult) compareByPath:(NSString *)other;
681 - (NSString *) stringByCachingURLWithCurrentCDN;
682 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
685 @implementation NSString (Cydia)
687 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
688 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
691 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
692 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
693 memcpy(data, bytes, length);
694 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
697 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
698 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
701 - (NSComparisonResult) compareByPath:(NSString *)other {
702 NSString *prefix = [self commonPrefixWithString:other options:0];
703 size_t length = [prefix length];
705 NSRange lrange = NSMakeRange(length, [self length] - length);
706 NSRange rrange = NSMakeRange(length, [other length] - length);
708 lrange = [self rangeOfString:@"/" options:0 range:lrange];
709 rrange = [other rangeOfString:@"/" options:0 range:rrange];
711 NSComparisonResult value;
713 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
714 value = NSOrderedSame;
715 else if (lrange.location == NSNotFound)
716 value = NSOrderedAscending;
717 else if (rrange.location == NSNotFound)
718 value = NSOrderedDescending;
720 value = NSOrderedSame;
722 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
723 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
724 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
725 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
727 NSComparisonResult result = [lpath compare:rpath];
728 return result == NSOrderedSame ? value : result;
731 - (NSString *) stringByCachingURLWithCurrentCDN {
733 stringByReplacingOccurrencesOfString:@"://"
734 withString:@"://ne.edgecastcdn.net/8003A4/"
736 /* XXX: this is somewhat inaccurate */
737 range:NSMakeRange(0, 10)
741 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
742 return [(id)CFURLCreateStringByAddingPercentEscapes(
747 kCFStringEncodingUTF8
753 static inline NSString *CYLocalizeEx(NSString *key, NSString *value = nil) {
754 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:nil];
757 #define CYLocalize(key) CYLocalizeEx(@ key)
765 _finline void clear_() {
771 _finline bool empty() const {
775 _finline size_t size() const {
779 _finline char *data() const {
783 _finline void clear() {
788 _finline CYString() :
795 _finline ~CYString() {
799 void operator =(const CYString &rhs) {
803 if (rhs.cache_ == nil)
806 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
809 void set(apr_pool_t *pool, const char *data, size_t size) {
815 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
816 memcpy(temp, data, size);
823 _finline void set(apr_pool_t *pool, const char *data) {
824 set(pool, data, data == NULL ? 0 : strlen(data));
827 _finline void set(apr_pool_t *pool, const std::string &rhs) {
828 set(pool, rhs.data(), rhs.size());
831 bool operator ==(const CYString &rhs) const {
832 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
835 operator CFStringRef() {
836 if (cache_ == NULL) {
839 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
843 _finline operator id() {
844 return (NSString *) static_cast<CFStringRef>(*this);
849 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
852 struct NSStringMapHash :
853 std::unary_function<NSString *, size_t>
855 _finline size_t operator ()(NSString *value) const {
856 return CFStringHashNSString((CFStringRef) value);
860 struct NSStringMapLess :
861 std::binary_function<NSString *, NSString *, bool>
863 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
864 return [lhs compare:rhs] == NSOrderedAscending;
868 struct NSStringMapEqual :
869 std::binary_function<NSString *, NSString *, bool>
871 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
872 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
873 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
874 //[lhs isEqualToString:rhs];
878 /* Perl-Compatible RegEx {{{ */
888 Pcre(const char *regex) :
893 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
896 lprintf("%d:%s\n", offset, error);
900 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
901 matches_ = new int[(capture_ + 1) * 3];
909 NSString *operator [](size_t match) {
910 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
913 bool operator ()(NSString *data) {
914 // XXX: length is for characters, not for bytes
915 return operator ()([data UTF8String], [data length]);
918 bool operator ()(const char *data, size_t size) {
920 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
924 /* Mime Addresses {{{ */
925 @interface Address : NSObject {
931 - (NSString *) address;
933 - (void) setAddress:(NSString *)address;
935 + (Address *) addressWithString:(NSString *)string;
936 - (Address *) initWithString:(NSString *)string;
939 @implementation Address
948 - (NSString *) name {
952 - (NSString *) address {
956 - (void) setAddress:(NSString *)address {
958 [address_ autorelease];
962 address_ = [address retain];
965 + (Address *) addressWithString:(NSString *)string {
966 return [[[Address alloc] initWithString:string] autorelease];
969 + (NSArray *) _attributeKeys {
970 return [NSArray arrayWithObjects:@"address", @"name", nil];
973 - (NSArray *) attributeKeys {
974 return [[self class] _attributeKeys];
977 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
978 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
981 - (Address *) initWithString:(NSString *)string {
982 if ((self = [super init]) != nil) {
983 const char *data = [string UTF8String];
984 size_t size = [string length];
986 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
988 if (address_r(data, size)) {
989 name_ = [address_r[1] retain];
990 address_ = [address_r[2] retain];
992 name_ = [string retain];
1000 /* CoreGraphics Primitives {{{ */
1011 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
1014 Set(space, red, green, blue, alpha);
1019 CGColorRelease(color_);
1026 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1028 float color[] = {red, green, blue, alpha};
1029 color_ = CGColorCreate(space, color);
1032 operator CGColorRef() {
1038 extern "C" void UISetColor(CGColorRef color);
1040 /* Random Global Variables {{{ */
1041 static const int PulseInterval_ = 50000;
1042 static const int ButtonBarHeight_ = 48;
1043 static const float KeyboardTime_ = 0.3f;
1045 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1046 #define SandboxTemplate_ "/usr/share/sandbox/SandboxTemplate.sb"
1047 #define NotifyConfig_ "/etc/notify.conf"
1049 static bool Queuing_;
1051 static CGColor Blue_;
1052 static CGColor Blueish_;
1053 static CGColor Black_;
1054 static CGColor Off_;
1055 static CGColor White_;
1056 static CGColor Gray_;
1057 static CGColor Green_;
1058 static CGColor Purple_;
1059 static CGColor Purplish_;
1061 static UIColor *InstallingColor_;
1062 static UIColor *RemovingColor_;
1064 static NSString *App_;
1065 static NSString *Home_;
1066 static BOOL Sounds_Keyboard_;
1068 static BOOL Advanced_;
1069 static BOOL Loaded_;
1070 static BOOL Ignored_;
1072 static UIFont *Font12_;
1073 static UIFont *Font12Bold_;
1074 static UIFont *Font14_;
1075 static UIFont *Font18Bold_;
1076 static UIFont *Font22Bold_;
1078 static const char *Machine_ = NULL;
1079 static const NSString *UniqueID_ = nil;
1080 static const NSString *Build_ = nil;
1081 static const NSString *Product_ = nil;
1082 static const NSString *Safari_ = nil;
1084 CFLocaleRef Locale_;
1085 NSArray *Languages_;
1086 CGColorSpaceRef space_;
1091 static NSDictionary *SectionMap_;
1092 static NSMutableDictionary *Metadata_;
1093 static _transient NSMutableDictionary *Settings_;
1094 static _transient NSString *Role_;
1095 static _transient NSMutableDictionary *Packages_;
1096 static _transient NSMutableDictionary *Sections_;
1097 static _transient NSMutableDictionary *Sources_;
1098 static bool Changed_;
1099 static NSDate *now_;
1102 static NSMutableArray *Documents_;
1105 NSString *GetLastUpdate() {
1106 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1109 return CYLocalize("NEVER_OR_UNKNOWN");
1111 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1112 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1114 CFRelease(formatter);
1116 return [(NSString *) formatted autorelease];
1119 /* Display Helpers {{{ */
1120 inline float Interpolate(float begin, float end, float fraction) {
1121 return (end - begin) * fraction + begin;
1124 /* XXX: localize this! */
1125 NSString *SizeString(double size) {
1126 bool negative = size < 0;
1131 while (size > 1024) {
1136 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1138 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1141 static _finline CFStringRef CFCString(const char *value) {
1142 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1145 CFStringRef StripVersion(const char *version) {
1146 const char *colon(strchr(version, ':'));
1148 version = colon + 1;
1149 return CFCString(version);
1152 NSString *LocalizeSection(NSString *section) {
1153 static Pcre title_r("^(.*?) \\((.*)\\)$");
1154 if (title_r(section)) {
1155 NSString *parent(title_r[1]);
1156 NSString *child(title_r[2]);
1158 return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"),
1159 LocalizeSection(parent),
1160 LocalizeSection(child)
1164 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1167 NSString *Simplify(NSString *title) {
1168 const char *data = [title UTF8String];
1169 size_t size = [title length];
1171 static Pcre square_r("^\\[(.*)\\]$");
1172 if (square_r(data, size))
1173 return Simplify(square_r[1]);
1175 static Pcre paren_r("^\\((.*)\\)$");
1176 if (paren_r(data, size))
1177 return Simplify(paren_r[1]);
1179 static Pcre title_r("^(.*?) \\((.*)\\)$");
1180 if (title_r(data, size))
1181 return Simplify(title_r[1]);
1187 bool isSectionVisible(NSString *section) {
1188 NSDictionary *metadata([Sections_ objectForKey:section]);
1189 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1190 return hidden == nil || ![hidden boolValue];
1193 /* Delegate Prototypes {{{ */
1197 @interface NSObject (ProgressDelegate)
1200 @implementation NSObject(ProgressDelegate)
1202 - (void) _setProgressError:(NSArray *)args {
1203 [self performSelector:@selector(setProgressError:forPackage:)
1204 withObject:[args objectAtIndex:0]
1205 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1211 @protocol ProgressDelegate
1212 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1213 - (void) setProgressTitle:(NSString *)title;
1214 - (void) setProgressPercent:(float)percent;
1215 - (void) startProgress;
1216 - (void) addProgressOutput:(NSString *)output;
1217 - (bool) isCancelling:(size_t)received;
1220 @protocol ConfigurationDelegate
1221 - (void) repairWithSelector:(SEL)selector;
1222 - (void) setConfigurationData:(NSString *)data;
1227 @protocol CydiaDelegate
1228 - (void) setPackageView:(PackageView *)view;
1229 - (void) clearPackage:(Package *)package;
1230 - (void) installPackage:(Package *)package;
1231 - (void) removePackage:(Package *)package;
1232 - (void) slideUp:(UIActionSheet *)alert;
1233 - (void) distUpgrade;
1234 - (void) updateData;
1236 - (void) askForSettings;
1237 - (UIProgressHUD *) addProgressHUD;
1238 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1239 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag;
1240 - (RVPage *) pageForPackage:(NSString *)name;
1241 - (void) openMailToURL:(NSURL *)url;
1242 - (void) clearFirstResponder;
1243 - (PackageView *) packageView;
1247 /* Status Delegation {{{ */
1249 public pkgAcquireStatus
1252 _transient NSObject<ProgressDelegate> *delegate_;
1260 void setDelegate(id delegate) {
1261 delegate_ = delegate;
1264 virtual bool MediaChange(std::string media, std::string drive) {
1268 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1271 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1272 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1273 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
1276 virtual void Done(pkgAcquire::ItemDesc &item) {
1279 virtual void Fail(pkgAcquire::ItemDesc &item) {
1281 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1282 item.Owner->Status == pkgAcquire::Item::StatDone
1286 std::string &error(item.Owner->ErrorText);
1290 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1291 NSArray *fields([description componentsSeparatedByString:@" "]);
1292 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1294 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1295 withObject:[NSArray arrayWithObjects:
1296 [NSString stringWithUTF8String:error.c_str()],
1303 virtual bool Pulse(pkgAcquire *Owner) {
1304 bool value = pkgAcquireStatus::Pulse(Owner);
1307 double(CurrentBytes + CurrentItems) /
1308 double(TotalBytes + TotalItems)
1311 [delegate_ setProgressPercent:percent];
1312 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1315 virtual void Start() {
1316 [delegate_ startProgress];
1319 virtual void Stop() {
1323 /* Progress Delegation {{{ */
1328 _transient id<ProgressDelegate> delegate_;
1331 virtual void Update() {
1332 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1333 [delegate_ setProgressPercent:(Percent / 100)];*/
1342 void setDelegate(id delegate) {
1343 delegate_ = delegate;
1346 virtual void Done() {
1347 //[delegate_ setProgressPercent:1];
1352 /* Database Interface {{{ */
1353 typedef std::map< unsigned long, _H<Source> > SourceMap;
1355 @interface Database : NSObject {
1361 pkgCacheFile cache_;
1362 pkgDepCache::Policy *policy_;
1363 pkgRecords *records_;
1364 pkgProblemResolver *resolver_;
1365 pkgAcquire *fetcher_;
1367 SPtr<pkgPackageManager> manager_;
1368 pkgSourceList *list_;
1371 NSMutableArray *packages_;
1373 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1382 + (Database *) sharedInstance;
1385 - (void) _readCydia:(NSNumber *)fd;
1386 - (void) _readStatus:(NSNumber *)fd;
1387 - (void) _readOutput:(NSNumber *)fd;
1391 - (Package *) packageWithName:(NSString *)name;
1393 - (pkgCacheFile &) cache;
1394 - (pkgDepCache::Policy *) policy;
1395 - (pkgRecords *) records;
1396 - (pkgProblemResolver *) resolver;
1397 - (pkgAcquire &) fetcher;
1398 - (pkgSourceList &) list;
1399 - (NSArray *) packages;
1400 - (NSArray *) sources;
1401 - (void) reloadData;
1409 - (void) updateWithStatus:(Status &)status;
1411 - (void) setDelegate:(id)delegate;
1412 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1416 /* Source Class {{{ */
1417 @interface Source : NSObject {
1418 NSString *description_;
1424 NSString *distribution_;
1428 NSString *defaultIcon_;
1430 NSDictionary *record_;
1434 - (Source *) initWithMetaIndex:(metaIndex *)index;
1436 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1438 - (NSString *) supportForPackage:(NSString *)package;
1440 - (NSDictionary *) record;
1444 - (NSString *) distribution;
1445 - (NSString *) type;
1447 - (NSString *) host;
1449 - (NSString *) name;
1450 - (NSString *) description;
1451 - (NSString *) label;
1452 - (NSString *) origin;
1453 - (NSString *) version;
1455 - (NSString *) defaultIcon;
1459 @implementation Source
1461 #define _clear(field) \
1468 _clear(distribution_)
1471 _clear(description_)
1476 _clear(defaultIcon_)
1485 + (NSArray *) _attributeKeys {
1486 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1489 - (NSArray *) attributeKeys {
1490 return [[self class] _attributeKeys];
1493 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1494 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1497 - (void) setMetaIndex:(metaIndex *)index {
1500 trusted_ = index->IsTrusted();
1502 uri_ = [[NSString stringWithUTF8String:index->GetURI().c_str()] retain];
1503 distribution_ = [[NSString stringWithUTF8String:index->GetDist().c_str()] retain];
1504 type_ = [[NSString stringWithUTF8String:index->GetType()] retain];
1506 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1507 if (dindex != NULL) {
1508 std::ifstream release(dindex->MetaIndexFile("Release").c_str());
1510 while (std::getline(release, line)) {
1511 std::string::size_type colon(line.find(':'));
1512 if (colon == std::string::npos)
1515 std::string name(line.substr(0, colon));
1516 std::string value(line.substr(colon + 1));
1517 while (!value.empty() && value[0] == ' ')
1518 value = value.substr(1);
1520 if (name == "Default-Icon")
1521 defaultIcon_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1522 else if (name == "Description")
1523 description_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1524 else if (name == "Label")
1525 label_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1526 else if (name == "Origin")
1527 origin_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1528 else if (name == "Support")
1529 support_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1530 else if (name == "Version")
1531 version_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1535 record_ = [Sources_ objectForKey:[self key]];
1537 record_ = [record_ retain];
1540 - (Source *) initWithMetaIndex:(metaIndex *)index {
1541 if ((self = [super init]) != nil) {
1542 [self setMetaIndex:index];
1546 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1547 NSDictionary *lhr = [self record];
1548 NSDictionary *rhr = [source record];
1551 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1553 NSString *lhs = [self name];
1554 NSString *rhs = [source name];
1556 if ([lhs length] != 0 && [rhs length] != 0) {
1557 unichar lhc = [lhs characterAtIndex:0];
1558 unichar rhc = [rhs characterAtIndex:0];
1560 if (isalpha(lhc) && !isalpha(rhc))
1561 return NSOrderedAscending;
1562 else if (!isalpha(lhc) && isalpha(rhc))
1563 return NSOrderedDescending;
1566 return [lhs compare:rhs options:LaxCompareOptions_];
1569 - (NSString *) supportForPackage:(NSString *)package {
1570 return support_ == nil ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1573 - (NSDictionary *) record {
1581 - (NSString *) uri {
1585 - (NSString *) distribution {
1586 return distribution_;
1589 - (NSString *) type {
1593 - (NSString *) key {
1594 return [NSString stringWithFormat:@"%@:%@:%@", type_, uri_, distribution_];
1597 - (NSString *) host {
1598 return [[[NSURL URLWithString:[self uri]] host] lowercaseString];
1601 - (NSString *) name {
1602 return origin_ == nil ? [self host] : origin_;
1605 - (NSString *) description {
1606 return description_;
1609 - (NSString *) label {
1610 return label_ == nil ? [self host] : label_;
1613 - (NSString *) origin {
1617 - (NSString *) version {
1621 - (NSString *) defaultIcon {
1622 return defaultIcon_;
1627 /* Relationship Class {{{ */
1628 @interface Relationship : NSObject {
1633 - (NSString *) type;
1635 - (NSString *) name;
1639 @implementation Relationship
1647 - (NSString *) type {
1655 - (NSString *) name {
1662 /* Package Class {{{ */
1663 @interface Package : NSObject {
1667 pkgCache::VerIterator version_;
1668 pkgCache::PkgIterator iterator_;
1669 _transient Database *database_;
1670 pkgCache::VerFileIterator file_;
1677 NSString *section$_;
1682 NSString *installed_;
1688 CYString depiction_;
1698 NSMutableArray *tags_;
1701 NSArray *relationships_;
1703 NSMutableDictionary *metadata_;
1704 _transient NSDate *firstSeen_;
1705 _transient NSDate *lastSeen_;
1709 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1710 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1712 - (pkgCache::PkgIterator) iterator;
1715 - (NSString *) section;
1716 - (NSString *) simpleSection;
1718 - (NSString *) longSection;
1719 - (NSString *) shortSection;
1723 - (Address *) maintainer;
1725 - (NSString *) longDescription;
1726 - (NSString *) shortDescription;
1729 - (NSMutableDictionary *) metadata;
1731 - (BOOL) subscribed;
1734 - (NSString *) latest;
1735 - (NSString *) installed;
1738 - (BOOL) upgradableAndEssential:(BOOL)essential;
1741 - (BOOL) unfiltered;
1745 - (BOOL) halfConfigured;
1746 - (BOOL) halfInstalled;
1748 - (NSString *) mode;
1751 - (NSString *) name;
1753 - (NSString *) homepage;
1754 - (NSString *) depiction;
1755 - (Address *) author;
1757 - (NSString *) support;
1759 - (NSArray *) files;
1760 - (NSArray *) relationships;
1761 - (NSArray *) warnings;
1762 - (NSArray *) applications;
1764 - (Source *) source;
1765 - (NSString *) role;
1767 - (BOOL) matches:(NSString *)text;
1769 - (bool) hasSupportingRole;
1770 - (BOOL) hasTag:(NSString *)tag;
1771 - (NSString *) primaryPurpose;
1772 - (NSArray *) purposes;
1773 - (bool) isCommercial;
1775 - (CYString &) cyname;
1777 - (uint32_t) compareBySection:(NSArray *)sections;
1779 - (uint32_t) compareForChanges;
1784 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1785 - (bool) isInstalledAndVisible:(NSNumber *)number;
1786 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1787 - (bool) isVisibleInSource:(Source *)source;
1791 uint32_t PackageChangesRadix(Package *self, void *) {
1796 uint32_t timestamp : 30;
1797 uint32_t ignored : 1;
1798 uint32_t upgradable : 1;
1802 bool upgradable([self upgradableAndEssential:YES]);
1803 value.bits.upgradable = upgradable ? 1 : 0;
1806 value.bits.timestamp = 0;
1807 value.bits.ignored = [self ignored] ? 0 : 1;
1808 value.bits.upgradable = 1;
1810 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1811 value.bits.ignored = 0;
1812 value.bits.upgradable = 0;
1815 return _not(uint32_t) - value.key;
1818 _finline static void Stifle(uint8_t &value) {
1821 uint32_t PackagePrefixRadix(Package *self, void *context) {
1822 size_t offset(reinterpret_cast<size_t>(context));
1823 CYString &name([self cyname]);
1825 size_t size(name.size());
1828 char *text(name.data());
1831 if (!isdigit(text[0]))
1835 while (size != digits && isdigit(text[digits]))
1845 if (offset == 0 && zeros != 0) {
1846 memset(data, '0', zeros);
1847 memcpy(data + zeros, text, 4 - zeros);
1849 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1850 if (size <= offset - zeros)
1853 text += offset - zeros;
1854 size -= offset - zeros;
1857 memcpy(data, text, 4);
1859 memcpy(data, text, size);
1860 memset(data + size, 0, 4 - size);
1863 for (size_t i(0); i != 4; ++i)
1864 if (isalpha(data[i]))
1869 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1871 /* XXX: ntohl may be more honest */
1872 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1875 CYString &(*PackageName)(Package *self, SEL sel);
1877 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1878 _profile(PackageNameCompare)
1879 CYString &lhi(PackageName(lhs, @selector(cyname)));
1880 CYString &rhi(PackageName(rhs, @selector(cyname)));
1881 CFStringRef lhn(lhi), rhn(rhi);
1883 _profile(PackageNameCompare$NumbersLast)
1884 if (!lhi.empty() && !rhi.empty()) {
1885 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1886 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1887 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1888 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1889 return lha ? NSOrderedAscending : NSOrderedDescending;
1893 CFIndex length = CFStringGetLength(lhn);
1895 _profile(PackageNameCompare$Compare)
1896 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1901 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1902 return PackageNameCompare(*lhs, *rhs, context);
1905 struct PackageNameOrdering :
1906 std::binary_function<Package *, Package *, bool>
1908 _finline bool operator ()(Package *lhs, Package *rhs) const {
1909 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1913 @implementation Package
1915 - (NSString *) description {
1916 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1922 if (section$_ != nil)
1923 [section$_ release];
1927 if (installed_ != nil)
1928 [installed_ release];
1930 if (sponsor$_ != nil)
1931 [sponsor$_ release];
1932 if (author$_ != nil)
1939 if (relationships_ != nil)
1940 [relationships_ release];
1941 if (metadata_ != nil)
1942 [metadata_ release];
1947 + (NSString *) webScriptNameForSelector:(SEL)selector {
1948 if (selector == @selector(hasTag:))
1954 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1955 return [self webScriptNameForSelector:selector] == nil;
1958 + (NSArray *) _attributeKeys {
1959 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];
1962 - (NSArray *) attributeKeys {
1963 return [[self class] _attributeKeys];
1966 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1967 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1977 _profile(Package$parse)
1978 pkgRecords::Parser *parser;
1980 _profile(Package$parse$Lookup)
1981 parser = &[database_ records]->Lookup(file_);
1986 _profile(Package$parse$Find)
1992 {"depiction", &depiction_},
1993 {"homepage", &homepage_},
1994 {"website", &website},
1995 {"support", &support_},
1996 {"sponsor", &sponsor_},
1997 {"author", &author_},
2000 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2001 const char *start, *end;
2003 if (parser->Find(names[i].name_, start, end)) {
2004 CYString &value(*names[i].value_);
2005 _profile(Package$parse$Value)
2006 value.set(pool_, start, end - start);
2012 _profile(Package$parse$Tagline)
2013 const char *start, *end;
2014 if (parser->ShortDesc(start, end)) {
2015 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2018 while (stop != start && stop[-1] == '\r')
2020 tagline_.set(pool_, start, stop - start);
2024 _profile(Package$parse$Retain)
2025 if (!homepage_.empty())
2026 homepage_ = website;
2027 if (homepage_ == depiction_)
2033 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2034 if ((self = [super init]) != nil) {
2035 _profile(Package$initWithVersion)
2036 @synchronized (database) {
2037 era_ = [database era];
2041 iterator_ = version.ParentPkg();
2042 database_ = database;
2044 _profile(Package$initWithVersion$Latest)
2045 latest_ = (NSString *) StripVersion(version_.VerStr());
2048 pkgCache::VerIterator current;
2049 _profile(Package$initWithVersion$Versions)
2050 current = iterator_.CurrentVer();
2052 installed_ = (NSString *) StripVersion(current.VerStr());
2054 if (!version_.end())
2055 file_ = version_.FileList();
2057 pkgCache &cache([database_ cache]);
2058 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2062 _profile(Package$initWithVersion$Name)
2063 id_.set(pool_, iterator_.Name());
2064 name_.set(pool, iterator_.Display());
2068 _profile(Package$initWithVersion$Source)
2069 source_ = [database_ getSource:file_.File()];
2076 _profile(Package$initWithVersion$Tags)
2077 pkgCache::TagIterator tag(iterator_.TagList());
2079 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2081 const char *name(tag.Name());
2082 [tags_ addObject:(NSString *)CFCString(name)];
2083 if (role_ == nil && strncmp(name, "role::", 6) == 0)
2084 role_ = (NSString *) CFCString(name + 6);
2086 } while (!tag.end());
2090 bool changed(false);
2091 NSString *key([id_ lowercaseString]);
2093 _profile(Package$initWithVersion$Metadata)
2094 metadata_ = [Packages_ objectForKey:key];
2096 if (metadata_ == nil) {
2099 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2100 firstSeen_, @"FirstSeen",
2101 latest_, @"LastVersion",
2106 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2107 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2109 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2110 subscribed_ = [subscribed boolValue];
2112 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2114 if (firstSeen_ == nil) {
2115 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2116 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2120 if (version == nil) {
2121 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2123 } else if (![version isEqualToString:latest_]) {
2124 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2126 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2131 metadata_ = [metadata_ retain];
2134 [Packages_ setObject:metadata_ forKey:key];
2139 _profile(Package$initWithVersion$Section)
2140 section_.set(pool_, iterator_.Section());
2143 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2144 visible_ = [self hasSupportingRole] && [self unfiltered];
2145 } _end } return self;
2148 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2149 pkgCache::VerIterator version;
2151 _profile(Package$packageWithIterator$GetCandidateVer)
2152 version = [database policy]->GetCandidateVer(iterator);
2158 return [[[Package alloc]
2159 initWithVersion:version
2166 - (pkgCache::PkgIterator) iterator {
2170 - (NSString *) section {
2171 if (section$_ == nil) {
2172 if (section_.empty())
2175 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2176 NSString *name(section_);
2179 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2180 if (NSString *rename = [value objectForKey:@"Rename"]) {
2185 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2189 - (NSString *) simpleSection {
2190 if (NSString *section = [self section])
2191 return Simplify(section);
2196 - (NSString *) longSection {
2197 return LocalizeSection(section_);
2200 - (NSString *) shortSection {
2201 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2204 - (NSString *) uri {
2207 pkgIndexFile *index;
2208 pkgCache::PkgFileIterator file(file_.File());
2209 if (![database_ list].FindIndex(file, index))
2211 return [NSString stringWithUTF8String:iterator_->Path];
2212 //return [NSString stringWithUTF8String:file.Site()];
2213 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2217 - (Address *) maintainer {
2220 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2221 const std::string &maintainer(parser->Maintainer());
2222 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2226 return version_.end() ? 0 : version_->InstalledSize;
2229 - (NSString *) longDescription {
2232 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2233 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2235 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2236 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2237 if ([lines count] < 2)
2240 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2241 for (size_t i(1), e([lines count]); i != e; ++i) {
2242 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2243 [trimmed addObject:trim];
2246 return [trimmed componentsJoinedByString:@"\n"];
2249 - (NSString *) shortDescription {
2254 _profile(Package$index)
2255 CFStringRef name((CFStringRef) [self name]);
2256 if (CFStringGetLength(name) == 0)
2258 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2259 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2261 return toupper(character);
2265 - (NSMutableDictionary *) metadata {
2270 if (subscribed_ && lastSeen_ != nil)
2275 - (BOOL) subscribed {
2280 NSDictionary *metadata([self metadata]);
2281 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2282 return [ignored boolValue];
2287 - (NSString *) latest {
2291 - (NSString *) installed {
2296 return !version_.end();
2299 - (BOOL) upgradableAndEssential:(BOOL)essential {
2300 _profile(Package$upgradableAndEssential)
2301 pkgCache::VerIterator current(iterator_.CurrentVer());
2303 return essential && essential_ && visible_;
2305 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2309 - (BOOL) essential {
2314 return [database_ cache][iterator_].InstBroken();
2317 - (BOOL) unfiltered {
2318 NSString *section([self section]);
2319 return section == nil || isSectionVisible(section);
2327 unsigned char current(iterator_->CurrentState);
2328 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2331 - (BOOL) halfConfigured {
2332 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2335 - (BOOL) halfInstalled {
2336 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2340 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2341 return state.Mode != pkgDepCache::ModeKeep;
2344 - (NSString *) mode {
2345 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2347 switch (state.Mode) {
2348 case pkgDepCache::ModeDelete:
2349 if ((state.iFlags & pkgDepCache::Purge) != 0)
2353 case pkgDepCache::ModeKeep:
2354 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2355 return @"REINSTALL";
2356 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2360 case pkgDepCache::ModeInstall:
2361 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2362 return @"REINSTALL";
2363 else*/ switch (state.Status) {
2365 return @"DOWNGRADE";
2371 return @"NEW_INSTALL";
2384 - (NSString *) name {
2385 return name_.empty() ? id_ : name_;
2388 - (UIImage *) icon {
2389 NSString *section = [self simpleSection];
2393 if ([icon_ hasPrefix:@"file:///"])
2394 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2395 if (icon == nil) if (section != nil)
2396 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2397 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2398 if ([dicon hasPrefix:@"file:///"])
2399 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2401 icon = [UIImage applicationImageNamed:@"unknown.png"];
2405 - (NSString *) homepage {
2409 - (NSString *) depiction {
2413 - (Address *) sponsor {
2414 if (sponsor$_ == nil) {
2415 if (sponsor_.empty())
2417 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2421 - (Address *) author {
2422 if (author$_ == nil) {
2423 if (author_.empty())
2425 author$_ = [[Address addressWithString:author_] retain];
2429 - (NSString *) support {
2430 return !support_.empty() ? support_ : [[self source] supportForPackage:id_];
2433 - (NSArray *) files {
2434 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2435 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2438 fin.open([path UTF8String]);
2443 while (std::getline(fin, line))
2444 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2449 - (NSArray *) relationships {
2450 return relationships_;
2453 - (NSArray *) warnings {
2454 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2455 const char *name(iterator_.Name());
2457 size_t length(strlen(name));
2458 if (length < 2) invalid:
2459 [warnings addObject:CYLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2460 else for (size_t i(0); i != length; ++i)
2462 /* XXX: technically this is not allowed */
2463 (name[i] < 'A' || name[i] > 'Z') &&
2464 (name[i] < 'a' || name[i] > 'z') &&
2465 (name[i] < '0' || name[i] > '9') &&
2466 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2469 if (strcmp(name, "cydia") != 0) {
2471 bool _private = false;
2474 bool repository = [[self section] isEqualToString:@"Repositories"];
2476 if (NSArray *files = [self files])
2477 for (NSString *file in files)
2478 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2480 else if (!_private && [file isEqualToString:@"/private"])
2482 else if (!stash && [file isEqualToString:@"/var/stash"])
2485 /* XXX: this is not sensitive enough. only some folders are valid. */
2486 if (cydia && !repository)
2487 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2489 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/private"]];
2491 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2494 return [warnings count] == 0 ? nil : warnings;
2497 - (NSArray *) applications {
2498 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2500 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2502 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2503 if (NSArray *files = [self files])
2504 for (NSString *file in files)
2505 if (application_r(file)) {
2506 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2507 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2508 if ([id isEqualToString:me])
2511 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2513 display = application_r[1];
2515 NSString *bundle([file stringByDeletingLastPathComponent]);
2516 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2517 if (icon == nil || [icon length] == 0)
2519 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2521 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2522 [applications addObject:application];
2524 [application addObject:id];
2525 [application addObject:display];
2526 [application addObject:url];
2529 return [applications count] == 0 ? nil : applications;
2532 - (Source *) source {
2534 @synchronized (database_) {
2535 if ([database_ era] != era_ || file_.end())
2538 source_ = [database_ getSource:file_.File()];
2550 - (NSString *) role {
2554 - (BOOL) matches:(NSString *)text {
2560 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2561 if (range.location != NSNotFound)
2564 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2565 if (range.location != NSNotFound)
2568 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2569 if (range.location != NSNotFound)
2575 - (bool) hasSupportingRole {
2578 if ([role_ isEqualToString:@"enduser"])
2580 if ([Role_ isEqualToString:@"User"])
2582 if ([role_ isEqualToString:@"hacker"])
2584 if ([Role_ isEqualToString:@"Hacker"])
2586 if ([role_ isEqualToString:@"developer"])
2588 if ([Role_ isEqualToString:@"Developer"])
2593 - (BOOL) hasTag:(NSString *)tag {
2594 return tags_ == nil ? NO : [tags_ containsObject:tag];
2597 - (NSString *) primaryPurpose {
2598 for (NSString *tag in tags_)
2599 if ([tag hasPrefix:@"purpose::"])
2600 return [tag substringFromIndex:9];
2604 - (NSArray *) purposes {
2605 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2606 for (NSString *tag in tags_)
2607 if ([tag hasPrefix:@"purpose::"])
2608 [purposes addObject:[tag substringFromIndex:9]];
2609 return [purposes count] == 0 ? nil : purposes;
2612 - (bool) isCommercial {
2613 return [self hasTag:@"cydia::commercial"];
2616 - (CYString &) cyname {
2617 return name_.empty() ? id_ : name_;
2620 - (uint32_t) compareBySection:(NSArray *)sections {
2621 NSString *section([self section]);
2622 for (size_t i(0), e([sections count]); i != e; ++i) {
2623 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2627 return _not(uint32_t);
2630 - (uint32_t) compareForChanges {
2635 uint32_t timestamp : 30;
2636 uint32_t ignored : 1;
2637 uint32_t upgradable : 1;
2641 bool upgradable([self upgradableAndEssential:YES]);
2642 value.bits.upgradable = upgradable ? 1 : 0;
2645 value.bits.timestamp = 0;
2646 value.bits.ignored = [self ignored] ? 0 : 1;
2647 value.bits.upgradable = 1;
2649 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2650 value.bits.ignored = 0;
2651 value.bits.upgradable = 0;
2654 return _not(uint32_t) - value.key;
2658 pkgProblemResolver *resolver = [database_ resolver];
2659 resolver->Clear(iterator_);
2660 resolver->Protect(iterator_);
2664 pkgProblemResolver *resolver = [database_ resolver];
2665 resolver->Clear(iterator_);
2666 resolver->Protect(iterator_);
2667 pkgCacheFile &cache([database_ cache]);
2668 cache->MarkInstall(iterator_, false);
2669 pkgDepCache::StateCache &state((*cache)[iterator_]);
2670 if (!state.Install())
2671 cache->SetReInstall(iterator_, true);
2675 pkgProblemResolver *resolver = [database_ resolver];
2676 resolver->Clear(iterator_);
2677 resolver->Protect(iterator_);
2678 resolver->Remove(iterator_);
2679 [database_ cache]->MarkDelete(iterator_, true);
2682 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2683 _profile(Package$isUnfilteredAndSearchedForBy)
2686 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2687 value &= [self unfiltered];
2690 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2691 value &= [self matches:search];
2698 - (bool) isInstalledAndVisible:(NSNumber *)number {
2699 return (![number boolValue] || [self visible]) && [self installed] != nil;
2702 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2703 NSString *section = [self section];
2707 [self installed] == nil && (
2709 section == nil && [name length] == 0 ||
2710 [name isEqualToString:section]
2714 - (bool) isVisibleInSource:(Source *)source {
2715 return [self source] == source && [self visible];
2720 /* Section Class {{{ */
2721 @interface Section : NSObject {
2726 NSString *localized_;
2729 - (NSComparisonResult) compareByLocalized:(Section *)section;
2730 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2731 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2732 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2733 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2734 - (NSString *) name;
2741 - (void) addToCount;
2743 - (void) setCount:(size_t)count;
2744 - (NSString *) localized;
2748 @implementation Section
2752 if (localized_ != nil)
2753 [localized_ release];
2757 - (NSComparisonResult) compareByLocalized:(Section *)section {
2758 NSString *lhs(localized_);
2759 NSString *rhs([section localized]);
2761 /*if ([lhs length] != 0 && [rhs length] != 0) {
2762 unichar lhc = [lhs characterAtIndex:0];
2763 unichar rhc = [rhs characterAtIndex:0];
2765 if (isalpha(lhc) && !isalpha(rhc))
2766 return NSOrderedAscending;
2767 else if (!isalpha(lhc) && isalpha(rhc))
2768 return NSOrderedDescending;
2771 return [lhs compare:rhs options:LaxCompareOptions_];
2774 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2775 if ((self = [self initWithName:name localize:NO]) != nil) {
2776 if (localized != nil)
2777 localized_ = [localized retain];
2781 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2782 return [self initWithName:name row:0 localize:localize];
2785 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2786 if ((self = [super init]) != nil) {
2787 name_ = [name retain];
2791 localized_ = [LocalizeSection(name_) retain];
2795 /* XXX: localize the index thingees */
2796 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2797 if ((self = [super init]) != nil) {
2798 name_ = [(index == '#' ? @"123" : [NSString stringWithCharacters:&index length:1]) retain];
2804 - (NSString *) name {
2824 - (void) addToCount {
2828 - (void) setCount:(size_t)count {
2832 - (NSString *) localized {
2840 static NSArray *Finishes_;
2842 /* Database Implementation {{{ */
2843 @implementation Database
2845 + (Database *) sharedInstance {
2846 static Database *instance;
2847 if (instance == nil)
2848 instance = [[Database alloc] init];
2858 NSRecycleZone(zone_);
2859 // XXX: malloc_destroy_zone(zone_);
2860 apr_pool_destroy(pool_);
2864 - (void) _readCydia:(NSNumber *)fd { _pooled
2865 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2866 std::istream is(&ib);
2869 static Pcre finish_r("^finish:([^:]*)$");
2871 while (std::getline(is, line)) {
2872 const char *data(line.c_str());
2873 size_t size = line.size();
2874 lprintf("C:%s\n", data);
2876 if (finish_r(data, size)) {
2877 NSString *finish = finish_r[1];
2878 int index = [Finishes_ indexOfObject:finish];
2879 if (index != INT_MAX && index > Finish_)
2887 - (void) _readStatus:(NSNumber *)fd { _pooled
2888 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2889 std::istream is(&ib);
2892 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2893 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2895 while (std::getline(is, line)) {
2896 const char *data(line.c_str());
2897 size_t size = line.size();
2898 lprintf("S:%s\n", data);
2900 if (conffile_r(data, size)) {
2901 [delegate_ setConfigurationData:conffile_r[1]];
2902 } else if (strncmp(data, "status: ", 8) == 0) {
2903 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2904 [delegate_ setProgressTitle:string];
2905 } else if (pmstatus_r(data, size)) {
2906 std::string type([pmstatus_r[1] UTF8String]);
2907 NSString *id = pmstatus_r[2];
2909 float percent([pmstatus_r[3] floatValue]);
2910 [delegate_ setProgressPercent:(percent / 100)];
2912 NSString *string = pmstatus_r[4];
2914 if (type == "pmerror")
2915 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2916 withObject:[NSArray arrayWithObjects:string, id, nil]
2919 else if (type == "pmstatus") {
2920 [delegate_ setProgressTitle:string];
2921 } else if (type == "pmconffile")
2922 [delegate_ setConfigurationData:string];
2923 else _assert(false);
2924 } else _assert(false);
2930 - (void) _readOutput:(NSNumber *)fd { _pooled
2931 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2932 std::istream is(&ib);
2935 while (std::getline(is, line)) {
2936 lprintf("O:%s\n", line.c_str());
2937 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2947 - (Package *) packageWithName:(NSString *)name {
2948 if (static_cast<pkgDepCache *>(cache_) == NULL)
2950 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
2951 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
2954 - (Database *) init {
2955 if ((self = [super init]) != nil) {
2962 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
2963 apr_pool_create(&pool_, NULL);
2965 packages_ = [[NSMutableArray alloc] init];
2969 _assert(pipe(fds) != -1);
2972 _config->Set("APT::Keep-Fds::", cydiafd_);
2973 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
2976 detachNewThreadSelector:@selector(_readCydia:)
2978 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2981 _assert(pipe(fds) != -1);
2985 detachNewThreadSelector:@selector(_readStatus:)
2987 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2990 _assert(pipe(fds) != -1);
2991 _assert(dup2(fds[0], 0) != -1);
2992 _assert(close(fds[0]) != -1);
2994 input_ = fdopen(fds[1], "a");
2996 _assert(pipe(fds) != -1);
2997 _assert(dup2(fds[1], 1) != -1);
2998 _assert(close(fds[1]) != -1);
3001 detachNewThreadSelector:@selector(_readOutput:)
3003 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3008 - (pkgCacheFile &) cache {
3012 - (pkgDepCache::Policy *) policy {
3016 - (pkgRecords *) records {
3020 - (pkgProblemResolver *) resolver {
3024 - (pkgAcquire &) fetcher {
3028 - (pkgSourceList &) list {
3032 - (NSArray *) packages {
3036 - (NSArray *) sources {
3037 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3038 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3039 [sources addObject:i->second];
3043 - (NSArray *) issues {
3044 if (cache_->BrokenCount() == 0)
3047 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3049 for (Package *package in packages_) {
3050 if (![package broken])
3052 pkgCache::PkgIterator pkg([package iterator]);
3054 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3055 [entry addObject:[package name]];
3056 [issues addObject:entry];
3058 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3062 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3063 pkgCache::DepIterator start;
3064 pkgCache::DepIterator end;
3065 dep.GlobOr(start, end); // ++dep
3067 if (!cache_->IsImportantDep(end))
3069 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3072 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3073 [entry addObject:failure];
3074 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3076 Package *package([self packageWithName:[NSString stringWithUTF8String:start.TargetPkg().Name()]]);
3077 [failure addObject:[package name]];
3079 pkgCache::PkgIterator target(start.TargetPkg());
3080 if (target->ProvidesList != 0)
3081 [failure addObject:@"?"];
3083 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3085 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3086 else if (!cache_[target].CandidateVerIter(cache_).end())
3087 [failure addObject:@"-"];
3088 else if (target->ProvidesList == 0)
3089 [failure addObject:@"!"];
3091 [failure addObject:@"%"];
3095 if (start.TargetVer() != 0)
3096 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3107 - (void) reloadData { _pooled
3108 @synchronized (self) {
3112 [packages_ removeAllObjects];
3138 apr_pool_clear(pool_);
3139 NSRecycleZone(zone_);
3141 int chk(creat("/tmp/cydia.chk", 0644));
3146 if (!cache_.Open(progress_, true)) {
3148 if (!_error->PopMessage(error))
3151 lprintf("cache_.Open():[%s]\n", error.c_str());
3153 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3154 [delegate_ repairWithSelector:@selector(configure)];
3155 else if (error == "The package lists or status file could not be parsed or opened.")
3156 [delegate_ repairWithSelector:@selector(update)];
3157 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3158 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3159 // else if (error == "The list of sources could not be read.")
3160 else _assert(false);
3166 unlink("/tmp/cydia.chk");
3168 now_ = [[NSDate date] retain];
3170 policy_ = new pkgDepCache::Policy();
3171 records_ = new pkgRecords(cache_);
3172 resolver_ = new pkgProblemResolver(cache_);
3173 fetcher_ = new pkgAcquire(&status_);
3176 list_ = new pkgSourceList();
3177 _assert(list_->ReadMainList());
3179 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3180 _assert(pkgApplyStatus(cache_));
3182 if (cache_->BrokenCount() != 0) {
3183 _assert(pkgFixBroken(cache_));
3184 _assert(cache_->BrokenCount() == 0);
3185 _assert(pkgMinimizeUpgrade(cache_));
3190 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3191 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3192 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3193 // XXX: this could be more intelligent
3194 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3195 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3197 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source] autorelease];
3204 /*std::vector<Package *> packages;
3205 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3206 [packages_ release];
3211 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3212 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3213 //packages.push_back(package);
3214 [packages_ addObject:package];
3218 /*if (packages.empty())
3219 packages_ = [[NSArray alloc] init];
3221 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3224 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3225 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3226 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3234 /*if (!packages.empty())
3235 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3236 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3238 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3240 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3242 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3248 - (void) configure {
3249 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3250 system([dpkg UTF8String]);
3258 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3259 _assert(!_error->PendingError());
3262 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3265 public pkgArchiveCleaner
3268 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3273 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3275 while (_error->PopMessage(error))
3276 lprintf("ArchiveCleaner: %s\n", error.c_str());
3281 pkgRecords records(cache_);
3283 lock_ = new FileFd();
3284 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3285 _assert(!_error->PendingError());
3288 // XXX: explain this with an error message
3289 _assert(list.ReadMainList());
3291 manager_ = (_system->CreatePM(cache_));
3292 _assert(manager_->GetArchives(fetcher_, &list, &records));
3293 _assert(!_error->PendingError());
3297 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3299 _assert(list.ReadMainList());
3300 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3301 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3304 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3309 bool failed = false;
3310 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3311 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3314 std::string uri = (*item)->DescURI();
3315 std::string error = (*item)->ErrorText;
3317 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3320 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3321 withObject:[NSArray arrayWithObjects:
3322 [NSString stringWithUTF8String:error.c_str()],
3334 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3336 if (_error->PendingError()) {
3341 if (result == pkgPackageManager::Failed) {
3346 if (result != pkgPackageManager::Completed) {
3351 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3353 _assert(list.ReadMainList());
3354 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3355 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3358 if (![before isEqualToArray:after])
3363 _assert(pkgDistUpgrade(cache_));
3367 [self updateWithStatus:status_];
3370 - (void) updateWithStatus:(Status &)status {
3372 _assert(list.ReadMainList());
3375 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3376 _assert(!_error->PendingError());
3378 pkgAcquire fetcher(&status);
3379 _assert(list.GetIndexes(&fetcher));
3381 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3382 bool failed = false;
3383 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3384 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3385 (*item)->Finished();
3389 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3390 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3391 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3394 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3399 - (void) setDelegate:(id)delegate {
3400 delegate_ = delegate;
3401 status_.setDelegate(delegate);
3402 progress_.setDelegate(delegate);
3405 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3406 return sources_[file->ID];
3412 /* PopUp Windows {{{ */
3413 @interface PopUpView : UIView {
3414 _transient id delegate_;
3415 UITransitionView *transition_;
3420 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3424 @implementation PopUpView
3427 [transition_ setDelegate:nil];
3428 [transition_ release];
3434 [transition_ transition:UITransitionPushFromTop toView:nil];
3437 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3438 if (from != nil && to == nil)
3439 [self removeFromSuperview];
3442 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3443 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3444 delegate_ = delegate;
3446 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3447 [self addSubview:transition_];
3449 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3451 [view addSubview:self];
3453 [transition_ setDelegate:self];
3455 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3456 [transition_ transition:UITransitionNone toView:blank];
3457 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3465 /* Mail Composition {{{ */
3466 @interface MailToView : PopUpView {
3467 MailComposeController *controller_;
3470 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
3474 @implementation MailToView
3477 [controller_ release];
3481 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
3485 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
3486 NSLog(@"did:%@", delivery);
3487 // [UIApp setStatusBarShowsProgress:NO];
3488 if ([controller error]){
3489 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3490 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3491 [mailAlertSheet setBodyText:[controller error]];
3492 [mailAlertSheet popupAlertAnimated:YES];
3496 - (void) showError {
3497 NSLog(@"%@", [controller_ error]);
3498 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3499 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3500 [mailAlertSheet setBodyText:[controller_ error]];
3501 [mailAlertSheet popupAlertAnimated:YES];
3504 - (void) deliverMessage { _pooled
3508 if (![controller_ deliverMessage])
3509 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
3512 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
3513 if ([controller_ needsDelivery])
3514 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
3519 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
3520 if ((self = [super initWithView:view delegate:delegate]) != nil) {
3521 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
3522 [controller_ setDelegate:self];
3523 [controller_ initializeUI];
3524 [controller_ setupForURL:url];
3526 UIView *view([controller_ view]);
3527 [overlay_ addSubview:view];
3535 /* Confirmation View {{{ */
3536 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3537 if (!iterator.end())
3538 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3539 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3541 pkgCache::PkgIterator package(dep.TargetPkg());
3544 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3551 @protocol ConfirmationViewDelegate
3557 @interface ConfirmationView : BrowserView {
3558 _transient Database *database_;
3559 UIActionSheet *essential_;
3566 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3570 @implementation ConfirmationView
3577 if (essential_ != nil)
3578 [essential_ release];
3584 [book_ popFromSuperviewAnimated:YES];
3587 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3588 NSString *context([sheet context]);
3590 if ([context isEqualToString:@"remove"]) {
3598 [delegate_ confirm];
3605 } else if ([context isEqualToString:@"unable"]) {
3609 [super alertSheet:sheet buttonClicked:button];
3612 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3613 [super webView:sender didClearWindowObject:window forFrame:frame];
3614 [window setValue:changes_ forKey:@"changes"];
3615 [window setValue:issues_ forKey:@"issues"];
3616 [window setValue:sizes_ forKey:@"sizes"];
3619 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3620 if ((self = [super initWithBook:book]) != nil) {
3621 database_ = database;
3623 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3624 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3625 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3626 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3627 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3631 pkgDepCache::Policy *policy([database_ policy]);
3633 pkgCacheFile &cache([database_ cache]);
3634 NSArray *packages = [database_ packages];
3635 for (Package *package in packages) {
3636 pkgCache::PkgIterator iterator = [package iterator];
3637 pkgDepCache::StateCache &state(cache[iterator]);
3639 NSString *name([package name]);
3641 if (state.NewInstall())
3642 [installing addObject:name];
3643 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3644 [reinstalling addObject:name];
3645 else if (state.Upgrade())
3646 [upgrading addObject:name];
3647 else if (state.Downgrade())
3648 [downgrading addObject:name];
3649 else if (state.Delete()) {
3650 if ([package essential])
3652 [removing addObject:name];
3655 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3656 substrate_ |= DepSubstrate(iterator.CurrentVer());
3661 else if (Advanced_ || true) {
3662 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
3664 essential_ = [[UIActionSheet alloc]
3665 initWithTitle:CYLocalize("REMOVING_ESSENTIALS")
3666 buttons:[NSArray arrayWithObjects:
3667 [NSString stringWithFormat:parenthetical, CYLocalize("CANCEL_OPERATION"), CYLocalize("SAFE")],
3668 [NSString stringWithFormat:parenthetical, CYLocalize("FORCE_REMOVAL"), CYLocalize("UNSAFE")],
3670 defaultButtonIndex:0
3676 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3678 [essential_ setBodyText:CYLocalize("REMOVING_ESSENTIALS_EX")];
3680 essential_ = [[UIActionSheet alloc]
3681 initWithTitle:CYLocalize("UNABLE_TO_COMPLY")
3682 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3683 defaultButtonIndex:0
3688 [essential_ setBodyText:CYLocalize("UNABLE_TO_COMPLY_EX")];
3691 changes_ = [[NSArray alloc] initWithObjects:
3699 issues_ = [database_ issues];
3701 issues_ = [issues_ retain];
3703 sizes_ = [[NSArray alloc] initWithObjects:
3704 SizeString([database_ fetcher].FetchNeeded()),
3705 SizeString([database_ fetcher].PartialPresent()),
3706 SizeString([database_ cache]->UsrSize()),
3709 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3713 - (NSString *) backButtonTitle {
3714 return CYLocalize("CONFIRM");
3717 - (NSString *) leftButtonTitle {
3718 return [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("CANCEL"), CYLocalize("QUEUE")];
3721 - (id) rightButtonTitle {
3722 return issues_ != nil ? nil : [super rightButtonTitle];
3725 - (id) _rightButtonTitle {
3726 #if AlwaysReload || IgnoreInstall
3727 return [super _rightButtonTitle];
3729 return CYLocalize("CONFIRM");
3733 - (void) _leftButtonClicked {
3738 - (void) _rightButtonClicked {
3740 return [super _rightButtonClicked];
3742 if (essential_ != nil)
3743 [essential_ popupAlertAnimated:YES];
3747 [delegate_ confirm];
3755 /* Progress Data {{{ */
3756 @interface ProgressData : NSObject {
3762 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3769 @implementation ProgressData
3771 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3772 if ((self = [super init]) != nil) {
3773 selector_ = selector;
3793 /* Progress View {{{ */
3794 @interface ProgressView : UIView <
3795 ConfigurationDelegate,
3798 _transient Database *database_;
3800 UIView *background_;
3801 UITransitionView *transition_;
3803 UINavigationBar *navbar_;
3804 UIProgressBar *progress_;
3805 UITextView *output_;
3806 UITextLabel *status_;
3807 UIPushButton *close_;
3810 SHA1SumValue springlist_;
3811 SHA1SumValue notifyconf_;
3812 SHA1SumValue sandplate_;
3815 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
3817 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
3818 - (void) setContentView:(UIView *)view;
3821 - (void) _retachThread;
3822 - (void) _detachNewThreadData:(ProgressData *)data;
3823 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
3829 @protocol ProgressViewDelegate
3830 - (void) progressViewIsComplete:(ProgressView *)sender;
3833 @implementation ProgressView
3836 [transition_ setDelegate:nil];
3837 [navbar_ setDelegate:nil];
3840 if (background_ != nil)
3841 [background_ release];
3842 [transition_ release];
3845 [progress_ release];
3852 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3853 if (bootstrap_ && from == overlay_ && to == view_)
3857 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
3858 if ((self = [super initWithFrame:frame]) != nil) {
3859 database_ = database;
3860 delegate_ = delegate;
3862 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3863 [transition_ setDelegate:self];
3865 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3868 [overlay_ setBackgroundColor:[UIColor blackColor]];
3870 background_ = [[UIView alloc] initWithFrame:[self bounds]];
3871 [background_ setBackgroundColor:[UIColor blackColor]];
3872 [self addSubview:background_];
3875 [self addSubview:transition_];
3877 CGSize navsize = [UINavigationBar defaultSize];
3878 CGRect navrect = {{0, 0}, navsize};
3880 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
3881 [overlay_ addSubview:navbar_];
3883 [navbar_ setBarStyle:1];
3884 [navbar_ setDelegate:self];
3886 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
3887 [navbar_ pushNavigationItem:navitem];
3889 CGRect bounds = [overlay_ bounds];
3890 CGSize prgsize = [UIProgressBar defaultSize];
3893 (bounds.size.width - prgsize.width) / 2,
3894 bounds.size.height - prgsize.height - 20
3897 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3898 [progress_ setStyle:0];
3900 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3902 bounds.size.height - prgsize.height - 50,
3903 bounds.size.width - 20,
3907 [status_ setColor:[UIColor whiteColor]];
3908 [status_ setBackgroundColor:[UIColor clearColor]];
3910 [status_ setCentersHorizontally:YES];
3911 //[status_ setFont:font];
3914 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3916 navrect.size.height + 20,
3917 bounds.size.width - 20,
3918 bounds.size.height - navsize.height - 62 - navrect.size.height
3922 //[output_ setTextFont:@"Courier New"];
3923 [output_ setTextSize:12];
3925 [output_ setTextColor:[UIColor whiteColor]];
3926 [output_ setBackgroundColor:[UIColor clearColor]];
3928 [output_ setMarginTop:0];
3929 [output_ setAllowsRubberBanding:YES];
3930 [output_ setEditable:NO];
3932 [overlay_ addSubview:output_];
3934 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3936 bounds.size.height - prgsize.height - 50,
3937 bounds.size.width - 20,
3941 [close_ setAutosizesToFit:NO];
3942 [close_ setDrawsShadow:YES];
3943 [close_ setStretchBackground:YES];
3944 [close_ setEnabled:YES];
3946 UIFont *bold = [UIFont boldSystemFontOfSize:22];
3947 [close_ setTitleFont:bold];
3949 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
3950 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
3951 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
3955 - (void) setContentView:(UIView *)view {
3956 view_ = [view retain];
3959 - (void) resetView {
3960 [transition_ transition:6 toView:view_];
3963 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3964 NSString *context([sheet context]);
3966 if ([context isEqualToString:@"error"])
3968 else if ([context isEqualToString:@"conffile"]) {
3969 FILE *input = [database_ input];
3973 fprintf(input, "N\n");
3977 fprintf(input, "Y\n");
3988 - (void) closeButtonPushed {
3997 [delegate_ suspendWithAnimation:YES];
4001 system("launchctl stop com.apple.SpringBoard");
4005 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4014 - (void) _retachThread {
4015 UINavigationItem *item = [navbar_ topItem];
4016 [item setTitle:CYLocalize("COMPLETE")];
4018 [overlay_ addSubview:close_];
4019 [progress_ removeFromSuperview];
4020 [status_ removeFromSuperview];
4022 [delegate_ progressViewIsComplete:self];
4025 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4026 MMap mmap(file, MMap::ReadOnly);
4028 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4029 if (!(sandplate_ == sha1.Result()))
4034 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4035 MMap mmap(file, MMap::ReadOnly);
4037 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4038 if (!(notifyconf_ == sha1.Result()))
4043 FileFd file(SpringBoard_, FileFd::ReadOnly);
4044 MMap mmap(file, MMap::ReadOnly);
4046 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4047 if (!(springlist_ == sha1.Result()))
4052 case 0: [close_ setTitle:CYLocalize("RETURN_TO_CYDIA")]; break;
4053 case 1: [close_ setTitle:CYLocalize("CLOSE_CYDIA")]; break;
4054 case 2: [close_ setTitle:CYLocalize("RESTART_SPRINGBOARD")]; break;
4055 case 3: [close_ setTitle:CYLocalize("RELOAD_SPRINGBOARD")]; break;
4056 case 4: [close_ setTitle:CYLocalize("REBOOT_DEVICE")]; break;
4059 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4061 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
4062 [cache autorelease];
4064 NSFileManager *manager = [NSFileManager defaultManager];
4065 NSError *error = nil;
4067 id system = [cache objectForKey:@"System"];
4072 if (stat(Cache_, &info) == -1)
4075 [system removeAllObjects];
4077 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4078 for (NSString *app in apps)
4079 if ([app hasSuffix:@".app"]) {
4080 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4081 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4082 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4084 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4085 [info setObject:path forKey:@"Path"];
4086 [info setObject:@"System" forKey:@"ApplicationType"];
4087 [system addInfoDictionary:info];
4093 [cache writeToFile:@Cache_ atomically:YES];
4095 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
4097 if (chmod(Cache_, info.st_mode) == -1)
4101 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4104 notify_post("com.apple.mobile.application_installed");
4106 [delegate_ setStatusBarShowsProgress:NO];
4109 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4110 [[data target] performSelector:[data selector] withObject:[data object]];
4113 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4116 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4117 UINavigationItem *item = [navbar_ topItem];
4118 [item setTitle:title];
4120 [status_ setText:nil];
4121 [output_ setText:@""];
4122 [progress_ setProgress:0];
4124 [close_ removeFromSuperview];
4125 [overlay_ addSubview:progress_];
4126 [overlay_ addSubview:status_];
4128 [delegate_ setStatusBarShowsProgress:YES];
4132 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4133 MMap mmap(file, MMap::ReadOnly);
4135 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4136 sandplate_ = sha1.Result();
4140 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4141 MMap mmap(file, MMap::ReadOnly);
4143 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4144 notifyconf_ = sha1.Result();
4148 FileFd file(SpringBoard_, FileFd::ReadOnly);
4149 MMap mmap(file, MMap::ReadOnly);
4151 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4152 springlist_ = sha1.Result();
4155 [transition_ transition:6 toView:overlay_];
4158 detachNewThreadSelector:@selector(_detachNewThreadData:)
4160 withObject:[[ProgressData alloc]
4161 initWithSelector:selector
4168 - (void) repairWithSelector:(SEL)selector {
4170 detachNewThreadSelector:selector
4173 title:CYLocalize("REPAIRING")
4177 - (void) setConfigurationData:(NSString *)data {
4179 performSelectorOnMainThread:@selector(_setConfigurationData:)
4185 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4186 Package *package = id == nil ? nil : [database_ packageWithName:id];
4188 UIActionSheet *sheet = [[[UIActionSheet alloc]
4189 initWithTitle:(package == nil ? id : [package name])
4190 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
4191 defaultButtonIndex:0
4196 [sheet setBodyText:error];
4197 [sheet popupAlertAnimated:YES];
4200 - (void) setProgressTitle:(NSString *)title {
4202 performSelectorOnMainThread:@selector(_setProgressTitle:)
4208 - (void) setProgressPercent:(float)percent {
4210 performSelectorOnMainThread:@selector(_setProgressPercent:)
4211 withObject:[NSNumber numberWithFloat:percent]
4216 - (void) startProgress {
4219 - (void) addProgressOutput:(NSString *)output {
4221 performSelectorOnMainThread:@selector(_addProgressOutput:)
4227 - (bool) isCancelling:(size_t)received {
4231 - (void) _setConfigurationData:(NSString *)data {
4232 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4234 _assert(conffile_r(data));
4236 NSString *ofile = conffile_r[1];
4237 //NSString *nfile = conffile_r[2];
4239 UIActionSheet *sheet = [[[UIActionSheet alloc]
4240 initWithTitle:CYLocalize("CONFIGURATION_UPGRADE")
4241 buttons:[NSArray arrayWithObjects:
4242 CYLocalize("KEEP_OLD_COPY"),
4243 CYLocalize("ACCEPT_NEW_COPY"),
4244 // XXX: CYLocalize("SEE_WHAT_CHANGED"),
4246 defaultButtonIndex:0
4251 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", CYLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4252 [sheet popupAlertAnimated:YES];
4255 - (void) _setProgressTitle:(NSString *)title {
4256 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4257 for (size_t i(0), e([words count]); i != e; ++i) {
4258 NSString *word([words objectAtIndex:i]);
4259 if (Package *package = [database_ packageWithName:word])
4260 [words replaceObjectAtIndex:i withObject:[package name]];
4263 [status_ setText:[words componentsJoinedByString:@" "]];
4266 - (void) _setProgressPercent:(NSNumber *)percent {
4267 [progress_ setProgress:[percent floatValue]];
4270 - (void) _addProgressOutput:(NSString *)output {
4271 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4272 CGSize size = [output_ contentSize];
4273 CGRect rect = {{0, size.height}, {size.width, 0}};
4274 [output_ scrollRectToVisible:rect animated:YES];
4277 - (BOOL) isRunning {
4284 /* Package Cell {{{ */
4285 @interface PackageCell : UITableCell {
4288 NSString *description_;
4295 UITextLabel *status_;
4299 - (PackageCell *) init;
4300 - (void) setPackage:(Package *)package;
4302 + (int) heightForPackage:(Package *)package;
4306 @implementation PackageCell
4308 - (void) clearPackage {
4319 if (description_ != nil) {
4320 [description_ release];
4324 if (source_ != nil) {
4329 if (badge_ != nil) {
4339 [self clearPackage];
4346 - (PackageCell *) init {
4347 if ((self = [super init]) != nil) {
4349 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4350 [status_ setBackgroundColor:[UIColor clearColor]];
4351 [status_ setFont:small];
4356 - (void) setPackage:(Package *)package {
4357 [self clearPackage];
4360 Source *source = [package source];
4362 icon_ = [[package icon] retain];
4363 name_ = [[package name] retain];
4364 description_ = [[package shortDescription] retain];
4365 commercial_ = [package isCommercial];
4367 package_ = [package retain];
4369 NSString *label = nil;
4370 bool trusted = false;
4372 if (source != nil) {
4373 label = [source label];
4374 trusted = [source trusted];
4375 } else if ([[package id] isEqualToString:@"firmware"])
4376 label = CYLocalize("APPLE");
4378 label = [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("UNKNOWN"), CYLocalize("LOCAL")];
4380 NSString *from(label);
4382 NSString *section = [package simpleSection];
4383 if (section != nil && ![section isEqualToString:label]) {
4384 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4385 from = [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), from, section];
4388 from = [NSString stringWithFormat:CYLocalize("FROM"), from];
4389 source_ = [from retain];
4391 if (NSString *purpose = [package primaryPurpose])
4392 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4393 badge_ = [badge_ retain];
4396 if (NSString *mode = [package mode]) {
4397 [badge_ setImage:[UIImage applicationImageNamed:
4398 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4401 [status_ setText:[NSString stringWithFormat:CYLocalize("QUEUED_FOR"), CYLocalize(mode)]];
4402 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4403 } else if ([package half]) {
4404 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4405 [status_ setText:CYLocalize("PACKAGE_DAMAGED")];
4406 [status_ setColor:[UIColor redColor]];
4408 [badge_ setImage:nil];
4409 [status_ setText:nil];
4416 - (void) drawRect:(CGRect)rect {
4420 if (NSString *mode = [package_ mode]) {
4421 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4422 color = remove ? RemovingColor_ : InstallingColor_;
4424 color = [UIColor whiteColor];
4426 [self setBackgroundColor:color];
4430 [super drawRect:rect];
4433 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4435 CGContextRef context(UIGraphicsGetCurrentContext());
4436 [[self backgroundColor] set];
4438 back.size.height -= 1;
4439 CGContextFillRect(context, back);
4442 [super drawBackgroundInRect:rect withFade:fade];
4445 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4448 rect.size = [icon_ size];
4450 rect.size.width /= 2;
4451 rect.size.height /= 2;
4453 rect.origin.x = 25 - rect.size.width / 2;
4454 rect.origin.y = 25 - rect.size.height / 2;
4456 [icon_ drawInRect:rect];
4459 if (badge_ != nil) {
4460 CGSize size = [badge_ size];
4462 [badge_ drawAtPoint:CGPointMake(
4463 36 - size.width / 2,
4464 36 - size.height / 2
4472 UISetColor(commercial_ ? Purple_ : Black_);
4473 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4474 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4477 UISetColor(commercial_ ? Purplish_ : Gray_);
4478 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4480 [super drawContentInRect:rect selected:selected];
4483 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4485 [super setSelected:selected withFade:fade];
4488 + (int) heightForPackage:(Package *)package {
4494 /* Section Cell {{{ */
4495 @interface SectionCell : UISimpleTableCell {
4500 _UISwitchSlider *switch_;
4505 - (void) setSection:(Section *)section editing:(BOOL)editing;
4509 @implementation SectionCell
4511 - (void) clearSection {
4512 if (section_ != nil) {
4522 if (count_ != nil) {
4529 [self clearSection];
4536 if ((self = [super init]) != nil) {
4537 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4539 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4540 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4544 - (void) onSwitch:(id)sender {
4545 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4546 if (metadata == nil) {
4547 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4548 [Sections_ setObject:metadata forKey:section_];
4552 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4555 - (void) setSection:(Section *)section editing:(BOOL)editing {
4556 if (editing != editing_) {
4558 [switch_ removeFromSuperview];
4560 [self addSubview:switch_];
4564 [self clearSection];
4566 if (section == nil) {
4567 name_ = [CYLocalize("ALL_PACKAGES") retain];
4570 section_ = [section localized];
4571 if (section_ != nil)
4572 section_ = [section_ retain];
4573 name_ = [(section_ == nil ? CYLocalize("NO_SECTION") : section_) retain];
4574 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4577 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4581 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4582 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4589 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4591 CGSize size = [count_ sizeWithFont:Font14_];
4595 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4597 [super drawContentInRect:rect selected:selected];
4603 /* File Table {{{ */
4604 @interface FileTable : RVPage {
4605 _transient Database *database_;
4608 NSMutableArray *files_;
4612 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4613 - (void) setPackage:(Package *)package;
4617 @implementation FileTable
4620 if (package_ != nil)
4629 - (int) numberOfRowsInTable:(UITable *)table {
4630 return files_ == nil ? 0 : [files_ count];
4633 - (float) table:(UITable *)table heightForRow:(int)row {
4637 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4638 if (reusing == nil) {
4639 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4640 UIFont *font = [UIFont systemFontOfSize:16];
4641 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4643 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4647 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4651 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4652 if ((self = [super initWithBook:book]) != nil) {
4653 database_ = database;
4655 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4657 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4658 [self addSubview:list_];
4660 UITableColumn *column = [[[UITableColumn alloc]
4661 initWithTitle:CYLocalize("NAME")
4663 width:[self frame].size.width
4666 [list_ setDataSource:self];
4667 [list_ setSeparatorStyle:1];
4668 [list_ addTableColumn:column];
4669 [list_ setDelegate:self];
4670 [list_ setReusesTableCells:YES];
4674 - (void) setPackage:(Package *)package {
4675 if (package_ != nil) {
4676 [package_ autorelease];
4685 [files_ removeAllObjects];
4687 if (package != nil) {
4688 package_ = [package retain];
4689 name_ = [[package id] retain];
4691 if (NSArray *files = [package files])
4692 [files_ addObjectsFromArray:files];
4694 if ([files_ count] != 0) {
4695 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4696 [files_ removeObjectAtIndex:0];
4697 [files_ sortUsingSelector:@selector(compareByPath:)];
4699 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4700 [stack addObject:@"/"];
4702 for (int i(0), e([files_ count]); i != e; ++i) {
4703 NSString *file = [files_ objectAtIndex:i];
4704 while (![file hasPrefix:[stack lastObject]])
4705 [stack removeLastObject];
4706 NSString *directory = [stack lastObject];
4707 [stack addObject:[file stringByAppendingString:@"/"]];
4708 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4709 ([stack count] - 2) * 3, "",
4710 [file substringFromIndex:[directory length]]
4719 - (void) resetViewAnimated:(BOOL)animated {
4720 [list_ resetViewAnimated:animated];
4723 - (void) reloadData {
4724 [self setPackage:[database_ packageWithName:name_]];
4725 [self reloadButtons];
4728 - (NSString *) title {
4729 return CYLocalize("INSTALLED_FILES");
4732 - (NSString *) backButtonTitle {
4733 return CYLocalize("FILES");
4738 /* Package View {{{ */
4739 @interface PackageView : BrowserView {
4740 _transient Database *database_;
4744 NSMutableArray *buttons_;
4747 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4748 - (void) setPackage:(Package *)package;
4752 @implementation PackageView
4755 if (package_ != nil)
4764 if ([self retainCount] == 1)
4765 [delegate_ setPackageView:self];
4769 /* XXX: this is not safe at all... localization of /fail/ */
4770 - (void) _clickButtonWithName:(NSString *)name {
4771 if ([name isEqualToString:CYLocalize("CLEAR")])
4772 [delegate_ clearPackage:package_];
4773 else if ([name isEqualToString:CYLocalize("INSTALL")])
4774 [delegate_ installPackage:package_];
4775 else if ([name isEqualToString:CYLocalize("REINSTALL")])
4776 [delegate_ installPackage:package_];
4777 else if ([name isEqualToString:CYLocalize("REMOVE")])
4778 [delegate_ removePackage:package_];
4779 else if ([name isEqualToString:CYLocalize("UPGRADE")])
4780 [delegate_ installPackage:package_];
4781 else _assert(false);
4784 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4785 NSString *context([sheet context]);
4787 if ([context isEqualToString:@"modify"]) {
4788 int count = [buttons_ count];
4789 _assert(count != 0);
4790 _assert(button <= count + 1);
4792 if (count != button - 1)
4793 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
4797 [super alertSheet:sheet buttonClicked:button];
4800 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
4801 return [super webView:sender didFinishLoadForFrame:frame];
4804 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4805 [super webView:sender didClearWindowObject:window forFrame:frame];
4806 [window setValue:package_ forKey:@"package"];
4809 - (bool) _allowJavaScriptPanel {
4814 - (void) __rightButtonClicked {
4815 int count = [buttons_ count];
4816 _assert(count != 0);
4819 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
4821 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
4822 [buttons addObjectsFromArray:buttons_];
4823 [buttons addObject:CYLocalize("CANCEL")];
4825 [delegate_ slideUp:[[[UIActionSheet alloc]
4828 defaultButtonIndex:([buttons count] - 1)
4835 - (void) _rightButtonClicked {
4837 [super _rightButtonClicked];
4839 [self __rightButtonClicked];
4843 - (id) _rightButtonTitle {
4844 int count = [buttons_ count];
4845 return count == 0 ? nil : count != 1 ? CYLocalize("MODIFY") : [buttons_ objectAtIndex:0];
4848 - (NSString *) backButtonTitle {
4852 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4853 if ((self = [super initWithBook:book]) != nil) {
4854 database_ = database;
4855 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
4856 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
4860 - (void) setPackage:(Package *)package {
4861 if (package_ != nil) {
4862 [package_ autorelease];
4871 [buttons_ removeAllObjects];
4873 if (package != nil) {
4876 package_ = [package retain];
4877 name_ = [[package id] retain];
4878 commercial_ = [package isCommercial];
4880 if ([package_ mode] != nil)
4881 [buttons_ addObject:CYLocalize("CLEAR")];
4882 if ([package_ source] == nil);
4883 else if ([package_ upgradableAndEssential:NO])
4884 [buttons_ addObject:CYLocalize("UPGRADE")];
4885 else if ([package_ installed] == nil)
4886 [buttons_ addObject:CYLocalize("INSTALL")];
4888 [buttons_ addObject:CYLocalize("REINSTALL")];
4889 if ([package_ installed] != nil)
4890 [buttons_ addObject:CYLocalize("REMOVE")];
4892 if (special_ != NULL) {
4893 CGRect frame([webview_ frame]);
4894 frame.size.width = 320;
4895 frame.size.height = 0;
4896 [webview_ setFrame:frame];
4898 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
4901 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
4903 [self setButtonTitle:nil withStyle:nil toFunction:nil];
4905 [self setFinishHook:nil];
4906 [self setPopupHook:nil];
4909 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
4910 [super callFunction:special_];
4914 [self reloadButtons];
4917 - (bool) isLoading {
4918 return commercial_ ? [super isLoading] : false;
4921 - (void) reloadData {
4922 [self setPackage:[database_ packageWithName:name_]];
4927 /* Package Table {{{ */
4928 @interface PackageTable : RVPage {
4929 _transient Database *database_;
4931 NSMutableArray *packages_;
4932 NSMutableArray *sections_;
4933 UISectionList *list_;
4936 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
4938 - (void) setDelegate:(id)delegate;
4940 - (void) reloadData;
4941 - (void) resetCursor;
4943 - (UISectionList *) list;
4945 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
4949 @implementation PackageTable
4952 [list_ setDataSource:nil];
4955 [packages_ release];
4956 [sections_ release];
4961 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
4962 return [sections_ count];
4965 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
4966 return [[sections_ objectAtIndex:section] name];
4969 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
4970 return [[sections_ objectAtIndex:section] row];
4973 - (int) numberOfRowsInTable:(UITable *)table {
4974 return [packages_ count];
4977 - (float) table:(UITable *)table heightForRow:(int)row {
4978 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
4981 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4983 reusing = [[[PackageCell alloc] init] autorelease];
4984 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
4988 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
4992 - (void) tableRowSelected:(NSNotification *)notification {
4993 int row = [[notification object] selectedRow];
4997 Package *package = [packages_ objectAtIndex:row];
4998 package = [database_ packageWithName:[package id]];
4999 PackageView *view([delegate_ packageView]);
5000 [view setPackage:package];
5001 [view setDelegate:delegate_];
5002 [book_ pushPage:view];
5005 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5006 if ((self = [super initWithBook:book]) != nil) {
5007 database_ = database;
5008 title_ = [title retain];
5010 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5011 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5013 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
5014 [list_ setDataSource:self];
5016 UITableColumn *column = [[[UITableColumn alloc]
5017 initWithTitle:CYLocalize("NAME")
5019 width:[self frame].size.width
5022 UITable *table = [list_ table];
5023 [table setSeparatorStyle:1];
5024 [table addTableColumn:column];
5025 [table setDelegate:self];
5026 [table setReusesTableCells:YES];
5028 [self addSubview:list_];
5030 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5031 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5035 - (void) setDelegate:(id)delegate {
5036 delegate_ = delegate;
5039 - (bool) hasPackage:(Package *)package {
5043 - (void) reloadData {
5044 NSArray *packages = [database_ packages];
5046 [packages_ removeAllObjects];
5047 [sections_ removeAllObjects];
5049 _profile(PackageTable$reloadData$Filter)
5050 for (Package *package in packages)
5051 if ([self hasPackage:package])
5052 [packages_ addObject:package];
5055 Section *section = nil;
5057 _profile(PackageTable$reloadData$Section)
5058 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5062 _profile(PackageTable$reloadData$Section$Package)
5063 package = [packages_ objectAtIndex:offset];
5064 index = [package index];
5067 if (section == nil || [section index] != index) {
5068 _profile(PackageTable$reloadData$Section$Allocate)
5069 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5072 _profile(PackageTable$reloadData$Section$Add)
5073 [sections_ addObject:section];
5077 [section addToCount];
5081 _profile(PackageTable$reloadData$List)
5086 - (NSString *) title {
5090 - (void) resetViewAnimated:(BOOL)animated {
5091 [list_ resetViewAnimated:animated];
5094 - (void) resetCursor {
5095 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
5098 - (UISectionList *) list {
5102 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5103 [list_ setShouldHideHeaderInShortLists:hide];
5108 /* Filtered Package Table {{{ */
5109 @interface FilteredPackageTable : PackageTable {
5115 - (void) setObject:(id)object;
5117 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5121 @implementation FilteredPackageTable
5129 - (void) setObject:(id)object {
5135 object_ = [object retain];
5138 - (bool) hasPackage:(Package *)package {
5139 _profile(FilteredPackageTable$hasPackage)
5140 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5144 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5145 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5147 object_ = object == nil ? nil : [object retain];
5149 /* XXX: this is an unsafe optimization of doomy hell */
5150 Method method = class_getInstanceMethod([Package class], filter);
5151 _assert(method != NULL);
5152 imp_ = method_getImplementation(method);
5153 _assert(imp_ != NULL);
5162 /* Add Source View {{{ */
5163 @interface AddSourceView : RVPage {
5164 _transient Database *database_;
5167 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5171 @implementation AddSourceView
5173 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5174 if ((self = [super initWithBook:book]) != nil) {
5175 database_ = database;
5181 /* Source Cell {{{ */
5182 @interface SourceCell : UITableCell {
5185 NSString *description_;
5191 - (SourceCell *) initWithSource:(Source *)source;
5195 @implementation SourceCell
5200 [description_ release];
5205 - (SourceCell *) initWithSource:(Source *)source {
5206 if ((self = [super init]) != nil) {
5208 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5210 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5211 icon_ = [icon_ retain];
5213 origin_ = [[source name] retain];
5214 label_ = [[source uri] retain];
5215 description_ = [[source description] retain];
5219 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5221 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5228 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5232 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5236 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5238 [super drawContentInRect:rect selected:selected];
5243 /* Source Table {{{ */
5244 @interface SourceTable : RVPage {
5245 _transient Database *database_;
5246 UISectionList *list_;
5247 NSMutableArray *sources_;
5248 UIActionSheet *alert_;
5252 UIProgressHUD *hud_;
5255 //NSURLConnection *installer_;
5256 NSURLConnection *trivial_bz2_;
5257 NSURLConnection *trivial_gz_;
5258 //NSURLConnection *automatic_;
5263 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5267 @implementation SourceTable
5269 - (void) _deallocConnection:(NSURLConnection *)connection {
5270 if (connection != nil) {
5271 [connection cancel];
5272 //[connection setDelegate:nil];
5273 [connection release];
5278 [[list_ table] setDelegate:nil];
5279 [list_ setDataSource:nil];
5288 //[self _deallocConnection:installer_];
5289 [self _deallocConnection:trivial_gz_];
5290 [self _deallocConnection:trivial_bz2_];
5291 //[self _deallocConnection:automatic_];
5298 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5299 return offset_ == 0 ? 1 : 2;
5302 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5303 switch (section + (offset_ == 0 ? 1 : 0)) {
5304 case 0: return CYLocalize("ENTERED_BY_USER");
5305 case 1: return CYLocalize("INSTALLED_BY_PACKAGE");
5313 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5314 switch (section + (offset_ == 0 ? 1 : 0)) {
5316 case 1: return offset_;
5324 - (int) numberOfRowsInTable:(UITable *)table {
5325 return [sources_ count];
5328 - (float) table:(UITable *)table heightForRow:(int)row {
5329 Source *source = [sources_ objectAtIndex:row];
5330 return [source description] == nil ? 56 : 73;
5333 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5334 Source *source = [sources_ objectAtIndex:row];
5335 // XXX: weird warning, stupid selectors ;P
5336 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5339 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5343 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5347 - (void) tableRowSelected:(NSNotification*)notification {
5348 UITable *table([list_ table]);
5349 int row([table selectedRow]);
5353 Source *source = [sources_ objectAtIndex:row];
5355 PackageTable *packages = [[[FilteredPackageTable alloc]
5358 title:[source label]
5359 filter:@selector(isVisibleInSource:)
5363 [packages setDelegate:delegate_];
5365 [book_ pushPage:packages];
5368 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5369 Source *source = [sources_ objectAtIndex:row];
5370 return [source record] != nil;
5373 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5374 [[list_ table] setDeleteConfirmationRow:row];
5377 - (void) table:(UITable *)table deleteRow:(int)row {
5378 Source *source = [sources_ objectAtIndex:row];
5379 [Sources_ removeObjectForKey:[source key]];
5380 [delegate_ syncData];
5384 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5387 @"./", @"Distribution",
5388 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5390 [delegate_ syncData];
5393 - (NSString *) getWarning {
5394 NSString *href(href_);
5395 NSRange colon([href rangeOfString:@"://"]);
5396 if (colon.location != NSNotFound)
5397 href = [href substringFromIndex:(colon.location + 3)];
5398 href = [href stringByAddingPercentEscapes];
5399 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5400 href = [href stringByCachingURLWithCurrentCDN];
5402 NSURL *url([NSURL URLWithString:href]);
5404 NSStringEncoding encoding;
5405 NSError *error(nil);
5407 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5408 return [warning length] == 0 ? nil : warning;
5412 - (void) _endConnection:(NSURLConnection *)connection {
5413 NSURLConnection **field = NULL;
5414 if (connection == trivial_bz2_)
5415 field = &trivial_bz2_;
5416 else if (connection == trivial_gz_)
5417 field = &trivial_gz_;
5418 _assert(field != NULL);
5419 [connection release];
5423 trivial_bz2_ == nil &&
5429 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5432 UIActionSheet *sheet = [[[UIActionSheet alloc]
5433 initWithTitle:CYLocalize("SOURCE_WARNING")
5434 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_ANYWAY"), CYLocalize("CANCEL"), nil]
5435 defaultButtonIndex:0
5440 [sheet setNumberOfRows:1];
5442 [sheet setBodyText:warning];
5443 [sheet popupAlertAnimated:YES];
5446 } else if (error_ != nil) {
5447 UIActionSheet *sheet = [[[UIActionSheet alloc]
5448 initWithTitle:CYLocalize("VERIFICATION_ERROR")
5449 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5450 defaultButtonIndex:0
5455 [sheet setBodyText:[error_ localizedDescription]];
5456 [sheet popupAlertAnimated:YES];
5458 UIActionSheet *sheet = [[[UIActionSheet alloc]
5459 initWithTitle:CYLocalize("NOT_REPOSITORY")
5460 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5461 defaultButtonIndex:0
5466 [sheet setBodyText:CYLocalize("NOT_REPOSITORY_EX")];
5467 [sheet popupAlertAnimated:YES];
5470 [delegate_ setStatusBarShowsProgress:NO];
5471 [delegate_ removeProgressHUD:hud_];
5481 if (error_ != nil) {
5488 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5489 switch ([response statusCode]) {
5495 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5496 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5498 error_ = [error retain];
5499 [self _endConnection:connection];
5502 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5503 [self _endConnection:connection];
5506 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5507 NSMutableURLRequest *request = [NSMutableURLRequest
5508 requestWithURL:[NSURL URLWithString:href]
5509 cachePolicy:NSURLRequestUseProtocolCachePolicy
5510 timeoutInterval:20.0
5513 [request setHTTPMethod:method];
5515 if (Machine_ != NULL)
5516 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5517 if (UniqueID_ != nil)
5518 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5521 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5523 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5526 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5527 NSString *context([sheet context]);
5529 if ([context isEqualToString:@"source"]) {
5532 NSString *href = [[sheet textField] text];
5534 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5536 if (![href hasSuffix:@"/"])
5537 href_ = [href stringByAppendingString:@"/"];
5540 href_ = [href_ retain];
5542 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5543 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5544 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5548 hud_ = [[delegate_ addProgressHUD] retain];
5549 [hud_ setText:CYLocalize("VERIFYING_URL")];
5560 } else if ([context isEqualToString:@"trivial"])
5562 else if ([context isEqualToString:@"urlerror"])
5564 else if ([context isEqualToString:@"warning"]) {
5584 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5585 if ((self = [super initWithBook:book]) != nil) {
5586 database_ = database;
5587 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5589 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5590 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5591 [list_ setShouldHideHeaderInShortLists:NO];
5593 [self addSubview:list_];
5594 [list_ setDataSource:self];
5596 UITableColumn *column = [[UITableColumn alloc]
5597 initWithTitle:CYLocalize("NAME")
5599 width:[self frame].size.width
5602 UITable *table = [list_ table];
5603 [table setSeparatorStyle:1];
5604 [table addTableColumn:column];
5605 [table setDelegate:self];
5609 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5610 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5614 - (void) reloadData {
5616 _assert(list.ReadMainList());
5618 [sources_ removeAllObjects];
5619 [sources_ addObjectsFromArray:[database_ sources]];
5621 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5624 int count = [sources_ count];
5625 for (offset_ = 0; offset_ != count; ++offset_) {
5626 Source *source = [sources_ objectAtIndex:offset_];
5627 if ([source record] == nil)
5634 - (void) resetViewAnimated:(BOOL)animated {
5635 [list_ resetViewAnimated:animated];
5638 - (void) _leftButtonClicked {
5639 /*[book_ pushPage:[[[AddSourceView alloc]
5644 UIActionSheet *sheet = [[[UIActionSheet alloc]
5645 initWithTitle:CYLocalize("ENTER_APT_URL")
5646 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_SOURCE"), CYLocalize("CANCEL"), nil]
5647 defaultButtonIndex:0
5652 [sheet setNumberOfRows:1];
5654 [sheet addTextFieldWithValue:@"http://" label:@""];
5656 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5657 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5658 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5659 [traits setKeyboardType:UIKeyboardTypeURL];
5660 // XXX: UIReturnKeyDone
5661 [traits setReturnKeyType:UIReturnKeyNext];
5663 [sheet popupAlertAnimated:YES];
5666 - (void) _rightButtonClicked {
5667 UITable *table = [list_ table];
5668 BOOL editing = [table isRowDeletionEnabled];
5669 [table enableRowDeletion:!editing animated:YES];
5670 [book_ reloadButtonsForPage:self];
5673 - (NSString *) title {
5674 return CYLocalize("SOURCES");
5677 - (NSString *) leftButtonTitle {
5678 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("ADD") : nil;
5681 - (id) rightButtonTitle {
5682 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("DONE") : CYLocalize("EDIT");
5685 - (UINavigationButtonStyle) rightButtonStyle {
5686 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5692 /* Installed View {{{ */
5693 @interface InstalledView : RVPage {
5694 _transient Database *database_;
5695 FilteredPackageTable *packages_;
5699 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5703 @implementation InstalledView
5706 [packages_ release];
5710 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5711 if ((self = [super initWithBook:book]) != nil) {
5712 database_ = database;
5714 packages_ = [[FilteredPackageTable alloc]
5718 filter:@selector(isInstalledAndVisible:)
5719 with:[NSNumber numberWithBool:YES]
5722 [self addSubview:packages_];
5724 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5725 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5729 - (void) resetViewAnimated:(BOOL)animated {
5730 [packages_ resetViewAnimated:animated];
5733 - (void) reloadData {
5734 [packages_ reloadData];
5737 - (void) _rightButtonClicked {
5738 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5739 [packages_ reloadData];
5741 [book_ reloadButtonsForPage:self];
5744 - (NSString *) title {
5745 return CYLocalize("INSTALLED");
5748 - (NSString *) backButtonTitle {
5749 return CYLocalize("PACKAGES");
5752 - (id) rightButtonTitle {
5753 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? CYLocalize("EXPERT") : CYLocalize("SIMPLE");
5756 - (UINavigationButtonStyle) rightButtonStyle {
5757 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5760 - (void) setDelegate:(id)delegate {
5761 [super setDelegate:delegate];
5762 [packages_ setDelegate:delegate];
5769 @interface HomeView : BrowserView {
5774 @implementation HomeView
5776 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5777 NSString *context([sheet context]);
5779 if ([context isEqualToString:@"about"])
5782 [super alertSheet:sheet buttonClicked:button];
5785 - (void) _leftButtonClicked {
5786 UIActionSheet *sheet = [[[UIActionSheet alloc]
5787 initWithTitle:CYLocalize("ABOUT_CYDIA")
5788 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
5789 defaultButtonIndex:0
5795 @"Copyright (C) 2008-2009\n"
5796 "Jay Freeman (saurik)\n"
5797 "saurik@saurik.com\n"
5798 "http://www.saurik.com/\n"
5801 "http://www.theokorigroup.com/\n"
5803 "College of Creative Studies,\n"
5804 "University of California,\n"
5806 "http://www.ccs.ucsb.edu/"
5809 [sheet popupAlertAnimated:YES];
5812 - (NSString *) leftButtonTitle {
5813 return CYLocalize("ABOUT");
5818 /* Manage View {{{ */
5819 @interface ManageView : BrowserView {
5824 @implementation ManageView
5826 - (NSString *) title {
5827 return CYLocalize("MANAGE");
5830 - (void) _leftButtonClicked {
5831 [delegate_ askForSettings];
5834 - (NSString *) leftButtonTitle {
5835 return CYLocalize("SETTINGS");
5839 - (id) _rightButtonTitle {
5840 return Queuing_ ? CYLocalize("QUEUE") : nil;
5843 - (UINavigationButtonStyle) rightButtonStyle {
5844 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5847 - (void) _rightButtonClicked {
5852 - (bool) isLoading {
5859 #include <BrowserView.m>
5861 /* Cydia Book {{{ */
5862 @interface CYBook : RVBook <
5865 _transient Database *database_;
5866 UINavigationBar *overlay_;
5867 UINavigationBar *underlay_;
5868 UIProgressIndicator *indicator_;
5869 UITextLabel *prompt_;
5870 UIProgressBar *progress_;
5871 UINavigationButton *cancel_;
5875 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
5881 @implementation CYBook
5885 [indicator_ release];
5887 [progress_ release];
5892 - (NSString *) getTitleForPage:(RVPage *)page {
5893 return [super getTitleForPage:page];
5901 [UIView beginAnimations:nil context:NULL];
5903 CGRect ovrframe = [overlay_ frame];
5904 ovrframe.origin.y = 0;
5905 [overlay_ setFrame:ovrframe];
5907 CGRect barframe = [navbar_ frame];
5908 barframe.origin.y += ovrframe.size.height;
5909 [navbar_ setFrame:barframe];
5911 CGRect trnframe = [transition_ frame];
5912 trnframe.origin.y += ovrframe.size.height;
5913 trnframe.size.height -= ovrframe.size.height;
5914 [transition_ setFrame:trnframe];
5916 [UIView endAnimations];
5918 [indicator_ startAnimation];
5919 [prompt_ setText:CYLocalize("UPDATING_DATABASE")];
5920 [progress_ setProgress:0];
5923 [overlay_ addSubview:cancel_];
5926 detachNewThreadSelector:@selector(_update)
5935 [indicator_ stopAnimation];
5937 [UIView beginAnimations:nil context:NULL];
5939 CGRect ovrframe = [overlay_ frame];
5940 ovrframe.origin.y = -ovrframe.size.height;
5941 [overlay_ setFrame:ovrframe];
5943 CGRect barframe = [navbar_ frame];
5944 barframe.origin.y -= ovrframe.size.height;
5945 [navbar_ setFrame:barframe];
5947 CGRect trnframe = [transition_ frame];
5948 trnframe.origin.y -= ovrframe.size.height;
5949 trnframe.size.height += ovrframe.size.height;
5950 [transition_ setFrame:trnframe];
5952 [UIView commitAnimations];
5954 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
5957 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
5958 if ((self = [super initWithFrame:frame]) != nil) {
5959 database_ = database;
5961 CGRect ovrrect = [navbar_ bounds];
5962 ovrrect.size.height = [UINavigationBar defaultSize].height;
5963 ovrrect.origin.y = -ovrrect.size.height;
5965 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5966 [self addSubview:overlay_];
5968 ovrrect.origin.y = frame.size.height;
5969 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5970 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
5971 [self addSubview:underlay_];
5973 [overlay_ setBarStyle:1];
5974 [underlay_ setBarStyle:1];
5976 int barstyle = [overlay_ _barStyle:NO];
5977 bool ugly = barstyle == 0;
5979 UIProgressIndicatorStyle style = ugly ?
5980 UIProgressIndicatorStyleMediumBrown :
5981 UIProgressIndicatorStyleMediumWhite;
5983 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
5984 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
5985 CGRect indrect = {{indoffset, indoffset}, indsize};
5987 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
5988 [indicator_ setStyle:style];
5989 [overlay_ addSubview:indicator_];
5991 CGSize prmsize = {215, indsize.height + 4};
5994 indoffset * 2 + indsize.width,
5998 unsigned(ovrrect.size.height - prmsize.height) / 2
6001 UIFont *font = [UIFont systemFontOfSize:15];
6003 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6005 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6006 [prompt_ setBackgroundColor:[UIColor clearColor]];
6007 [prompt_ setFont:font];
6009 [overlay_ addSubview:prompt_];
6011 CGSize prgsize = {75, 100};
6014 ovrrect.size.width - prgsize.width - 10,
6015 (ovrrect.size.height - prgsize.height) / 2
6018 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6019 [progress_ setStyle:0];
6020 [overlay_ addSubview:progress_];
6022 cancel_ = [[UINavigationButton alloc] initWithTitle:CYLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6023 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6025 CGRect frame = [cancel_ frame];
6026 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6027 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6028 [cancel_ setFrame:frame];
6030 [cancel_ setBarStyle:barstyle];
6034 - (void) _onCancel {
6036 [cancel_ removeFromSuperview];
6039 - (void) _update { _pooled
6041 status.setDelegate(self);
6043 [database_ updateWithStatus:status];
6046 performSelectorOnMainThread:@selector(_update_)
6052 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
6053 [prompt_ setText:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), error]];
6056 - (void) setProgressTitle:(NSString *)title {
6058 performSelectorOnMainThread:@selector(_setProgressTitle:)
6064 - (void) setProgressPercent:(float)percent {
6066 performSelectorOnMainThread:@selector(_setProgressPercent:)
6067 withObject:[NSNumber numberWithFloat:percent]
6072 - (void) startProgress {
6075 - (void) addProgressOutput:(NSString *)output {
6077 performSelectorOnMainThread:@selector(_addProgressOutput:)
6083 - (bool) isCancelling:(size_t)received {
6087 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6091 - (void) _setProgressTitle:(NSString *)title {
6092 [prompt_ setText:title];
6095 - (void) _setProgressPercent:(NSNumber *)percent {
6096 [progress_ setProgress:[percent floatValue]];
6099 - (void) _addProgressOutput:(NSString *)output {
6104 /* Cydia:// Protocol {{{ */
6105 @interface CydiaURLProtocol : NSURLProtocol {
6110 @implementation CydiaURLProtocol
6112 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6113 NSURL *url([request URL]);
6116 NSString *scheme([[url scheme] lowercaseString]);
6117 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6122 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6126 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6127 id<NSURLProtocolClient> client([self client]);
6129 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6131 NSData *data(UIImagePNGRepresentation(icon));
6133 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6134 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6135 [client URLProtocol:self didLoadData:data];
6136 [client URLProtocolDidFinishLoading:self];
6140 - (void) startLoading {
6141 id<NSURLProtocolClient> client([self client]);
6142 NSURLRequest *request([self request]);
6144 NSURL *url([request URL]);
6145 NSString *href([url absoluteString]);
6147 NSString *path([href substringFromIndex:8]);
6148 NSRange slash([path rangeOfString:@"/"]);
6151 if (slash.location == NSNotFound) {
6155 command = [path substringToIndex:slash.location];
6156 path = [path substringFromIndex:(slash.location + 1)];
6159 Database *database([Database sharedInstance]);
6161 if ([command isEqualToString:@"package-icon"]) {
6164 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6165 Package *package([database packageWithName:path]);
6168 UIImage *icon([package icon]);
6169 [self _returnPNGWithImage:icon forRequest:request];
6170 } else if ([command isEqualToString:@"source-icon"]) {
6173 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6174 NSString *source(Simplify(path));
6175 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6177 icon = [UIImage applicationImageNamed:@"unknown.png"];
6178 [self _returnPNGWithImage:icon forRequest:request];
6179 } else if ([command isEqualToString:@"uikit-image"]) {
6182 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6183 UIImage *icon(_UIImageWithName(path));
6184 [self _returnPNGWithImage:icon forRequest:request];
6185 } else if ([command isEqualToString:@"section-icon"]) {
6188 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6189 NSString *section(Simplify(path));
6190 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6192 icon = [UIImage applicationImageNamed:@"unknown.png"];
6193 [self _returnPNGWithImage:icon forRequest:request];
6195 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6199 - (void) stopLoading {
6205 /* Sections View {{{ */
6206 @interface SectionsView : RVPage {
6207 _transient Database *database_;
6208 NSMutableArray *sections_;
6209 NSMutableArray *filtered_;
6210 UITransitionView *transition_;
6216 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6217 - (void) reloadData;
6222 @implementation SectionsView
6225 [list_ setDataSource:nil];
6226 [list_ setDelegate:nil];
6228 [sections_ release];
6229 [filtered_ release];
6230 [transition_ release];
6232 [accessory_ release];
6236 - (int) numberOfRowsInTable:(UITable *)table {
6237 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6240 - (float) table:(UITable *)table heightForRow:(int)row {
6244 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6246 reusing = [[[SectionCell alloc] init] autorelease];
6247 [(SectionCell *)reusing setSection:(editing_ ?
6248 [sections_ objectAtIndex:row] :
6249 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6250 ) editing:editing_];
6254 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6258 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6262 - (void) tableRowSelected:(NSNotification *)notification {
6263 int row = [[notification object] selectedRow];
6274 title = CYLocalize("ALL_PACKAGES");
6276 section = [filtered_ objectAtIndex:(row - 1)];
6277 name = [section name];
6280 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6283 title = CYLocalize("NO_SECTION");
6287 PackageTable *table = [[[FilteredPackageTable alloc]
6291 filter:@selector(isVisiblyUninstalledInSection:)
6295 [table setDelegate:delegate_];
6297 [book_ pushPage:table];
6300 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6301 if ((self = [super initWithBook:book]) != nil) {
6302 database_ = database;
6304 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6305 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6307 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6308 [self addSubview:transition_];
6310 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6311 [transition_ transition:0 toView:list_];
6313 UITableColumn *column = [[[UITableColumn alloc]
6314 initWithTitle:CYLocalize("NAME")
6316 width:[self frame].size.width
6319 [list_ setDataSource:self];
6320 [list_ setSeparatorStyle:1];
6321 [list_ addTableColumn:column];
6322 [list_ setDelegate:self];
6323 [list_ setReusesTableCells:YES];
6327 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6328 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6332 - (void) reloadData {
6333 NSArray *packages = [database_ packages];
6335 [sections_ removeAllObjects];
6336 [filtered_ removeAllObjects];
6339 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6340 SectionMap sections;
6341 sections.resize(64);
6343 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6347 for (Package *package in packages) {
6348 NSString *name([package section]);
6349 NSString *key(name == nil ? @"" : name);
6354 _profile(SectionsView$reloadData$Section)
6355 section = §ions[key];
6356 if (*section == nil) {
6357 _profile(SectionsView$reloadData$Section$Allocate)
6358 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6363 [*section addToCount];
6365 _profile(SectionsView$reloadData$Filter)
6366 if (![package valid] || [package installed] != nil || ![package visible])
6370 [*section addToRow];
6374 _profile(SectionsView$reloadData$Section)
6375 section = [sections objectForKey:key];
6376 if (section == nil) {
6377 _profile(SectionsView$reloadData$Section$Allocate)
6378 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6379 [sections setObject:section forKey:key];
6384 [section addToCount];
6386 _profile(SectionsView$reloadData$Filter)
6387 if (![package valid] || [package installed] != nil || ![package visible])
6397 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6398 [sections_ addObject:i->second];
6400 [sections_ addObjectsFromArray:[sections allValues]];
6403 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6405 for (Section *section in sections_) {
6406 size_t count([section row]);
6410 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6411 [section setCount:count];
6412 [filtered_ addObject:section];
6419 - (void) resetView {
6421 [self _rightButtonClicked];
6424 - (void) resetViewAnimated:(BOOL)animated {
6425 [list_ resetViewAnimated:animated];
6428 - (void) _rightButtonClicked {
6429 if ((editing_ = !editing_))
6432 [delegate_ updateData];
6433 [book_ reloadTitleForPage:self];
6434 [book_ reloadButtonsForPage:self];
6437 - (NSString *) title {
6438 return editing_ ? CYLocalize("SECTION_VISIBILITY") : CYLocalize("INSTALL_BY_SECTION");
6441 - (NSString *) backButtonTitle {
6442 return CYLocalize("SECTIONS");
6445 - (id) rightButtonTitle {
6446 return [sections_ count] == 0 ? nil : editing_ ? CYLocalize("DONE") : CYLocalize("EDIT");
6449 - (UINavigationButtonStyle) rightButtonStyle {
6450 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6453 - (UIView *) accessoryView {
6459 /* Changes View {{{ */
6460 @interface ChangesView : RVPage {
6461 _transient Database *database_;
6462 NSMutableArray *packages_;
6463 NSMutableArray *sections_;
6464 UISectionList *list_;
6468 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6469 - (void) reloadData;
6473 @implementation ChangesView
6476 [[list_ table] setDelegate:nil];
6477 [list_ setDataSource:nil];
6479 [packages_ release];
6480 [sections_ release];
6485 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6486 return [sections_ count];
6489 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6490 return [[sections_ objectAtIndex:section] name];
6493 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6494 return [[sections_ objectAtIndex:section] row];
6497 - (int) numberOfRowsInTable:(UITable *)table {
6498 return [packages_ count];
6501 - (float) table:(UITable *)table heightForRow:(int)row {
6502 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6505 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6507 reusing = [[[PackageCell alloc] init] autorelease];
6508 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6512 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6516 - (void) tableRowSelected:(NSNotification *)notification {
6517 int row = [[notification object] selectedRow];
6520 Package *package = [packages_ objectAtIndex:row];
6521 PackageView *view([delegate_ packageView]);
6522 [view setDelegate:delegate_];
6523 [view setPackage:package];
6524 [book_ pushPage:view];
6527 - (void) _leftButtonClicked {
6528 [(CYBook *)book_ update];
6529 [self reloadButtons];
6532 - (void) _rightButtonClicked {
6533 [delegate_ distUpgrade];
6536 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6537 if ((self = [super initWithBook:book]) != nil) {
6538 database_ = database;
6540 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6541 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6543 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6544 [self addSubview:list_];
6546 [list_ setShouldHideHeaderInShortLists:NO];
6547 [list_ setDataSource:self];
6548 //[list_ setSectionListStyle:1];
6550 UITableColumn *column = [[[UITableColumn alloc]
6551 initWithTitle:CYLocalize("NAME")
6553 width:[self frame].size.width
6556 UITable *table = [list_ table];
6557 [table setSeparatorStyle:1];
6558 [table addTableColumn:column];
6559 [table setDelegate:self];
6560 [table setReusesTableCells:YES];
6564 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6565 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6569 - (void) reloadData {
6570 NSArray *packages = [database_ packages];
6572 [packages_ removeAllObjects];
6573 [sections_ removeAllObjects];
6576 for (Package *package in packages)
6578 [package installed] == nil && [package valid] && [package visible] ||
6579 [package upgradableAndEssential:YES]
6581 [packages_ addObject:package];
6584 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6587 Section *upgradable = [[[Section alloc] initWithName:CYLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6588 Section *ignored = [[[Section alloc] initWithName:CYLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6589 Section *section = nil;
6593 bool unseens = false;
6595 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6597 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6598 Package *package = [packages_ objectAtIndex:offset];
6600 BOOL uae = [package upgradableAndEssential:YES];
6606 _profile(ChangesView$reloadData$Remember)
6607 seen = [package seen];
6610 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6615 name = CYLocalize("UNKNOWN");
6617 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6621 _profile(ChangesView$reloadData$Allocate)
6622 name = [NSString stringWithFormat:CYLocalize("NEW_AT"), name];
6623 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6624 [sections_ addObject:section];
6628 [section addToCount];
6629 } else if ([package ignored])
6630 [ignored addToCount];
6633 [upgradable addToCount];
6638 CFRelease(formatter);
6641 Section *last = [sections_ lastObject];
6642 size_t count = [last count];
6643 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6644 [sections_ removeLastObject];
6647 if ([ignored count] != 0)
6648 [sections_ insertObject:ignored atIndex:0];
6650 [sections_ insertObject:upgradable atIndex:0];
6653 [self reloadButtons];
6656 - (void) resetViewAnimated:(BOOL)animated {
6657 [list_ resetViewAnimated:animated];
6660 - (NSString *) leftButtonTitle {
6661 return [(CYBook *)book_ updating] ? nil : CYLocalize("REFRESH");
6664 - (id) rightButtonTitle {
6665 return upgrades_ == 0 ? nil : [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6668 - (NSString *) title {
6669 return CYLocalize("CHANGES");
6674 /* Search View {{{ */
6675 @protocol SearchViewDelegate
6676 - (void) showKeyboard:(BOOL)show;
6679 @interface SearchView : RVPage {
6681 UISearchField *field_;
6682 UITransitionView *transition_;
6683 FilteredPackageTable *table_;
6684 UIPreferencesTable *advanced_;
6690 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6691 - (void) reloadData;
6695 @implementation SearchView
6698 [field_ setDelegate:nil];
6700 [accessory_ release];
6702 [transition_ release];
6704 [advanced_ release];
6709 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6713 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6715 case 0: return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("ADVANCED_SEARCH"), CYLocalize("COMING_SOON")];
6717 default: _assert(false);
6721 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6725 default: _assert(false);
6729 - (void) _showKeyboard:(BOOL)show {
6730 CGSize keysize = [UIKeyboard defaultSize];
6731 CGRect keydown = [book_ pageBounds];
6732 CGRect keyup = keydown;
6733 keyup.size.height -= keysize.height - ButtonBarHeight_;
6735 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6737 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6738 [animation setSignificantRectFields:8];
6741 [animation setStartFrame:keydown];
6742 [animation setEndFrame:keyup];
6744 [animation setStartFrame:keyup];
6745 [animation setEndFrame:keydown];
6748 UIAnimator *animator = [UIAnimator sharedAnimator];
6751 addAnimations:[NSArray arrayWithObjects:animation, nil]
6752 withDuration:(KeyboardTime_ - delay)
6757 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6759 [delegate_ showKeyboard:show];
6762 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6763 [self _showKeyboard:YES];
6766 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
6767 [self _showKeyboard:NO];
6770 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
6772 NSString *text([field_ text]);
6773 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6779 - (void) textFieldClearButtonPressed:(UITextField *)field {
6783 - (void) keyboardInputShouldDelete:(id)input {
6787 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
6788 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6792 [field_ resignFirstResponder];
6797 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6798 if ((self = [super initWithBook:book]) != nil) {
6799 CGRect pageBounds = [book_ pageBounds];
6801 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6802 [self addSubview:transition_];
6804 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6806 [advanced_ setReusesTableCells:YES];
6807 [advanced_ setDataSource:self];
6808 [advanced_ reloadData];
6810 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6811 CGColor dimmed(space_, 0, 0, 0, 0.5);
6812 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
6814 table_ = [[FilteredPackageTable alloc]
6818 filter:@selector(isUnfilteredAndSearchedForBy:)
6822 [table_ setShouldHideHeaderInShortLists:NO];
6823 [transition_ transition:0 toView:table_];
6832 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
6839 [self bounds].size.width - area.origin.x - 18;
6841 area.size.height = [UISearchField defaultHeight];
6843 field_ = [[UISearchField alloc] initWithFrame:area];
6845 UIFont *font = [UIFont systemFontOfSize:16];
6846 [field_ setFont:font];
6848 [field_ setPlaceholder:CYLocalize("SEARCH_EX")];
6849 [field_ setDelegate:self];
6851 [field_ setPaddingTop:5];
6853 UITextInputTraits *traits([field_ textInputTraits]);
6854 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6855 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6856 [traits setReturnKeyType:UIReturnKeySearch];
6858 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
6860 accessory_ = [[UIView alloc] initWithFrame:accrect];
6861 [accessory_ addSubview:field_];
6863 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
6864 [configure setShowPressFeedback:YES];
6865 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
6866 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
6867 [accessory_ addSubview:configure];*/
6869 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6870 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6876 LKAnimation *animation = [LKTransition animation];
6877 [animation setType:@"oglFlip"];
6878 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
6879 [animation setFillMode:@"extended"];
6880 [animation setTransitionFlags:3];
6881 [animation setDuration:10];
6882 [animation setSpeed:0.35];
6883 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
6884 [[transition_ _layer] addAnimation:animation forKey:0];
6885 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
6886 flipped_ = !flipped_;
6890 - (void) configurePushed {
6891 [field_ resignFirstResponder];
6895 - (void) resetViewAnimated:(BOOL)animated {
6898 [table_ resetViewAnimated:animated];
6901 - (void) _reloadData {
6904 - (void) reloadData {
6907 [table_ setObject:[field_ text]];
6908 _profile(SearchView$reloadData)
6909 [table_ reloadData];
6912 [table_ resetCursor];
6915 - (UIView *) accessoryView {
6919 - (NSString *) title {
6923 - (NSString *) backButtonTitle {
6924 return CYLocalize("SEARCH");
6927 - (void) setDelegate:(id)delegate {
6928 [table_ setDelegate:delegate];
6929 [super setDelegate:delegate];
6935 @interface SettingsView : RVPage {
6936 _transient Database *database_;
6939 UIPreferencesTable *table_;
6940 _UISwitchSlider *subscribedSwitch_;
6941 _UISwitchSlider *ignoredSwitch_;
6942 UIPreferencesControlTableCell *subscribedCell_;
6943 UIPreferencesControlTableCell *ignoredCell_;
6946 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6950 @implementation SettingsView
6953 [table_ setDataSource:nil];
6956 if (package_ != nil)
6959 [subscribedSwitch_ release];
6960 [ignoredSwitch_ release];
6961 [subscribedCell_ release];
6962 [ignoredCell_ release];
6966 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6967 if (package_ == nil)
6973 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6974 if (package_ == nil)
6981 default: _assert(false);
6987 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
6988 if (package_ == nil)
6995 default: _assert(false);
7001 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7002 if (package_ == nil)
7009 default: _assert(false);
7015 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7016 if (package_ == nil)
7019 _UISwitchSlider *slider([cell control]);
7020 BOOL value([slider value] != 0);
7021 NSMutableDictionary *metadata([package_ metadata]);
7024 if (NSNumber *number = [metadata objectForKey:key])
7025 before = [number boolValue];
7029 if (value != before) {
7030 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7032 [delegate_ updateData];
7036 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7037 [self onSomething:cell withKey:@"IsSubscribed"];
7040 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7041 [self onSomething:cell withKey:@"IsIgnored"];
7044 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7045 if (package_ == nil)
7049 case 0: switch (row) {
7051 return subscribedCell_;
7053 return ignoredCell_;
7054 default: _assert(false);
7057 case 1: switch (row) {
7059 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7060 [cell setShowSelection:NO];
7061 [cell setTitle:CYLocalize("SHOW_ALL_CHANGES_EX")];
7065 default: _assert(false);
7068 default: _assert(false);
7074 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7075 if ((self = [super initWithBook:book])) {
7076 database_ = database;
7077 name_ = [package retain];
7079 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7080 [self addSubview:table_];
7082 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7083 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
7085 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7086 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
7088 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7089 [subscribedCell_ setShowSelection:NO];
7090 [subscribedCell_ setTitle:CYLocalize("SHOW_ALL_CHANGES")];
7091 [subscribedCell_ setControl:subscribedSwitch_];
7093 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7094 [ignoredCell_ setShowSelection:NO];
7095 [ignoredCell_ setTitle:CYLocalize("IGNORE_UPGRADES")];
7096 [ignoredCell_ setControl:ignoredSwitch_];
7098 [table_ setDataSource:self];
7103 - (void) resetViewAnimated:(BOOL)animated {
7104 [table_ resetViewAnimated:animated];
7107 - (void) reloadData {
7108 if (package_ != nil)
7109 [package_ autorelease];
7110 package_ = [database_ packageWithName:name_];
7111 if (package_ != nil) {
7113 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7114 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7117 [table_ reloadData];
7120 - (NSString *) title {
7121 return CYLocalize("SETTINGS");
7126 /* Signature View {{{ */
7127 @interface SignatureView : BrowserView {
7128 _transient Database *database_;
7132 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7136 @implementation SignatureView
7143 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7145 [super webView:sender didClearWindowObject:window forFrame:frame];
7148 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7149 if ((self = [super initWithBook:book]) != nil) {
7150 database_ = database;
7151 package_ = [package retain];
7156 - (void) resetViewAnimated:(BOOL)animated {
7159 - (void) reloadData {
7160 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7166 @interface Cydia : UIApplication <
7167 ConfirmationViewDelegate,
7168 ProgressViewDelegate,
7177 UIToolbar *buttonbar_;
7181 NSMutableArray *essential_;
7182 NSMutableArray *broken_;
7184 Database *database_;
7185 ProgressView *progress_;
7189 UIKeyboard *keyboard_;
7190 UIProgressHUD *hud_;
7192 SectionsView *sections_;
7193 ChangesView *changes_;
7194 ManageView *manage_;
7195 SearchView *search_;
7197 PackageView *package_;
7202 @implementation Cydia
7205 if ([broken_ count] != 0) {
7206 int count = [broken_ count];
7208 UIActionSheet *sheet = [[[UIActionSheet alloc]
7209 initWithTitle:(count == 1 ? CYLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:CYLocalize("HALFINSTALLED_PACKAGES"), count])
7210 buttons:[NSArray arrayWithObjects:
7211 CYLocalize("FORCIBLY_CLEAR"),
7212 CYLocalize("TEMPORARY_IGNORE"),
7214 defaultButtonIndex:0
7219 [sheet setBodyText:CYLocalize("HALFINSTALLED_PACKAGE_EX")];
7220 [sheet popupAlertAnimated:YES];
7221 } else if (!Ignored_ && [essential_ count] != 0) {
7222 int count = [essential_ count];
7224 UIActionSheet *sheet = [[[UIActionSheet alloc]
7225 initWithTitle:(count == 1 ? CYLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:CYLocalize("ESSENTIAL_UPGRADES"), count])
7226 buttons:[NSArray arrayWithObjects:
7227 CYLocalize("UPGRADE_ESSENTIAL"),
7228 CYLocalize("COMPLETE_UPGRADE"),
7229 CYLocalize("TEMPORARY_IGNORE"),
7231 defaultButtonIndex:0
7236 [sheet setBodyText:CYLocalize("ESSENTIAL_UPGRADE_EX")];
7237 [sheet popupAlertAnimated:YES];
7241 - (void) _reloadData {
7244 static bool loaded(false);
7245 UIProgressHUD *hud([self addProgressHUD]);
7246 [hud setText:(loaded ? CYLocalize("RELOADING_DATA") : CYLocalize("LOADING_DATA"))];
7249 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7252 [self removeProgressHUD:hud];
7256 [essential_ removeAllObjects];
7257 [broken_ removeAllObjects];
7259 NSArray *packages = [database_ packages];
7260 for (Package *package in packages) {
7262 [broken_ addObject:package];
7263 if ([package upgradableAndEssential:NO]) {
7264 if ([package essential])
7265 [essential_ addObject:package];
7271 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7272 [buttonbar_ setBadgeValue:badge forButton:3];
7273 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7274 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7275 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7276 [self setApplicationBadge:badge];
7278 [self setApplicationBadgeString:badge];
7280 [buttonbar_ setBadgeValue:nil forButton:3];
7281 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7282 [buttonbar_ setBadgeAnimated:NO forButton:3];
7283 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7284 [self removeApplicationBadge];
7285 else // XXX: maybe use setApplicationBadgeString also?
7286 [self setApplicationIconBadgeNumber:0];
7290 [buttonbar_ setBadgeValue:nil forButton:4];
7294 // XXX: what is this line of code for?
7295 if ([packages count] == 0);
7296 else if (Loaded_ || ManualRefresh) loaded:
7301 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7302 NSTimeInterval interval([update timeIntervalSinceNow]);
7303 if (interval <= 0 && interval > -600)
7311 - (void) _saveConfig {
7314 NSString *error(nil);
7315 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7317 NSError *error(nil);
7318 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7319 NSLog(@"failure to save metadata data: %@", error);
7322 NSLog(@"failure to serialize metadata: %@", error);
7330 - (void) updateData {
7333 /* XXX: this is just stupid */
7334 if (tag_ != 2 && sections_ != nil)
7335 [sections_ reloadData];
7336 if (tag_ != 3 && changes_ != nil)
7337 [changes_ reloadData];
7338 if (tag_ != 5 && search_ != nil)
7339 [search_ reloadData];
7349 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7350 _assert(file != NULL);
7352 NSArray *keys = [Sources_ allKeys];
7354 for (NSString *key in keys) {
7355 NSDictionary *source = [Sources_ objectForKey:key];
7357 fprintf(file, "%s %s %s\n",
7358 [[source objectForKey:@"Type"] UTF8String],
7359 [[source objectForKey:@"URI"] UTF8String],
7360 [[source objectForKey:@"Distribution"] UTF8String]
7369 detachNewThreadSelector:@selector(update_)
7372 title:CYLocalize("UPDATING_SOURCES")
7376 - (void) reloadData {
7377 @synchronized (self) {
7378 if (confirm_ == nil)
7384 pkgProblemResolver *resolver = [database_ resolver];
7386 resolver->InstallProtect();
7387 if (!resolver->Resolve(true))
7391 - (void) popUpBook:(RVBook *)book {
7392 [underlay_ popSubview:book];
7395 - (CGRect) popUpBounds {
7396 return [underlay_ bounds];
7400 [database_ prepare];
7402 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7403 [confirm_ setDelegate:self];
7405 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7406 [page setDelegate:self];
7408 [confirm_ setPage:page];
7409 [self popUpBook:confirm_];
7413 @synchronized (self) {
7418 - (void) clearPackage:(Package *)package {
7419 @synchronized (self) {
7426 - (void) installPackage:(Package *)package {
7427 @synchronized (self) {
7434 - (void) removePackage:(Package *)package {
7435 @synchronized (self) {
7442 - (void) distUpgrade {
7443 @synchronized (self) {
7444 [database_ upgrade];
7450 [self slideUp:[[[UIActionSheet alloc]
7452 buttons:[NSArray arrayWithObjects:CYLocalize("CONTINUE_QUEUING"), CYLocalize("CANCEL_CLEAR"), nil]
7453 defaultButtonIndex:1
7460 @synchronized (self) {
7463 if (confirm_ != nil) {
7471 [overlay_ removeFromSuperview];
7475 detachNewThreadSelector:@selector(perform)
7478 title:CYLocalize("RUNNING")
7482 - (void) bootstrap_ {
7484 [database_ upgrade];
7485 [database_ prepare];
7486 [database_ perform];
7489 /* XXX: replace and localize */
7490 - (void) bootstrap {
7492 detachNewThreadSelector:@selector(bootstrap_)
7495 title:@"Bootstrap Install"
7499 - (void) progressViewIsComplete:(ProgressView *)progress {
7500 if (confirm_ != nil) {
7501 [underlay_ addSubview:overlay_];
7502 [confirm_ popFromSuperviewAnimated:NO];
7508 - (void) setPage:(RVPage *)page {
7509 [page resetViewAnimated:NO];
7510 [page setDelegate:self];
7511 [book_ setPage:page];
7514 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7515 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7516 [browser loadURL:url];
7520 - (void) _setHomePage {
7521 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7524 - (SectionsView *) sectionsView {
7525 if (sections_ == nil)
7526 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7530 - (void) buttonBarItemTapped:(id)sender {
7531 unsigned tag = [sender tag];
7533 [book_ resetViewAnimated:YES];
7535 } else if (tag_ == 2 && tag != 2)
7536 [[self sectionsView] resetView];
7539 case 1: [self _setHomePage]; break;
7541 case 2: [self setPage:[self sectionsView]]; break;
7542 case 3: [self setPage:changes_]; break;
7543 case 4: [self setPage:manage_]; break;
7544 case 5: [self setPage:search_]; break;
7546 default: _assert(false);
7552 - (void) applicationWillSuspend {
7554 [super applicationWillSuspend];
7557 - (void) askForSettings {
7558 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
7560 UIActionSheet *role = [[[UIActionSheet alloc]
7561 initWithTitle:CYLocalize("WHO_ARE_YOU")
7562 buttons:[NSArray arrayWithObjects:
7563 [NSString stringWithFormat:parenthetical, CYLocalize("USER"), CYLocalize("USER_EX")],
7564 [NSString stringWithFormat:parenthetical, CYLocalize("HACKER"), CYLocalize("HACKER_EX")],
7565 [NSString stringWithFormat:parenthetical, CYLocalize("DEVELOPER"), CYLocalize("DEVELOPER_EX")],
7567 defaultButtonIndex:-1
7572 [role setBodyText:CYLocalize("ROLE_EX")];
7573 [role popupAlertAnimated:YES];
7576 - (void) setPackageView:(PackageView *)view {
7577 if (package_ == nil)
7578 package_ = [view retain];
7581 - (PackageView *) packageView {
7584 if (package_ == nil)
7585 view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7588 view = [package_ autorelease];
7597 [self setStatusBarShowsProgress:NO];
7598 [self removeProgressHUD:hud_];
7603 pid_t pid = ExecFork();
7605 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7606 perror("launchctl stop");
7613 [self askForSettings];
7618 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7620 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7621 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7622 0, 0, screenrect.size.width, screenrect.size.height - 48
7623 ) database:database_];
7625 [book_ setDelegate:self];
7627 [overlay_ addSubview:book_];
7629 NSArray *buttonitems = [NSArray arrayWithObjects:
7630 [NSDictionary dictionaryWithObjectsAndKeys:
7631 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7632 @"home-up.png", kUIButtonBarButtonInfo,
7633 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7634 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7635 self, kUIButtonBarButtonTarget,
7636 @"Cydia", kUIButtonBarButtonTitle,
7637 @"0", kUIButtonBarButtonType,
7640 [NSDictionary dictionaryWithObjectsAndKeys:
7641 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7642 @"install-up.png", kUIButtonBarButtonInfo,
7643 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7644 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7645 self, kUIButtonBarButtonTarget,
7646 CYLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7647 @"0", kUIButtonBarButtonType,
7650 [NSDictionary dictionaryWithObjectsAndKeys:
7651 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7652 @"changes-up.png", kUIButtonBarButtonInfo,
7653 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7654 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7655 self, kUIButtonBarButtonTarget,
7656 CYLocalize("CHANGES"), kUIButtonBarButtonTitle,
7657 @"0", kUIButtonBarButtonType,
7660 [NSDictionary dictionaryWithObjectsAndKeys:
7661 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7662 @"manage-up.png", kUIButtonBarButtonInfo,
7663 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7664 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7665 self, kUIButtonBarButtonTarget,
7666 CYLocalize("MANAGE"), kUIButtonBarButtonTitle,
7667 @"0", kUIButtonBarButtonType,
7670 [NSDictionary dictionaryWithObjectsAndKeys:
7671 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7672 @"search-up.png", kUIButtonBarButtonInfo,
7673 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7674 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7675 self, kUIButtonBarButtonTarget,
7676 CYLocalize("SEARCH"), kUIButtonBarButtonTitle,
7677 @"0", kUIButtonBarButtonType,
7681 buttonbar_ = [[UIToolbar alloc]
7683 withFrame:CGRectMake(
7684 0, screenrect.size.height - ButtonBarHeight_,
7685 screenrect.size.width, ButtonBarHeight_
7687 withItemList:buttonitems
7690 [buttonbar_ setDelegate:self];
7691 [buttonbar_ setBarStyle:1];
7692 [buttonbar_ setButtonBarTrackingMode:2];
7694 int buttons[5] = {1, 2, 3, 4, 5};
7695 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7696 [buttonbar_ showButtonGroup:0 withDuration:0];
7698 for (int i = 0; i != 5; ++i)
7699 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7700 i * 64 + 2, 1, 60, ButtonBarHeight_
7703 [buttonbar_ showSelectionForButton:1];
7704 [overlay_ addSubview:buttonbar_];
7706 [UIKeyboard initImplementationNow];
7707 CGSize keysize = [UIKeyboard defaultSize];
7708 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7709 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7710 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
7711 [overlay_ addSubview:keyboard_];
7714 [underlay_ addSubview:overlay_];
7718 [self sectionsView];
7719 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7720 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7722 manage_ = (ManageView *) [[self
7723 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7724 withClass:[ManageView class]
7727 [self setPackageView:[self packageView]];
7734 [self _setHomePage];
7737 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7738 NSString *context([sheet context]);
7740 if ([context isEqualToString:@"missing"])
7742 else if ([context isEqualToString:@"cancel"]) {
7760 @synchronized (self) {
7765 [buttonbar_ setBadgeValue:CYLocalize("Q_D") forButton:4];
7769 if (confirm_ != nil) {
7774 } else if ([context isEqualToString:@"fixhalf"]) {
7777 @synchronized (self) {
7778 for (Package *broken in broken_) {
7781 NSString *id = [broken id];
7782 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7783 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7784 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7785 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7794 [broken_ removeAllObjects];
7803 } else if ([context isEqualToString:@"role"]) {
7805 case 1: Role_ = @"User"; break;
7806 case 2: Role_ = @"Hacker"; break;
7807 case 3: Role_ = @"Developer"; break;
7814 bool reset = Settings_ != nil;
7816 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7820 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7830 } else if ([context isEqualToString:@"upgrade"]) {
7833 @synchronized (self) {
7834 for (Package *essential in essential_)
7835 [essential install];
7858 - (void) reorganize { _pooled
7859 system("/usr/libexec/cydia/free.sh");
7860 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
7863 - (void) applicationSuspend:(__GSEvent *)event {
7864 if (hud_ == nil && ![progress_ isRunning])
7865 [super applicationSuspend:event];
7868 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7870 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7873 - (void) _setSuspended:(BOOL)value {
7875 [super _setSuspended:value];
7878 - (UIProgressHUD *) addProgressHUD {
7879 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
7880 [window_ setUserInteractionEnabled:NO];
7882 [progress_ addSubview:hud];
7886 - (void) removeProgressHUD:(UIProgressHUD *)hud {
7888 [hud removeFromSuperview];
7889 [window_ setUserInteractionEnabled:YES];
7892 - (void) openMailToURL:(NSURL *)url {
7893 // XXX: this makes me sad
7895 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
7897 [UIApp openURL:url];// asPanel:YES];
7901 - (void) clearFirstResponder {
7902 if (id responder = [window_ firstResponder])
7903 [responder resignFirstResponder];
7906 - (RVPage *) pageForPackage:(NSString *)name {
7907 if (Package *package = [database_ packageWithName:name]) {
7908 PackageView *view([self packageView]);
7909 [view setPackage:package];
7912 UIActionSheet *sheet = [[[UIActionSheet alloc]
7913 initWithTitle:CYLocalize("CANNOT_LOCATE_PACKAGE")
7914 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
7915 defaultButtonIndex:0
7920 [sheet setBodyText:[NSString stringWithFormat:CYLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
7922 [sheet popupAlertAnimated:YES];
7927 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
7931 NSString *scheme([[url scheme] lowercaseString]);
7932 if (![scheme isEqualToString:@"cydia"])
7934 NSString *path([url absoluteString]);
7935 if ([path length] < 8)
7937 path = [path substringFromIndex:8];
7938 if (![path hasPrefix:@"/"])
7939 path = [@"/" stringByAppendingString:path];
7941 if ([path isEqualToString:@"/add-source"])
7942 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
7943 else if ([path isEqualToString:@"/storage"])
7944 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[BrowserView class]];
7945 else if ([path isEqualToString:@"/sources"])
7946 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
7947 else if ([path isEqualToString:@"/packages"])
7948 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
7949 else if ([path hasPrefix:@"/url/"])
7950 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[BrowserView class]];
7951 else if ([path hasPrefix:@"/launch/"])
7952 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
7953 else if ([path hasPrefix:@"/package-settings/"])
7954 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
7955 else if ([path hasPrefix:@"/package-signature/"])
7956 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
7957 else if ([path hasPrefix:@"/package/"])
7958 return [self pageForPackage:[path substringFromIndex:9]];
7959 else if ([path hasPrefix:@"/files/"]) {
7960 NSString *name = [path substringFromIndex:7];
7962 if (Package *package = [database_ packageWithName:name]) {
7963 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
7964 [files setPackage:package];
7972 - (void) applicationOpenURL:(NSURL *)url {
7973 [super applicationOpenURL:url];
7975 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
7976 [self setPage:page];
7977 [buttonbar_ showSelectionForButton:tag];
7982 - (void) applicationDidFinishLaunching:(id)unused {
7984 Font12_ = [[UIFont systemFontOfSize:12] retain];
7985 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
7986 Font14_ = [[UIFont systemFontOfSize:14] retain];
7987 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
7988 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
7992 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
7993 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
7995 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
7997 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7998 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
8000 [window_ orderFront:self];
8001 [window_ makeKey:self];
8002 [window_ setHidden:NO];
8004 database_ = [Database sharedInstance];
8005 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8006 [database_ setDelegate:progress_];
8007 [window_ setContentView:progress_];
8009 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8010 [progress_ setContentView:underlay_];
8012 [progress_ resetView];
8015 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8016 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8017 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8018 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8019 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8020 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
8021 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
8023 [self setIdleTimerDisabled:YES];
8025 hud_ = [[self addProgressHUD] retain];
8026 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8028 [self setStatusBarShowsProgress:YES];
8031 detachNewThreadSelector:@selector(reorganize)
8039 - (void) showKeyboard:(BOOL)show {
8040 CGSize keysize = [UIKeyboard defaultSize];
8041 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8042 CGRect keyup = keydown;
8043 keyup.origin.y -= keysize.height;
8045 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
8046 [animation setSignificantRectFields:2];
8049 [animation setStartFrame:keydown];
8050 [animation setEndFrame:keyup];
8051 [keyboard_ activate];
8053 [animation setStartFrame:keyup];
8054 [animation setEndFrame:keydown];
8055 [keyboard_ deactivate];
8058 [[UIAnimator sharedAnimator]
8059 addAnimations:[NSArray arrayWithObjects:animation, nil]
8060 withDuration:KeyboardTime_
8065 - (void) slideUp:(UIActionSheet *)alert {
8067 [alert presentSheetFromButtonBar:buttonbar_];
8069 [alert presentSheetInView:overlay_];
8074 void AddPreferences(NSString *plist) { _pooled
8075 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
8076 _assert(settings != NULL);
8077 NSMutableArray *items = [settings objectForKey:@"items"];
8081 for (NSMutableDictionary *item in items) {
8082 NSString *label = [item objectForKey:@"label"];
8083 if (label != nil && [label isEqualToString:@"Cydia"]) {
8090 for (size_t i(0); i != [items count]; ++i) {
8091 NSDictionary *item([items objectAtIndex:i]);
8092 NSString *label = [item objectForKey:@"label"];
8093 if (label != nil && [label isEqualToString:@"General"]) {
8094 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
8095 @"CydiaSettings", @"bundle",
8096 @"PSLinkCell", @"cell",
8097 [NSNumber numberWithBool:YES], @"hasIcon",
8098 [NSNumber numberWithBool:YES], @"isController",
8100 nil] atIndex:(i + 1)];
8106 _assert([settings writeToFile:plist atomically:YES] == YES);
8111 id Alloc_(id self, SEL selector) {
8112 id object = alloc_(self, selector);
8113 lprintf("[%s]A-%p\n", self->isa->name, object);
8118 id Dealloc_(id self, SEL selector) {
8119 id object = dealloc_(self, selector);
8120 lprintf("[%s]D-%p\n", self->isa->name, object);
8124 Class $WebDefaultUIKitDelegate;
8126 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
8128 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
8129 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8130 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8131 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
8134 int main(int argc, char *argv[]) { _pooled
8137 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8139 /* Library Hacks {{{ */
8140 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8142 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8143 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8144 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8145 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8146 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8149 /* Set Locale {{{ */
8150 Locale_ = CFLocaleCopyCurrent();
8151 Languages_ = [NSLocale preferredLanguages];
8152 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8153 //NSLog(@"%@", [Languages_ description]);
8155 if (Languages_ == nil || [Languages_ count] == 0)
8158 lang = [[Languages_ objectAtIndex:0] UTF8String];
8159 setenv("LANG", lang, true);
8160 //std::setlocale(LC_ALL, lang);
8161 NSLog(@"Setting Language: %s", lang);
8164 // XXX: apr_app_initialize?
8167 /* Parse Arguments {{{ */
8168 bool substrate(false);
8174 for (int argi(1); argi != argc; ++argi)
8175 if (strcmp(argv[argi], "--") == 0) {
8177 argv[argi] = argv[0];
8183 for (int argi(1); argi != arge; ++argi)
8184 if (strcmp(args[argi], "--bootstrap") == 0)
8186 else if (strcmp(args[argi], "--substrate") == 0)
8189 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8194 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
8195 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
8196 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
8197 Sounds_Keyboard_ = [keyboard boolValue];
8200 App_ = [[NSBundle mainBundle] bundlePath];
8201 Home_ = NSHomeDirectory();
8206 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8207 alloc_ = alloc->method_imp;
8208 alloc->method_imp = (IMP) &Alloc_;*/
8210 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8211 dealloc_ = dealloc->method_imp;
8212 dealloc->method_imp = (IMP) &Dealloc_;*/
8217 size = sizeof(maxproc);
8218 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8219 perror("sysctlbyname(\"kern.maxproc\", ?)");
8220 else if (maxproc < 64) {
8222 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8223 perror("sysctlbyname(\"kern.maxproc\", #)");
8226 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8227 char *machine = new char[size];
8228 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8229 perror("sysctlbyname(\"hw.machine\", ?)");
8233 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8235 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8236 Build_ = [system objectForKey:@"ProductBuildVersion"];
8237 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8238 Product_ = [info objectForKey:@"SafariProductVersion"];
8239 Safari_ = [info objectForKey:@"CFBundleVersion"];
8242 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8243 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
8245 /* Load Database {{{ */
8247 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8249 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8252 if (Metadata_ == NULL)
8253 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8255 Settings_ = [Metadata_ objectForKey:@"Settings"];
8257 Packages_ = [Metadata_ objectForKey:@"Packages"];
8258 Sections_ = [Metadata_ objectForKey:@"Sections"];
8259 Sources_ = [Metadata_ objectForKey:@"Sources"];
8262 if (Settings_ != nil)
8263 Role_ = [Settings_ objectForKey:@"Role"];
8265 if (Packages_ == nil) {
8266 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8267 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8270 if (Sections_ == nil) {
8271 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8272 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8275 if (Sources_ == nil) {
8276 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8277 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8282 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8285 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8286 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8287 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8288 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8290 if (access("/User", F_OK) != 0) {
8292 system("/usr/libexec/cydia/firmware.sh");
8296 _assert([[NSFileManager defaultManager]
8297 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8298 withIntermediateDirectories:YES
8303 if (access("/tmp/cydia.chk", F_OK) == 0) {
8304 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8305 _assert(errno == ENOENT);
8306 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8307 _assert(errno == ENOENT);
8310 _assert(pkgInitConfig(*_config));
8311 _assert(pkgInitSystem(*_config, _system));
8314 _config->Set("APT::Acquire::Translation", lang);
8315 _config->Set("Acquire::http::Timeout", 15);
8316 _config->Set("Acquire::http::MaxParallel", 4);
8318 /* Color Choices {{{ */
8319 space_ = CGColorSpaceCreateDeviceRGB();
8321 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8322 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8323 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8324 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8325 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8326 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8327 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8328 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8329 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8330 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8331 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8332 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8333 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8334 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8335 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8338 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8339 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8342 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8344 /* UIKit Configuration {{{ */
8345 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8346 if ($GSFontSetUseLegacyFontMetrics != NULL)
8347 $GSFontSetUseLegacyFontMetrics(YES);
8349 UIKeyboardDisableAutomaticAppearance();
8353 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8355 CGColorSpaceRelease(space_);