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 NSString *StripVersion(const char *version) {
1142 const char *colon(strchr(version, ':'));
1144 version = colon + 1;
1145 return [NSString stringWithUTF8String:version];
1148 NSString *LocalizeSection(NSString *section) {
1149 static Pcre title_r("^(.*?) \\((.*)\\)$");
1150 if (title_r(section)) {
1151 NSString *parent(title_r[1]);
1152 NSString *child(title_r[2]);
1154 return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"),
1155 LocalizeSection(parent),
1156 LocalizeSection(child)
1160 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1163 NSString *Simplify(NSString *title) {
1164 const char *data = [title UTF8String];
1165 size_t size = [title length];
1167 static Pcre square_r("^\\[(.*)\\]$");
1168 if (square_r(data, size))
1169 return Simplify(square_r[1]);
1171 static Pcre paren_r("^\\((.*)\\)$");
1172 if (paren_r(data, size))
1173 return Simplify(paren_r[1]);
1175 static Pcre title_r("^(.*?) \\((.*)\\)$");
1176 if (title_r(data, size))
1177 return Simplify(title_r[1]);
1183 bool isSectionVisible(NSString *section) {
1184 NSDictionary *metadata([Sections_ objectForKey:section]);
1185 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1186 return hidden == nil || ![hidden boolValue];
1189 /* Delegate Prototypes {{{ */
1193 @interface NSObject (ProgressDelegate)
1196 @implementation NSObject(ProgressDelegate)
1198 - (void) _setProgressError:(NSArray *)args {
1199 [self performSelector:@selector(setProgressError:forPackage:)
1200 withObject:[args objectAtIndex:0]
1201 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1207 @protocol ProgressDelegate
1208 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1209 - (void) setProgressTitle:(NSString *)title;
1210 - (void) setProgressPercent:(float)percent;
1211 - (void) startProgress;
1212 - (void) addProgressOutput:(NSString *)output;
1213 - (bool) isCancelling:(size_t)received;
1216 @protocol ConfigurationDelegate
1217 - (void) repairWithSelector:(SEL)selector;
1218 - (void) setConfigurationData:(NSString *)data;
1223 @protocol CydiaDelegate
1224 - (void) setPackageView:(PackageView *)view;
1225 - (void) clearPackage:(Package *)package;
1226 - (void) installPackage:(Package *)package;
1227 - (void) removePackage:(Package *)package;
1228 - (void) slideUp:(UIActionSheet *)alert;
1229 - (void) distUpgrade;
1230 - (void) updateData;
1232 - (void) askForSettings;
1233 - (UIProgressHUD *) addProgressHUD;
1234 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1235 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag;
1236 - (RVPage *) pageForPackage:(NSString *)name;
1237 - (void) openMailToURL:(NSURL *)url;
1238 - (void) clearFirstResponder;
1239 - (PackageView *) packageView;
1243 /* Status Delegation {{{ */
1245 public pkgAcquireStatus
1248 _transient NSObject<ProgressDelegate> *delegate_;
1256 void setDelegate(id delegate) {
1257 delegate_ = delegate;
1260 virtual bool MediaChange(std::string media, std::string drive) {
1264 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1267 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1268 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1269 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
1272 virtual void Done(pkgAcquire::ItemDesc &item) {
1275 virtual void Fail(pkgAcquire::ItemDesc &item) {
1277 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1278 item.Owner->Status == pkgAcquire::Item::StatDone
1282 std::string &error(item.Owner->ErrorText);
1286 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1287 NSArray *fields([description componentsSeparatedByString:@" "]);
1288 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1290 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1291 withObject:[NSArray arrayWithObjects:
1292 [NSString stringWithUTF8String:error.c_str()],
1299 virtual bool Pulse(pkgAcquire *Owner) {
1300 bool value = pkgAcquireStatus::Pulse(Owner);
1303 double(CurrentBytes + CurrentItems) /
1304 double(TotalBytes + TotalItems)
1307 [delegate_ setProgressPercent:percent];
1308 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1311 virtual void Start() {
1312 [delegate_ startProgress];
1315 virtual void Stop() {
1319 /* Progress Delegation {{{ */
1324 _transient id<ProgressDelegate> delegate_;
1327 virtual void Update() {
1328 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1329 [delegate_ setProgressPercent:(Percent / 100)];*/
1338 void setDelegate(id delegate) {
1339 delegate_ = delegate;
1342 virtual void Done() {
1343 //[delegate_ setProgressPercent:1];
1348 /* Database Interface {{{ */
1349 typedef std::map< unsigned long, _H<Source> > SourceMap;
1351 @interface Database : NSObject {
1357 pkgCacheFile cache_;
1358 pkgDepCache::Policy *policy_;
1359 pkgRecords *records_;
1360 pkgProblemResolver *resolver_;
1361 pkgAcquire *fetcher_;
1363 SPtr<pkgPackageManager> manager_;
1364 pkgSourceList *list_;
1367 NSMutableArray *packages_;
1369 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1378 + (Database *) sharedInstance;
1381 - (void) _readCydia:(NSNumber *)fd;
1382 - (void) _readStatus:(NSNumber *)fd;
1383 - (void) _readOutput:(NSNumber *)fd;
1387 - (Package *) packageWithName:(NSString *)name;
1389 - (pkgCacheFile &) cache;
1390 - (pkgDepCache::Policy *) policy;
1391 - (pkgRecords *) records;
1392 - (pkgProblemResolver *) resolver;
1393 - (pkgAcquire &) fetcher;
1394 - (pkgSourceList &) list;
1395 - (NSArray *) packages;
1396 - (NSArray *) sources;
1397 - (void) reloadData;
1405 - (void) updateWithStatus:(Status &)status;
1407 - (void) setDelegate:(id)delegate;
1408 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1412 /* Source Class {{{ */
1413 @interface Source : NSObject {
1414 NSString *description_;
1420 NSString *distribution_;
1424 NSString *defaultIcon_;
1426 NSDictionary *record_;
1430 - (Source *) initWithMetaIndex:(metaIndex *)index;
1432 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1434 - (NSString *) supportForPackage:(NSString *)package;
1436 - (NSDictionary *) record;
1440 - (NSString *) distribution;
1441 - (NSString *) type;
1443 - (NSString *) host;
1445 - (NSString *) name;
1446 - (NSString *) description;
1447 - (NSString *) label;
1448 - (NSString *) origin;
1449 - (NSString *) version;
1451 - (NSString *) defaultIcon;
1455 @implementation Source
1457 #define _clear(field) \
1464 _clear(distribution_)
1467 _clear(description_)
1472 _clear(defaultIcon_)
1481 + (NSArray *) _attributeKeys {
1482 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1485 - (NSArray *) attributeKeys {
1486 return [[self class] _attributeKeys];
1489 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1490 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1493 - (void) setMetaIndex:(metaIndex *)index {
1496 trusted_ = index->IsTrusted();
1498 uri_ = [[NSString stringWithUTF8String:index->GetURI().c_str()] retain];
1499 distribution_ = [[NSString stringWithUTF8String:index->GetDist().c_str()] retain];
1500 type_ = [[NSString stringWithUTF8String:index->GetType()] retain];
1502 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1503 if (dindex != NULL) {
1504 std::ifstream release(dindex->MetaIndexFile("Release").c_str());
1506 while (std::getline(release, line)) {
1507 std::string::size_type colon(line.find(':'));
1508 if (colon == std::string::npos)
1511 std::string name(line.substr(0, colon));
1512 std::string value(line.substr(colon + 1));
1513 while (!value.empty() && value[0] == ' ')
1514 value = value.substr(1);
1516 if (name == "Default-Icon")
1517 defaultIcon_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1518 else if (name == "Description")
1519 description_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1520 else if (name == "Label")
1521 label_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1522 else if (name == "Origin")
1523 origin_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1524 else if (name == "Support")
1525 support_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1526 else if (name == "Version")
1527 version_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1531 record_ = [Sources_ objectForKey:[self key]];
1533 record_ = [record_ retain];
1536 - (Source *) initWithMetaIndex:(metaIndex *)index {
1537 if ((self = [super init]) != nil) {
1538 [self setMetaIndex:index];
1542 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1543 NSDictionary *lhr = [self record];
1544 NSDictionary *rhr = [source record];
1547 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1549 NSString *lhs = [self name];
1550 NSString *rhs = [source name];
1552 if ([lhs length] != 0 && [rhs length] != 0) {
1553 unichar lhc = [lhs characterAtIndex:0];
1554 unichar rhc = [rhs characterAtIndex:0];
1556 if (isalpha(lhc) && !isalpha(rhc))
1557 return NSOrderedAscending;
1558 else if (!isalpha(lhc) && isalpha(rhc))
1559 return NSOrderedDescending;
1562 return [lhs compare:rhs options:LaxCompareOptions_];
1565 - (NSString *) supportForPackage:(NSString *)package {
1566 return support_ == nil ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1569 - (NSDictionary *) record {
1577 - (NSString *) uri {
1581 - (NSString *) distribution {
1582 return distribution_;
1585 - (NSString *) type {
1589 - (NSString *) key {
1590 return [NSString stringWithFormat:@"%@:%@:%@", type_, uri_, distribution_];
1593 - (NSString *) host {
1594 return [[[NSURL URLWithString:[self uri]] host] lowercaseString];
1597 - (NSString *) name {
1598 return origin_ == nil ? [self host] : origin_;
1601 - (NSString *) description {
1602 return description_;
1605 - (NSString *) label {
1606 return label_ == nil ? [self host] : label_;
1609 - (NSString *) origin {
1613 - (NSString *) version {
1617 - (NSString *) defaultIcon {
1618 return defaultIcon_;
1623 /* Relationship Class {{{ */
1624 @interface Relationship : NSObject {
1629 - (NSString *) type;
1631 - (NSString *) name;
1635 @implementation Relationship
1643 - (NSString *) type {
1651 - (NSString *) name {
1658 /* Package Class {{{ */
1659 @interface Package : NSObject {
1663 pkgCache::VerIterator version_;
1664 pkgCache::PkgIterator iterator_;
1665 _transient Database *database_;
1666 pkgCache::VerFileIterator file_;
1673 NSString *section$_;
1678 NSString *installed_;
1684 CYString depiction_;
1697 NSArray *relationships_;
1699 NSMutableDictionary *metadata_;
1700 _transient NSDate *firstSeen_;
1701 _transient NSDate *lastSeen_;
1705 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1706 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1708 - (pkgCache::PkgIterator) iterator;
1711 - (NSString *) section;
1712 - (NSString *) simpleSection;
1714 - (NSString *) longSection;
1715 - (NSString *) shortSection;
1719 - (Address *) maintainer;
1721 - (NSString *) longDescription;
1722 - (NSString *) shortDescription;
1725 - (NSMutableDictionary *) metadata;
1727 - (BOOL) subscribed;
1730 - (NSString *) latest;
1731 - (NSString *) installed;
1734 - (BOOL) upgradableAndEssential:(BOOL)essential;
1737 - (BOOL) unfiltered;
1741 - (BOOL) halfConfigured;
1742 - (BOOL) halfInstalled;
1744 - (NSString *) mode;
1747 - (NSString *) name;
1749 - (NSString *) homepage;
1750 - (NSString *) depiction;
1751 - (Address *) author;
1753 - (NSString *) support;
1755 - (NSArray *) files;
1756 - (NSArray *) relationships;
1757 - (NSArray *) warnings;
1758 - (NSArray *) applications;
1760 - (Source *) source;
1761 - (NSString *) role;
1763 - (BOOL) matches:(NSString *)text;
1765 - (bool) hasSupportingRole;
1766 - (BOOL) hasTag:(NSString *)tag;
1767 - (NSString *) primaryPurpose;
1768 - (NSArray *) purposes;
1769 - (bool) isCommercial;
1771 - (CYString &) cyname;
1773 - (uint32_t) compareBySection:(NSArray *)sections;
1775 - (uint32_t) compareForChanges;
1780 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1781 - (bool) isInstalledAndVisible:(NSNumber *)number;
1782 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1783 - (bool) isVisibleInSource:(Source *)source;
1787 uint32_t PackageChangesRadix(Package *self, void *) {
1792 uint32_t timestamp : 30;
1793 uint32_t ignored : 1;
1794 uint32_t upgradable : 1;
1798 bool upgradable([self upgradableAndEssential:YES]);
1799 value.bits.upgradable = upgradable ? 1 : 0;
1802 value.bits.timestamp = 0;
1803 value.bits.ignored = [self ignored] ? 0 : 1;
1804 value.bits.upgradable = 1;
1806 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1807 value.bits.ignored = 0;
1808 value.bits.upgradable = 0;
1811 return _not(uint32_t) - value.key;
1814 _finline static void Stifle(uint8_t &value) {
1817 uint32_t PackagePrefixRadix(Package *self, void *context) {
1818 size_t offset(reinterpret_cast<size_t>(context));
1819 CYString &name([self cyname]);
1821 size_t size(name.size());
1824 char *text(name.data());
1827 if (!isdigit(text[0]))
1831 while (size != digits && isdigit(text[digits]))
1841 if (offset == 0 && zeros != 0) {
1842 memset(data, '0', zeros);
1843 memcpy(data + zeros, text, 4 - zeros);
1845 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1846 if (size <= offset - zeros)
1849 text += offset - zeros;
1850 size -= offset - zeros;
1853 memcpy(data, text, 4);
1855 memcpy(data, text, size);
1856 memset(data + size, 0, 4 - size);
1859 for (size_t i(0); i != 4; ++i)
1860 if (isalpha(data[i]))
1865 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1867 /* XXX: ntohl may be more honest */
1868 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1871 CYString &(*PackageName)(Package *self, SEL sel);
1873 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1874 _profile(PackageNameCompare)
1875 CYString &lhi(PackageName(lhs, @selector(cyname)));
1876 CYString &rhi(PackageName(rhs, @selector(cyname)));
1877 CFStringRef lhn(lhi), rhn(rhi);
1879 _profile(PackageNameCompare$NumbersLast)
1880 if (!lhi.empty() && !rhi.empty()) {
1881 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1882 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1883 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1884 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1885 return lha ? NSOrderedAscending : NSOrderedDescending;
1889 CFIndex length = CFStringGetLength(lhn);
1891 _profile(PackageNameCompare$Compare)
1892 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1897 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1898 return PackageNameCompare(*lhs, *rhs, context);
1901 struct PackageNameOrdering :
1902 std::binary_function<Package *, Package *, bool>
1904 _finline bool operator ()(Package *lhs, Package *rhs) const {
1905 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1909 @implementation Package
1911 - (NSString *) description {
1912 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1918 if (section$_ != nil)
1919 [section$_ release];
1923 if (installed_ != nil)
1924 [installed_ release];
1926 if (sponsor$_ != nil)
1927 [sponsor$_ release];
1928 if (author$_ != nil)
1935 if (relationships_ != nil)
1936 [relationships_ release];
1937 if (metadata_ != nil)
1938 [metadata_ release];
1943 + (NSString *) webScriptNameForSelector:(SEL)selector {
1944 if (selector == @selector(hasTag:))
1950 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1951 return [self webScriptNameForSelector:selector] == nil;
1954 + (NSArray *) _attributeKeys {
1955 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];
1958 - (NSArray *) attributeKeys {
1959 return [[self class] _attributeKeys];
1962 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1963 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1973 _profile(Package$parse)
1974 pkgRecords::Parser *parser;
1976 _profile(Package$parse$Lookup)
1977 parser = &[database_ records]->Lookup(file_);
1982 _profile(Package$parse$Find)
1988 {"depiction", &depiction_},
1989 {"homepage", &homepage_},
1990 {"website", &website},
1991 {"support", &support_},
1992 {"sponsor", &sponsor_},
1993 {"author", &author_},
1996 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1997 const char *start, *end;
1999 if (parser->Find(names[i].name_, start, end)) {
2000 CYString &value(*names[i].value_);
2001 _profile(Package$parse$Value)
2002 value.set(pool_, start, end - start);
2008 _profile(Package$parse$Tagline)
2009 const char *start, *end;
2010 if (parser->Find("Description", start, end)) {
2011 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2014 while (stop != start && stop[-1] == '\r')
2016 tagline_.set(pool_, start, stop - start);
2020 _profile(Package$parse$Retain)
2021 if (!homepage_.empty())
2022 homepage_ = website;
2023 if (homepage_ == depiction_)
2029 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2030 if ((self = [super init]) != nil) {
2031 _profile(Package$initWithVersion)
2032 @synchronized (database) {
2033 era_ = [database era];
2037 iterator_ = version.ParentPkg();
2038 database_ = database;
2040 _profile(Package$initWithVersion$Latest)
2041 latest_ = [StripVersion(version_.VerStr()) retain];
2044 pkgCache::VerIterator current;
2045 _profile(Package$initWithVersion$Versions)
2046 current = iterator_.CurrentVer();
2048 installed_ = [StripVersion(current.VerStr()) retain];
2050 if (!version_.end())
2051 file_ = version_.FileList();
2053 pkgCache &cache([database_ cache]);
2054 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2058 _profile(Package$initWithVersion$Name)
2059 id_.set(pool_, iterator_.Name());
2063 _profile(Package$initWithVersion$Source)
2064 source_ = [database_ getSource:file_.File()];
2071 /* XXX: get the damned Name */
2073 _profile(Package$initWithVersion$Tags)
2075 for (NSString *tag in tags_)
2076 if ([tag hasPrefix:@"role::"]) {
2077 role_ = [[tag substringFromIndex:6] retain];
2082 bool changed(false);
2083 NSString *key([id_ lowercaseString]);
2085 _profile(Package$initWithVersion$Metadata)
2086 metadata_ = [Packages_ objectForKey:key];
2088 if (metadata_ == nil) {
2089 firstSeen_ = [now_ retain];
2091 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2092 firstSeen_, @"FirstSeen",
2093 latest_, @"LastVersion",
2098 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2099 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2101 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2102 subscribed_ = [subscribed boolValue];
2104 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2106 if (firstSeen_ == nil) {
2107 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2108 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2112 if (version == nil) {
2113 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2115 } else if (![version isEqualToString:latest_]) {
2116 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2118 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2123 metadata_ = [metadata_ retain];
2126 [Packages_ setObject:metadata_ forKey:key];
2131 _profile(Package$initWithVersion$Section)
2132 section_.set(pool_, iterator_.Section());
2135 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2136 visible_ = [self hasSupportingRole] && [self unfiltered];
2137 } _end } return self;
2140 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2141 pkgCache::VerIterator version;
2143 _profile(Package$packageWithIterator$GetCandidateVer)
2144 version = [database policy]->GetCandidateVer(iterator);
2150 return [[[Package alloc]
2151 initWithVersion:version
2158 - (pkgCache::PkgIterator) iterator {
2162 - (NSString *) section {
2163 if (section$_ == nil) {
2164 if (section_.empty())
2167 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2168 NSString *name(section_);
2171 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2172 if (NSString *rename = [value objectForKey:@"Rename"]) {
2177 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2181 - (NSString *) simpleSection {
2182 if (NSString *section = [self section])
2183 return Simplify(section);
2188 - (NSString *) longSection {
2189 return LocalizeSection(section_);
2192 - (NSString *) shortSection {
2193 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2196 - (NSString *) uri {
2199 pkgIndexFile *index;
2200 pkgCache::PkgFileIterator file(file_.File());
2201 if (![database_ list].FindIndex(file, index))
2203 return [NSString stringWithUTF8String:iterator_->Path];
2204 //return [NSString stringWithUTF8String:file.Site()];
2205 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2209 - (Address *) maintainer {
2212 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2213 const std::string &maintainer(parser->Maintainer());
2214 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2218 return version_.end() ? 0 : version_->InstalledSize;
2221 - (NSString *) longDescription {
2224 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2225 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2227 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2228 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2229 if ([lines count] < 2)
2232 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2233 for (size_t i(1), e([lines count]); i != e; ++i) {
2234 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2235 [trimmed addObject:trim];
2238 return [trimmed componentsJoinedByString:@"\n"];
2241 - (NSString *) shortDescription {
2246 _profile(Package$index)
2247 CFStringRef name((CFStringRef) [self name]);
2248 if (CFStringGetLength(name) == 0)
2250 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2251 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2253 return toupper(character);
2257 - (NSMutableDictionary *) metadata {
2262 if (subscribed_ && lastSeen_ != nil)
2267 - (BOOL) subscribed {
2272 NSDictionary *metadata([self metadata]);
2273 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2274 return [ignored boolValue];
2279 - (NSString *) latest {
2283 - (NSString *) installed {
2288 return !version_.end();
2291 - (BOOL) upgradableAndEssential:(BOOL)essential {
2292 _profile(Package$upgradableAndEssential)
2293 pkgCache::VerIterator current(iterator_.CurrentVer());
2295 return essential && essential_ && visible_;
2297 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2301 - (BOOL) essential {
2306 return [database_ cache][iterator_].InstBroken();
2309 - (BOOL) unfiltered {
2310 NSString *section([self section]);
2311 return section == nil || isSectionVisible(section);
2319 unsigned char current(iterator_->CurrentState);
2320 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2323 - (BOOL) halfConfigured {
2324 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2327 - (BOOL) halfInstalled {
2328 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2332 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2333 return state.Mode != pkgDepCache::ModeKeep;
2336 - (NSString *) mode {
2337 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2339 switch (state.Mode) {
2340 case pkgDepCache::ModeDelete:
2341 if ((state.iFlags & pkgDepCache::Purge) != 0)
2345 case pkgDepCache::ModeKeep:
2346 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2347 return @"REINSTALL";
2348 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2352 case pkgDepCache::ModeInstall:
2353 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2354 return @"REINSTALL";
2355 else*/ switch (state.Status) {
2357 return @"DOWNGRADE";
2363 return @"NEW_INSTALL";
2376 - (NSString *) name {
2377 return name_.empty() ? id_ : name_;
2380 - (UIImage *) icon {
2381 NSString *section = [self simpleSection];
2385 if ([icon_ hasPrefix:@"file:///"])
2386 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2387 if (icon == nil) if (section != nil)
2388 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2389 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2390 if ([dicon hasPrefix:@"file:///"])
2391 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2393 icon = [UIImage applicationImageNamed:@"unknown.png"];
2397 - (NSString *) homepage {
2401 - (NSString *) depiction {
2405 - (Address *) sponsor {
2406 if (sponsor$_ == nil) {
2407 if (sponsor_.empty())
2409 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2413 - (Address *) author {
2414 if (author$_ == nil) {
2415 if (author_.empty())
2417 author$_ = [[Address addressWithString:author_] retain];
2421 - (NSString *) support {
2422 return !support_.empty() ? support_ : [[self source] supportForPackage:id_];
2425 - (NSArray *) files {
2426 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2427 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2430 fin.open([path UTF8String]);
2435 while (std::getline(fin, line))
2436 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2441 - (NSArray *) relationships {
2442 return relationships_;
2445 - (NSArray *) warnings {
2446 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2447 const char *name(iterator_.Name());
2449 size_t length(strlen(name));
2450 if (length < 2) invalid:
2451 [warnings addObject:CYLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2452 else for (size_t i(0); i != length; ++i)
2454 /* XXX: technically this is not allowed */
2455 (name[i] < 'A' || name[i] > 'Z') &&
2456 (name[i] < 'a' || name[i] > 'z') &&
2457 (name[i] < '0' || name[i] > '9') &&
2458 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2461 if (strcmp(name, "cydia") != 0) {
2463 bool _private = false;
2466 bool repository = [[self section] isEqualToString:@"Repositories"];
2468 if (NSArray *files = [self files])
2469 for (NSString *file in files)
2470 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2472 else if (!_private && [file isEqualToString:@"/private"])
2474 else if (!stash && [file isEqualToString:@"/var/stash"])
2477 /* XXX: this is not sensitive enough. only some folders are valid. */
2478 if (cydia && !repository)
2479 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2481 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/private"]];
2483 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2486 return [warnings count] == 0 ? nil : warnings;
2489 - (NSArray *) applications {
2490 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2492 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2494 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2495 if (NSArray *files = [self files])
2496 for (NSString *file in files)
2497 if (application_r(file)) {
2498 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2499 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2500 if ([id isEqualToString:me])
2503 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2505 display = application_r[1];
2507 NSString *bundle([file stringByDeletingLastPathComponent]);
2508 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2509 if (icon == nil || [icon length] == 0)
2511 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2513 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2514 [applications addObject:application];
2516 [application addObject:id];
2517 [application addObject:display];
2518 [application addObject:url];
2521 return [applications count] == 0 ? nil : applications;
2524 - (Source *) source {
2526 @synchronized (database_) {
2527 if ([database_ era] != era_ || file_.end())
2530 source_ = [database_ getSource:file_.File()];
2542 - (NSString *) role {
2546 - (BOOL) matches:(NSString *)text {
2552 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2553 if (range.location != NSNotFound)
2556 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2557 if (range.location != NSNotFound)
2560 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2561 if (range.location != NSNotFound)
2567 - (bool) hasSupportingRole {
2570 if ([role_ isEqualToString:@"enduser"])
2572 if ([Role_ isEqualToString:@"User"])
2574 if ([role_ isEqualToString:@"hacker"])
2576 if ([Role_ isEqualToString:@"Hacker"])
2578 if ([role_ isEqualToString:@"developer"])
2580 if ([Role_ isEqualToString:@"Developer"])
2585 - (BOOL) hasTag:(NSString *)tag {
2586 return tags_ == nil ? NO : [tags_ containsObject:tag];
2589 - (NSString *) primaryPurpose {
2590 for (NSString *tag in tags_)
2591 if ([tag hasPrefix:@"purpose::"])
2592 return [tag substringFromIndex:9];
2596 - (NSArray *) purposes {
2597 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2598 for (NSString *tag in tags_)
2599 if ([tag hasPrefix:@"purpose::"])
2600 [purposes addObject:[tag substringFromIndex:9]];
2601 return [purposes count] == 0 ? nil : purposes;
2604 - (bool) isCommercial {
2605 return [self hasTag:@"cydia::commercial"];
2608 - (CYString &) cyname {
2609 return name_.empty() ? id_ : name_;
2612 - (uint32_t) compareBySection:(NSArray *)sections {
2613 NSString *section([self section]);
2614 for (size_t i(0), e([sections count]); i != e; ++i) {
2615 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2619 return _not(uint32_t);
2622 - (uint32_t) compareForChanges {
2627 uint32_t timestamp : 30;
2628 uint32_t ignored : 1;
2629 uint32_t upgradable : 1;
2633 bool upgradable([self upgradableAndEssential:YES]);
2634 value.bits.upgradable = upgradable ? 1 : 0;
2637 value.bits.timestamp = 0;
2638 value.bits.ignored = [self ignored] ? 0 : 1;
2639 value.bits.upgradable = 1;
2641 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2642 value.bits.ignored = 0;
2643 value.bits.upgradable = 0;
2646 return _not(uint32_t) - value.key;
2650 pkgProblemResolver *resolver = [database_ resolver];
2651 resolver->Clear(iterator_);
2652 resolver->Protect(iterator_);
2656 pkgProblemResolver *resolver = [database_ resolver];
2657 resolver->Clear(iterator_);
2658 resolver->Protect(iterator_);
2659 pkgCacheFile &cache([database_ cache]);
2660 cache->MarkInstall(iterator_, false);
2661 pkgDepCache::StateCache &state((*cache)[iterator_]);
2662 if (!state.Install())
2663 cache->SetReInstall(iterator_, true);
2667 pkgProblemResolver *resolver = [database_ resolver];
2668 resolver->Clear(iterator_);
2669 resolver->Protect(iterator_);
2670 resolver->Remove(iterator_);
2671 [database_ cache]->MarkDelete(iterator_, true);
2674 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2675 _profile(Package$isUnfilteredAndSearchedForBy)
2678 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2679 value &= [self unfiltered];
2682 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2683 value &= [self matches:search];
2690 - (bool) isInstalledAndVisible:(NSNumber *)number {
2691 return (![number boolValue] || [self visible]) && [self installed] != nil;
2694 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2695 NSString *section = [self section];
2699 [self installed] == nil && (
2701 section == nil && [name length] == 0 ||
2702 [name isEqualToString:section]
2706 - (bool) isVisibleInSource:(Source *)source {
2707 return [self source] == source && [self visible];
2712 /* Section Class {{{ */
2713 @interface Section : NSObject {
2718 NSString *localized_;
2721 - (NSComparisonResult) compareByLocalized:(Section *)section;
2722 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2723 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2724 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2725 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2726 - (NSString *) name;
2733 - (void) addToCount;
2735 - (void) setCount:(size_t)count;
2736 - (NSString *) localized;
2740 @implementation Section
2744 if (localized_ != nil)
2745 [localized_ release];
2749 - (NSComparisonResult) compareByLocalized:(Section *)section {
2750 NSString *lhs(localized_);
2751 NSString *rhs([section localized]);
2753 /*if ([lhs length] != 0 && [rhs length] != 0) {
2754 unichar lhc = [lhs characterAtIndex:0];
2755 unichar rhc = [rhs characterAtIndex:0];
2757 if (isalpha(lhc) && !isalpha(rhc))
2758 return NSOrderedAscending;
2759 else if (!isalpha(lhc) && isalpha(rhc))
2760 return NSOrderedDescending;
2763 return [lhs compare:rhs options:LaxCompareOptions_];
2766 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2767 if ((self = [self initWithName:name localize:NO]) != nil) {
2768 if (localized != nil)
2769 localized_ = [localized retain];
2773 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2774 return [self initWithName:name row:0 localize:localize];
2777 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2778 if ((self = [super init]) != nil) {
2779 name_ = [name retain];
2783 localized_ = [LocalizeSection(name_) retain];
2787 /* XXX: localize the index thingees */
2788 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2789 if ((self = [super init]) != nil) {
2790 name_ = [(index == '#' ? @"123" : [NSString stringWithCharacters:&index length:1]) retain];
2796 - (NSString *) name {
2816 - (void) addToCount {
2820 - (void) setCount:(size_t)count {
2824 - (NSString *) localized {
2832 static NSArray *Finishes_;
2834 /* Database Implementation {{{ */
2835 @implementation Database
2837 + (Database *) sharedInstance {
2838 static Database *instance;
2839 if (instance == nil)
2840 instance = [[Database alloc] init];
2850 NSRecycleZone(zone_);
2851 // XXX: malloc_destroy_zone(zone_);
2852 apr_pool_destroy(pool_);
2856 - (void) _readCydia:(NSNumber *)fd { _pooled
2857 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2858 std::istream is(&ib);
2861 static Pcre finish_r("^finish:([^:]*)$");
2863 while (std::getline(is, line)) {
2864 const char *data(line.c_str());
2865 size_t size = line.size();
2866 lprintf("C:%s\n", data);
2868 if (finish_r(data, size)) {
2869 NSString *finish = finish_r[1];
2870 int index = [Finishes_ indexOfObject:finish];
2871 if (index != INT_MAX && index > Finish_)
2879 - (void) _readStatus:(NSNumber *)fd { _pooled
2880 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2881 std::istream is(&ib);
2884 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2885 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2887 while (std::getline(is, line)) {
2888 const char *data(line.c_str());
2889 size_t size = line.size();
2890 lprintf("S:%s\n", data);
2892 if (conffile_r(data, size)) {
2893 [delegate_ setConfigurationData:conffile_r[1]];
2894 } else if (strncmp(data, "status: ", 8) == 0) {
2895 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2896 [delegate_ setProgressTitle:string];
2897 } else if (pmstatus_r(data, size)) {
2898 std::string type([pmstatus_r[1] UTF8String]);
2899 NSString *id = pmstatus_r[2];
2901 float percent([pmstatus_r[3] floatValue]);
2902 [delegate_ setProgressPercent:(percent / 100)];
2904 NSString *string = pmstatus_r[4];
2906 if (type == "pmerror")
2907 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2908 withObject:[NSArray arrayWithObjects:string, id, nil]
2911 else if (type == "pmstatus") {
2912 [delegate_ setProgressTitle:string];
2913 } else if (type == "pmconffile")
2914 [delegate_ setConfigurationData:string];
2915 else _assert(false);
2916 } else _assert(false);
2922 - (void) _readOutput:(NSNumber *)fd { _pooled
2923 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2924 std::istream is(&ib);
2927 while (std::getline(is, line)) {
2928 lprintf("O:%s\n", line.c_str());
2929 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2939 - (Package *) packageWithName:(NSString *)name {
2940 if (static_cast<pkgDepCache *>(cache_) == NULL)
2942 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
2943 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
2946 - (Database *) init {
2947 if ((self = [super init]) != nil) {
2954 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
2955 apr_pool_create(&pool_, NULL);
2957 packages_ = [[NSMutableArray alloc] init];
2961 _assert(pipe(fds) != -1);
2964 _config->Set("APT::Keep-Fds::", cydiafd_);
2965 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
2968 detachNewThreadSelector:@selector(_readCydia:)
2970 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2973 _assert(pipe(fds) != -1);
2977 detachNewThreadSelector:@selector(_readStatus:)
2979 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2982 _assert(pipe(fds) != -1);
2983 _assert(dup2(fds[0], 0) != -1);
2984 _assert(close(fds[0]) != -1);
2986 input_ = fdopen(fds[1], "a");
2988 _assert(pipe(fds) != -1);
2989 _assert(dup2(fds[1], 1) != -1);
2990 _assert(close(fds[1]) != -1);
2993 detachNewThreadSelector:@selector(_readOutput:)
2995 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3000 - (pkgCacheFile &) cache {
3004 - (pkgDepCache::Policy *) policy {
3008 - (pkgRecords *) records {
3012 - (pkgProblemResolver *) resolver {
3016 - (pkgAcquire &) fetcher {
3020 - (pkgSourceList &) list {
3024 - (NSArray *) packages {
3028 - (NSArray *) sources {
3029 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3030 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3031 [sources addObject:i->second];
3035 - (NSArray *) issues {
3036 if (cache_->BrokenCount() == 0)
3039 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3041 for (Package *package in packages_) {
3042 if (![package broken])
3044 pkgCache::PkgIterator pkg([package iterator]);
3046 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3047 [entry addObject:[package name]];
3048 [issues addObject:entry];
3050 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3054 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3055 pkgCache::DepIterator start;
3056 pkgCache::DepIterator end;
3057 dep.GlobOr(start, end); // ++dep
3059 if (!cache_->IsImportantDep(end))
3061 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3064 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3065 [entry addObject:failure];
3066 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3068 Package *package([self packageWithName:[NSString stringWithUTF8String:start.TargetPkg().Name()]]);
3069 [failure addObject:[package name]];
3071 pkgCache::PkgIterator target(start.TargetPkg());
3072 if (target->ProvidesList != 0)
3073 [failure addObject:@"?"];
3075 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3077 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3078 else if (!cache_[target].CandidateVerIter(cache_).end())
3079 [failure addObject:@"-"];
3080 else if (target->ProvidesList == 0)
3081 [failure addObject:@"!"];
3083 [failure addObject:@"%"];
3087 if (start.TargetVer() != 0)
3088 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3099 - (void) reloadData { _pooled
3100 @synchronized (self) {
3122 apr_pool_clear(pool_);
3123 NSRecycleZone(zone_);
3125 int chk(creat("/tmp/cydia.chk", 0644));
3130 if (!cache_.Open(progress_, true)) {
3132 if (!_error->PopMessage(error))
3135 lprintf("cache_.Open():[%s]\n", error.c_str());
3137 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3138 [delegate_ repairWithSelector:@selector(configure)];
3139 else if (error == "The package lists or status file could not be parsed or opened.")
3140 [delegate_ repairWithSelector:@selector(update)];
3141 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3142 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3143 // else if (error == "The list of sources could not be read.")
3144 else _assert(false);
3150 unlink("/tmp/cydia.chk");
3152 now_ = [[NSDate date] retain];
3154 policy_ = new pkgDepCache::Policy();
3155 records_ = new pkgRecords(cache_);
3156 resolver_ = new pkgProblemResolver(cache_);
3157 fetcher_ = new pkgAcquire(&status_);
3160 list_ = new pkgSourceList();
3161 _assert(list_->ReadMainList());
3163 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3164 _assert(pkgApplyStatus(cache_));
3166 if (cache_->BrokenCount() != 0) {
3167 _assert(pkgFixBroken(cache_));
3168 _assert(cache_->BrokenCount() == 0);
3169 _assert(pkgMinimizeUpgrade(cache_));
3175 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3176 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3177 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3178 // XXX: this could be more intelligent
3179 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3180 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3182 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source] autorelease];
3189 /*std::vector<Package *> packages;
3190 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3191 [packages_ release];
3194 [packages_ removeAllObjects];
3198 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3199 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3200 //packages.push_back(package);
3201 [packages_ addObject:package];
3205 /*if (packages.empty())
3206 packages_ = [[NSArray alloc] init];
3208 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3211 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3212 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3213 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3221 /*if (!packages.empty())
3222 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3223 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3225 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3227 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3229 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3235 - (void) configure {
3236 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3237 system([dpkg UTF8String]);
3245 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3246 _assert(!_error->PendingError());
3249 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3252 public pkgArchiveCleaner
3255 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3260 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3262 while (_error->PopMessage(error))
3263 lprintf("ArchiveCleaner: %s\n", error.c_str());
3268 pkgRecords records(cache_);
3270 lock_ = new FileFd();
3271 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3272 _assert(!_error->PendingError());
3275 // XXX: explain this with an error message
3276 _assert(list.ReadMainList());
3278 manager_ = (_system->CreatePM(cache_));
3279 _assert(manager_->GetArchives(fetcher_, &list, &records));
3280 _assert(!_error->PendingError());
3284 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3286 _assert(list.ReadMainList());
3287 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3288 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3291 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3296 bool failed = false;
3297 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3298 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3301 std::string uri = (*item)->DescURI();
3302 std::string error = (*item)->ErrorText;
3304 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3307 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3308 withObject:[NSArray arrayWithObjects:
3309 [NSString stringWithUTF8String:error.c_str()],
3321 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3323 if (_error->PendingError()) {
3328 if (result == pkgPackageManager::Failed) {
3333 if (result != pkgPackageManager::Completed) {
3338 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3340 _assert(list.ReadMainList());
3341 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3342 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3345 if (![before isEqualToArray:after])
3350 _assert(pkgDistUpgrade(cache_));
3354 [self updateWithStatus:status_];
3357 - (void) updateWithStatus:(Status &)status {
3359 _assert(list.ReadMainList());
3362 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3363 _assert(!_error->PendingError());
3365 pkgAcquire fetcher(&status);
3366 _assert(list.GetIndexes(&fetcher));
3368 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3369 bool failed = false;
3370 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3371 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3372 (*item)->Finished();
3376 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3377 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3378 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3381 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3386 - (void) setDelegate:(id)delegate {
3387 delegate_ = delegate;
3388 status_.setDelegate(delegate);
3389 progress_.setDelegate(delegate);
3392 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3393 return sources_[file->ID];
3399 /* PopUp Windows {{{ */
3400 @interface PopUpView : UIView {
3401 _transient id delegate_;
3402 UITransitionView *transition_;
3407 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3411 @implementation PopUpView
3414 [transition_ setDelegate:nil];
3415 [transition_ release];
3421 [transition_ transition:UITransitionPushFromTop toView:nil];
3424 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3425 if (from != nil && to == nil)
3426 [self removeFromSuperview];
3429 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3430 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3431 delegate_ = delegate;
3433 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3434 [self addSubview:transition_];
3436 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3438 [view addSubview:self];
3440 [transition_ setDelegate:self];
3442 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3443 [transition_ transition:UITransitionNone toView:blank];
3444 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3452 /* Mail Composition {{{ */
3453 @interface MailToView : PopUpView {
3454 MailComposeController *controller_;
3457 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
3461 @implementation MailToView
3464 [controller_ release];
3468 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
3472 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
3473 NSLog(@"did:%@", delivery);
3474 // [UIApp setStatusBarShowsProgress:NO];
3475 if ([controller error]){
3476 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3477 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3478 [mailAlertSheet setBodyText:[controller error]];
3479 [mailAlertSheet popupAlertAnimated:YES];
3483 - (void) showError {
3484 NSLog(@"%@", [controller_ error]);
3485 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3486 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3487 [mailAlertSheet setBodyText:[controller_ error]];
3488 [mailAlertSheet popupAlertAnimated:YES];
3491 - (void) deliverMessage { _pooled
3495 if (![controller_ deliverMessage])
3496 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
3499 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
3500 if ([controller_ needsDelivery])
3501 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
3506 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
3507 if ((self = [super initWithView:view delegate:delegate]) != nil) {
3508 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
3509 [controller_ setDelegate:self];
3510 [controller_ initializeUI];
3511 [controller_ setupForURL:url];
3513 UIView *view([controller_ view]);
3514 [overlay_ addSubview:view];
3522 /* Confirmation View {{{ */
3523 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3524 if (!iterator.end())
3525 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3526 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3528 pkgCache::PkgIterator package(dep.TargetPkg());
3531 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3538 @protocol ConfirmationViewDelegate
3544 @interface ConfirmationView : BrowserView {
3545 _transient Database *database_;
3546 UIActionSheet *essential_;
3553 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3557 @implementation ConfirmationView
3564 if (essential_ != nil)
3565 [essential_ release];
3571 [book_ popFromSuperviewAnimated:YES];
3574 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3575 NSString *context([sheet context]);
3577 if ([context isEqualToString:@"remove"]) {
3585 [delegate_ confirm];
3592 } else if ([context isEqualToString:@"unable"]) {
3596 [super alertSheet:sheet buttonClicked:button];
3599 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3600 [super webView:sender didClearWindowObject:window forFrame:frame];
3601 [window setValue:changes_ forKey:@"changes"];
3602 [window setValue:issues_ forKey:@"issues"];
3603 [window setValue:sizes_ forKey:@"sizes"];
3606 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3607 if ((self = [super initWithBook:book]) != nil) {
3608 database_ = database;
3610 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3611 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3612 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3613 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3614 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3618 pkgDepCache::Policy *policy([database_ policy]);
3620 pkgCacheFile &cache([database_ cache]);
3621 NSArray *packages = [database_ packages];
3622 for (Package *package in packages) {
3623 pkgCache::PkgIterator iterator = [package iterator];
3624 pkgDepCache::StateCache &state(cache[iterator]);
3626 NSString *name([package name]);
3628 if (state.NewInstall())
3629 [installing addObject:name];
3630 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3631 [reinstalling addObject:name];
3632 else if (state.Upgrade())
3633 [upgrading addObject:name];
3634 else if (state.Downgrade())
3635 [downgrading addObject:name];
3636 else if (state.Delete()) {
3637 if ([package essential])
3639 [removing addObject:name];
3642 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3643 substrate_ |= DepSubstrate(iterator.CurrentVer());
3648 else if (Advanced_ || true) {
3649 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
3651 essential_ = [[UIActionSheet alloc]
3652 initWithTitle:CYLocalize("REMOVING_ESSENTIALS")
3653 buttons:[NSArray arrayWithObjects:
3654 [NSString stringWithFormat:parenthetical, CYLocalize("CANCEL_OPERATION"), CYLocalize("SAFE")],
3655 [NSString stringWithFormat:parenthetical, CYLocalize("FORCE_REMOVAL"), CYLocalize("UNSAFE")],
3657 defaultButtonIndex:0
3663 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3665 [essential_ setBodyText:CYLocalize("REMOVING_ESSENTIALS_EX")];
3667 essential_ = [[UIActionSheet alloc]
3668 initWithTitle:CYLocalize("UNABLE_TO_COMPLY")
3669 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3670 defaultButtonIndex:0
3675 [essential_ setBodyText:CYLocalize("UNABLE_TO_COMPLY_EX")];
3678 changes_ = [[NSArray alloc] initWithObjects:
3686 issues_ = [database_ issues];
3688 issues_ = [issues_ retain];
3690 sizes_ = [[NSArray alloc] initWithObjects:
3691 SizeString([database_ fetcher].FetchNeeded()),
3692 SizeString([database_ fetcher].PartialPresent()),
3693 SizeString([database_ cache]->UsrSize()),
3696 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3700 - (NSString *) backButtonTitle {
3701 return CYLocalize("CONFIRM");
3704 - (NSString *) leftButtonTitle {
3705 return [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("CANCEL"), CYLocalize("QUEUE")];
3708 - (id) rightButtonTitle {
3709 return issues_ != nil ? nil : [super rightButtonTitle];
3712 - (id) _rightButtonTitle {
3713 #if AlwaysReload || IgnoreInstall
3714 return [super _rightButtonTitle];
3716 return CYLocalize("CONFIRM");
3720 - (void) _leftButtonClicked {
3725 - (void) _rightButtonClicked {
3727 return [super _rightButtonClicked];
3729 if (essential_ != nil)
3730 [essential_ popupAlertAnimated:YES];
3734 [delegate_ confirm];
3742 /* Progress Data {{{ */
3743 @interface ProgressData : NSObject {
3749 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3756 @implementation ProgressData
3758 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3759 if ((self = [super init]) != nil) {
3760 selector_ = selector;
3780 /* Progress View {{{ */
3781 @interface ProgressView : UIView <
3782 ConfigurationDelegate,
3785 _transient Database *database_;
3787 UIView *background_;
3788 UITransitionView *transition_;
3790 UINavigationBar *navbar_;
3791 UIProgressBar *progress_;
3792 UITextView *output_;
3793 UITextLabel *status_;
3794 UIPushButton *close_;
3797 SHA1SumValue springlist_;
3798 SHA1SumValue notifyconf_;
3799 SHA1SumValue sandplate_;
3802 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
3804 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
3805 - (void) setContentView:(UIView *)view;
3808 - (void) _retachThread;
3809 - (void) _detachNewThreadData:(ProgressData *)data;
3810 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
3816 @protocol ProgressViewDelegate
3817 - (void) progressViewIsComplete:(ProgressView *)sender;
3820 @implementation ProgressView
3823 [transition_ setDelegate:nil];
3824 [navbar_ setDelegate:nil];
3827 if (background_ != nil)
3828 [background_ release];
3829 [transition_ release];
3832 [progress_ release];
3839 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3840 if (bootstrap_ && from == overlay_ && to == view_)
3844 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
3845 if ((self = [super initWithFrame:frame]) != nil) {
3846 database_ = database;
3847 delegate_ = delegate;
3849 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3850 [transition_ setDelegate:self];
3852 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3855 [overlay_ setBackgroundColor:[UIColor blackColor]];
3857 background_ = [[UIView alloc] initWithFrame:[self bounds]];
3858 [background_ setBackgroundColor:[UIColor blackColor]];
3859 [self addSubview:background_];
3862 [self addSubview:transition_];
3864 CGSize navsize = [UINavigationBar defaultSize];
3865 CGRect navrect = {{0, 0}, navsize};
3867 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
3868 [overlay_ addSubview:navbar_];
3870 [navbar_ setBarStyle:1];
3871 [navbar_ setDelegate:self];
3873 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
3874 [navbar_ pushNavigationItem:navitem];
3876 CGRect bounds = [overlay_ bounds];
3877 CGSize prgsize = [UIProgressBar defaultSize];
3880 (bounds.size.width - prgsize.width) / 2,
3881 bounds.size.height - prgsize.height - 20
3884 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3885 [progress_ setStyle:0];
3887 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3889 bounds.size.height - prgsize.height - 50,
3890 bounds.size.width - 20,
3894 [status_ setColor:[UIColor whiteColor]];
3895 [status_ setBackgroundColor:[UIColor clearColor]];
3897 [status_ setCentersHorizontally:YES];
3898 //[status_ setFont:font];
3901 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3903 navrect.size.height + 20,
3904 bounds.size.width - 20,
3905 bounds.size.height - navsize.height - 62 - navrect.size.height
3909 //[output_ setTextFont:@"Courier New"];
3910 [output_ setTextSize:12];
3912 [output_ setTextColor:[UIColor whiteColor]];
3913 [output_ setBackgroundColor:[UIColor clearColor]];
3915 [output_ setMarginTop:0];
3916 [output_ setAllowsRubberBanding:YES];
3917 [output_ setEditable:NO];
3919 [overlay_ addSubview:output_];
3921 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3923 bounds.size.height - prgsize.height - 50,
3924 bounds.size.width - 20,
3928 [close_ setAutosizesToFit:NO];
3929 [close_ setDrawsShadow:YES];
3930 [close_ setStretchBackground:YES];
3931 [close_ setEnabled:YES];
3933 UIFont *bold = [UIFont boldSystemFontOfSize:22];
3934 [close_ setTitleFont:bold];
3936 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
3937 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
3938 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
3942 - (void) setContentView:(UIView *)view {
3943 view_ = [view retain];
3946 - (void) resetView {
3947 [transition_ transition:6 toView:view_];
3950 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3951 NSString *context([sheet context]);
3953 if ([context isEqualToString:@"error"])
3955 else if ([context isEqualToString:@"conffile"]) {
3956 FILE *input = [database_ input];
3960 fprintf(input, "N\n");
3964 fprintf(input, "Y\n");
3975 - (void) closeButtonPushed {
3984 [delegate_ suspendWithAnimation:YES];
3988 system("launchctl stop com.apple.SpringBoard");
3992 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4001 - (void) _retachThread {
4002 UINavigationItem *item = [navbar_ topItem];
4003 [item setTitle:CYLocalize("COMPLETE")];
4005 [overlay_ addSubview:close_];
4006 [progress_ removeFromSuperview];
4007 [status_ removeFromSuperview];
4009 [delegate_ progressViewIsComplete:self];
4012 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4013 MMap mmap(file, MMap::ReadOnly);
4015 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4016 if (!(sandplate_ == sha1.Result()))
4021 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4022 MMap mmap(file, MMap::ReadOnly);
4024 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4025 if (!(notifyconf_ == sha1.Result()))
4030 FileFd file(SpringBoard_, FileFd::ReadOnly);
4031 MMap mmap(file, MMap::ReadOnly);
4033 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4034 if (!(springlist_ == sha1.Result()))
4039 case 0: [close_ setTitle:CYLocalize("RETURN_TO_CYDIA")]; break;
4040 case 1: [close_ setTitle:CYLocalize("CLOSE_CYDIA")]; break;
4041 case 2: [close_ setTitle:CYLocalize("RESTART_SPRINGBOARD")]; break;
4042 case 3: [close_ setTitle:CYLocalize("RELOAD_SPRINGBOARD")]; break;
4043 case 4: [close_ setTitle:CYLocalize("REBOOT_DEVICE")]; break;
4046 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4048 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
4049 [cache autorelease];
4051 NSFileManager *manager = [NSFileManager defaultManager];
4052 NSError *error = nil;
4054 id system = [cache objectForKey:@"System"];
4059 if (stat(Cache_, &info) == -1)
4062 [system removeAllObjects];
4064 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4065 for (NSString *app in apps)
4066 if ([app hasSuffix:@".app"]) {
4067 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4068 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4069 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4071 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4072 [info setObject:path forKey:@"Path"];
4073 [info setObject:@"System" forKey:@"ApplicationType"];
4074 [system addInfoDictionary:info];
4080 [cache writeToFile:@Cache_ atomically:YES];
4082 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
4084 if (chmod(Cache_, info.st_mode) == -1)
4088 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4091 notify_post("com.apple.mobile.application_installed");
4093 [delegate_ setStatusBarShowsProgress:NO];
4096 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4097 [[data target] performSelector:[data selector] withObject:[data object]];
4100 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4103 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4104 UINavigationItem *item = [navbar_ topItem];
4105 [item setTitle:title];
4107 [status_ setText:nil];
4108 [output_ setText:@""];
4109 [progress_ setProgress:0];
4111 [close_ removeFromSuperview];
4112 [overlay_ addSubview:progress_];
4113 [overlay_ addSubview:status_];
4115 [delegate_ setStatusBarShowsProgress:YES];
4119 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4120 MMap mmap(file, MMap::ReadOnly);
4122 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4123 sandplate_ = sha1.Result();
4127 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4128 MMap mmap(file, MMap::ReadOnly);
4130 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4131 notifyconf_ = sha1.Result();
4135 FileFd file(SpringBoard_, FileFd::ReadOnly);
4136 MMap mmap(file, MMap::ReadOnly);
4138 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4139 springlist_ = sha1.Result();
4142 [transition_ transition:6 toView:overlay_];
4145 detachNewThreadSelector:@selector(_detachNewThreadData:)
4147 withObject:[[ProgressData alloc]
4148 initWithSelector:selector
4155 - (void) repairWithSelector:(SEL)selector {
4157 detachNewThreadSelector:selector
4160 title:CYLocalize("REPAIRING")
4164 - (void) setConfigurationData:(NSString *)data {
4166 performSelectorOnMainThread:@selector(_setConfigurationData:)
4172 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4173 Package *package = id == nil ? nil : [database_ packageWithName:id];
4175 UIActionSheet *sheet = [[[UIActionSheet alloc]
4176 initWithTitle:(package == nil ? id : [package name])
4177 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
4178 defaultButtonIndex:0
4183 [sheet setBodyText:error];
4184 [sheet popupAlertAnimated:YES];
4187 - (void) setProgressTitle:(NSString *)title {
4189 performSelectorOnMainThread:@selector(_setProgressTitle:)
4195 - (void) setProgressPercent:(float)percent {
4197 performSelectorOnMainThread:@selector(_setProgressPercent:)
4198 withObject:[NSNumber numberWithFloat:percent]
4203 - (void) startProgress {
4206 - (void) addProgressOutput:(NSString *)output {
4208 performSelectorOnMainThread:@selector(_addProgressOutput:)
4214 - (bool) isCancelling:(size_t)received {
4218 - (void) _setConfigurationData:(NSString *)data {
4219 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4221 _assert(conffile_r(data));
4223 NSString *ofile = conffile_r[1];
4224 //NSString *nfile = conffile_r[2];
4226 UIActionSheet *sheet = [[[UIActionSheet alloc]
4227 initWithTitle:CYLocalize("CONFIGURATION_UPGRADE")
4228 buttons:[NSArray arrayWithObjects:
4229 CYLocalize("KEEP_OLD_COPY"),
4230 CYLocalize("ACCEPT_NEW_COPY"),
4231 // XXX: CYLocalize("SEE_WHAT_CHANGED"),
4233 defaultButtonIndex:0
4238 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", CYLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4239 [sheet popupAlertAnimated:YES];
4242 - (void) _setProgressTitle:(NSString *)title {
4243 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4244 for (size_t i(0), e([words count]); i != e; ++i) {
4245 NSString *word([words objectAtIndex:i]);
4246 if (Package *package = [database_ packageWithName:word])
4247 [words replaceObjectAtIndex:i withObject:[package name]];
4250 [status_ setText:[words componentsJoinedByString:@" "]];
4253 - (void) _setProgressPercent:(NSNumber *)percent {
4254 [progress_ setProgress:[percent floatValue]];
4257 - (void) _addProgressOutput:(NSString *)output {
4258 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4259 CGSize size = [output_ contentSize];
4260 CGRect rect = {{0, size.height}, {size.width, 0}};
4261 [output_ scrollRectToVisible:rect animated:YES];
4264 - (BOOL) isRunning {
4271 /* Package Cell {{{ */
4272 @interface PackageCell : UITableCell {
4275 NSString *description_;
4282 UITextLabel *status_;
4286 - (PackageCell *) init;
4287 - (void) setPackage:(Package *)package;
4289 + (int) heightForPackage:(Package *)package;
4293 @implementation PackageCell
4295 - (void) clearPackage {
4306 if (description_ != nil) {
4307 [description_ release];
4311 if (source_ != nil) {
4316 if (badge_ != nil) {
4326 [self clearPackage];
4333 - (PackageCell *) init {
4334 if ((self = [super init]) != nil) {
4336 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4337 [status_ setBackgroundColor:[UIColor clearColor]];
4338 [status_ setFont:small];
4343 - (void) setPackage:(Package *)package {
4344 [self clearPackage];
4347 Source *source = [package source];
4349 icon_ = [[package icon] retain];
4350 name_ = [[package name] retain];
4351 description_ = [[package shortDescription] retain];
4352 commercial_ = [package isCommercial];
4354 package_ = [package retain];
4356 NSString *label = nil;
4357 bool trusted = false;
4359 if (source != nil) {
4360 label = [source label];
4361 trusted = [source trusted];
4362 } else if ([[package id] isEqualToString:@"firmware"])
4363 label = CYLocalize("APPLE");
4365 label = [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("UNKNOWN"), CYLocalize("LOCAL")];
4367 NSString *from(label);
4369 NSString *section = [package simpleSection];
4370 if (section != nil && ![section isEqualToString:label]) {
4371 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4372 from = [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), from, section];
4375 from = [NSString stringWithFormat:CYLocalize("FROM"), from];
4376 source_ = [from retain];
4378 if (NSString *purpose = [package primaryPurpose])
4379 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4380 badge_ = [badge_ retain];
4383 if (NSString *mode = [package mode]) {
4384 [badge_ setImage:[UIImage applicationImageNamed:
4385 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4388 [status_ setText:[NSString stringWithFormat:CYLocalize("QUEUED_FOR"), CYLocalize(mode)]];
4389 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4390 } else if ([package half]) {
4391 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4392 [status_ setText:CYLocalize("PACKAGE_DAMAGED")];
4393 [status_ setColor:[UIColor redColor]];
4395 [badge_ setImage:nil];
4396 [status_ setText:nil];
4403 - (void) drawRect:(CGRect)rect {
4407 if (NSString *mode = [package_ mode]) {
4408 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4409 color = remove ? RemovingColor_ : InstallingColor_;
4411 color = [UIColor whiteColor];
4413 [self setBackgroundColor:color];
4417 [super drawRect:rect];
4420 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4422 CGContextRef context(UIGraphicsGetCurrentContext());
4423 [[self backgroundColor] set];
4425 back.size.height -= 1;
4426 CGContextFillRect(context, back);
4429 [super drawBackgroundInRect:rect withFade:fade];
4432 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4435 rect.size = [icon_ size];
4437 rect.size.width /= 2;
4438 rect.size.height /= 2;
4440 rect.origin.x = 25 - rect.size.width / 2;
4441 rect.origin.y = 25 - rect.size.height / 2;
4443 [icon_ drawInRect:rect];
4446 if (badge_ != nil) {
4447 CGSize size = [badge_ size];
4449 [badge_ drawAtPoint:CGPointMake(
4450 36 - size.width / 2,
4451 36 - size.height / 2
4459 UISetColor(commercial_ ? Purple_ : Black_);
4460 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4461 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4464 UISetColor(commercial_ ? Purplish_ : Gray_);
4465 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4467 [super drawContentInRect:rect selected:selected];
4470 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4472 [super setSelected:selected withFade:fade];
4475 + (int) heightForPackage:(Package *)package {
4481 /* Section Cell {{{ */
4482 @interface SectionCell : UISimpleTableCell {
4487 _UISwitchSlider *switch_;
4492 - (void) setSection:(Section *)section editing:(BOOL)editing;
4496 @implementation SectionCell
4498 - (void) clearSection {
4499 if (section_ != nil) {
4509 if (count_ != nil) {
4516 [self clearSection];
4523 if ((self = [super init]) != nil) {
4524 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4526 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4527 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4531 - (void) onSwitch:(id)sender {
4532 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4533 if (metadata == nil) {
4534 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4535 [Sections_ setObject:metadata forKey:section_];
4539 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4542 - (void) setSection:(Section *)section editing:(BOOL)editing {
4543 if (editing != editing_) {
4545 [switch_ removeFromSuperview];
4547 [self addSubview:switch_];
4551 [self clearSection];
4553 if (section == nil) {
4554 name_ = [CYLocalize("ALL_PACKAGES") retain];
4557 section_ = [section localized];
4558 if (section_ != nil)
4559 section_ = [section_ retain];
4560 name_ = [(section_ == nil ? CYLocalize("NO_SECTION") : section_) retain];
4561 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4564 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4568 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4569 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4576 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4578 CGSize size = [count_ sizeWithFont:Font14_];
4582 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4584 [super drawContentInRect:rect selected:selected];
4590 /* File Table {{{ */
4591 @interface FileTable : RVPage {
4592 _transient Database *database_;
4595 NSMutableArray *files_;
4599 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4600 - (void) setPackage:(Package *)package;
4604 @implementation FileTable
4607 if (package_ != nil)
4616 - (int) numberOfRowsInTable:(UITable *)table {
4617 return files_ == nil ? 0 : [files_ count];
4620 - (float) table:(UITable *)table heightForRow:(int)row {
4624 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4625 if (reusing == nil) {
4626 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4627 UIFont *font = [UIFont systemFontOfSize:16];
4628 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4630 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4634 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4638 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4639 if ((self = [super initWithBook:book]) != nil) {
4640 database_ = database;
4642 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4644 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4645 [self addSubview:list_];
4647 UITableColumn *column = [[[UITableColumn alloc]
4648 initWithTitle:CYLocalize("NAME")
4650 width:[self frame].size.width
4653 [list_ setDataSource:self];
4654 [list_ setSeparatorStyle:1];
4655 [list_ addTableColumn:column];
4656 [list_ setDelegate:self];
4657 [list_ setReusesTableCells:YES];
4661 - (void) setPackage:(Package *)package {
4662 if (package_ != nil) {
4663 [package_ autorelease];
4672 [files_ removeAllObjects];
4674 if (package != nil) {
4675 package_ = [package retain];
4676 name_ = [[package id] retain];
4678 if (NSArray *files = [package files])
4679 [files_ addObjectsFromArray:files];
4681 if ([files_ count] != 0) {
4682 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4683 [files_ removeObjectAtIndex:0];
4684 [files_ sortUsingSelector:@selector(compareByPath:)];
4686 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4687 [stack addObject:@"/"];
4689 for (int i(0), e([files_ count]); i != e; ++i) {
4690 NSString *file = [files_ objectAtIndex:i];
4691 while (![file hasPrefix:[stack lastObject]])
4692 [stack removeLastObject];
4693 NSString *directory = [stack lastObject];
4694 [stack addObject:[file stringByAppendingString:@"/"]];
4695 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4696 ([stack count] - 2) * 3, "",
4697 [file substringFromIndex:[directory length]]
4706 - (void) resetViewAnimated:(BOOL)animated {
4707 [list_ resetViewAnimated:animated];
4710 - (void) reloadData {
4711 [self setPackage:[database_ packageWithName:name_]];
4712 [self reloadButtons];
4715 - (NSString *) title {
4716 return CYLocalize("INSTALLED_FILES");
4719 - (NSString *) backButtonTitle {
4720 return CYLocalize("FILES");
4725 /* Package View {{{ */
4726 @interface PackageView : BrowserView {
4727 _transient Database *database_;
4731 NSMutableArray *buttons_;
4734 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4735 - (void) setPackage:(Package *)package;
4739 @implementation PackageView
4742 if (package_ != nil)
4751 if ([self retainCount] == 1)
4752 [delegate_ setPackageView:self];
4756 /* XXX: this is not safe at all... localization of /fail/ */
4757 - (void) _clickButtonWithName:(NSString *)name {
4758 if ([name isEqualToString:CYLocalize("CLEAR")])
4759 [delegate_ clearPackage:package_];
4760 else if ([name isEqualToString:CYLocalize("INSTALL")])
4761 [delegate_ installPackage:package_];
4762 else if ([name isEqualToString:CYLocalize("REINSTALL")])
4763 [delegate_ installPackage:package_];
4764 else if ([name isEqualToString:CYLocalize("REMOVE")])
4765 [delegate_ removePackage:package_];
4766 else if ([name isEqualToString:CYLocalize("UPGRADE")])
4767 [delegate_ installPackage:package_];
4768 else _assert(false);
4771 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4772 NSString *context([sheet context]);
4774 if ([context isEqualToString:@"modify"]) {
4775 int count = [buttons_ count];
4776 _assert(count != 0);
4777 _assert(button <= count + 1);
4779 if (count != button - 1)
4780 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
4784 [super alertSheet:sheet buttonClicked:button];
4787 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
4788 return [super webView:sender didFinishLoadForFrame:frame];
4791 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4792 [super webView:sender didClearWindowObject:window forFrame:frame];
4793 [window setValue:package_ forKey:@"package"];
4796 - (bool) _allowJavaScriptPanel {
4801 - (void) __rightButtonClicked {
4802 int count = [buttons_ count];
4803 _assert(count != 0);
4806 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
4808 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
4809 [buttons addObjectsFromArray:buttons_];
4810 [buttons addObject:CYLocalize("CANCEL")];
4812 [delegate_ slideUp:[[[UIActionSheet alloc]
4815 defaultButtonIndex:([buttons count] - 1)
4822 - (void) _rightButtonClicked {
4824 [super _rightButtonClicked];
4826 [self __rightButtonClicked];
4830 - (id) _rightButtonTitle {
4831 int count = [buttons_ count];
4832 return count == 0 ? nil : count != 1 ? CYLocalize("MODIFY") : [buttons_ objectAtIndex:0];
4835 - (NSString *) backButtonTitle {
4839 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4840 if ((self = [super initWithBook:book]) != nil) {
4841 database_ = database;
4842 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
4843 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
4847 - (void) setPackage:(Package *)package {
4848 if (package_ != nil) {
4849 [package_ autorelease];
4858 [buttons_ removeAllObjects];
4860 if (package != nil) {
4863 package_ = [package retain];
4864 name_ = [[package id] retain];
4865 commercial_ = [package isCommercial];
4867 if ([package_ mode] != nil)
4868 [buttons_ addObject:CYLocalize("CLEAR")];
4869 if ([package_ source] == nil);
4870 else if ([package_ upgradableAndEssential:NO])
4871 [buttons_ addObject:CYLocalize("UPGRADE")];
4872 else if ([package_ installed] == nil)
4873 [buttons_ addObject:CYLocalize("INSTALL")];
4875 [buttons_ addObject:CYLocalize("REINSTALL")];
4876 if ([package_ installed] != nil)
4877 [buttons_ addObject:CYLocalize("REMOVE")];
4879 if (special_ != NULL) {
4880 CGRect frame([webview_ frame]);
4881 frame.size.width = 320;
4882 frame.size.height = 0;
4883 [webview_ setFrame:frame];
4885 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
4888 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
4890 [self setButtonTitle:nil withStyle:nil toFunction:nil];
4892 [self setFinishHook:nil];
4893 [self setPopupHook:nil];
4896 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
4897 [super callFunction:special_];
4901 [self reloadButtons];
4904 - (bool) isLoading {
4905 return commercial_ ? [super isLoading] : false;
4908 - (void) reloadData {
4909 [self setPackage:[database_ packageWithName:name_]];
4914 /* Package Table {{{ */
4915 @interface PackageTable : RVPage {
4916 _transient Database *database_;
4918 NSMutableArray *packages_;
4919 NSMutableArray *sections_;
4920 UISectionList *list_;
4923 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
4925 - (void) setDelegate:(id)delegate;
4927 - (void) reloadData;
4928 - (void) resetCursor;
4930 - (UISectionList *) list;
4932 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
4936 @implementation PackageTable
4939 [list_ setDataSource:nil];
4942 [packages_ release];
4943 [sections_ release];
4948 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
4949 return [sections_ count];
4952 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
4953 return [[sections_ objectAtIndex:section] name];
4956 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
4957 return [[sections_ objectAtIndex:section] row];
4960 - (int) numberOfRowsInTable:(UITable *)table {
4961 return [packages_ count];
4964 - (float) table:(UITable *)table heightForRow:(int)row {
4965 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
4968 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4970 reusing = [[[PackageCell alloc] init] autorelease];
4971 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
4975 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
4979 - (void) tableRowSelected:(NSNotification *)notification {
4980 int row = [[notification object] selectedRow];
4984 Package *package = [packages_ objectAtIndex:row];
4985 package = [database_ packageWithName:[package id]];
4986 PackageView *view([delegate_ packageView]);
4987 [view setPackage:package];
4988 [view setDelegate:delegate_];
4989 [book_ pushPage:view];
4992 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
4993 if ((self = [super initWithBook:book]) != nil) {
4994 database_ = database;
4995 title_ = [title retain];
4997 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
4998 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5000 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
5001 [list_ setDataSource:self];
5003 UITableColumn *column = [[[UITableColumn alloc]
5004 initWithTitle:CYLocalize("NAME")
5006 width:[self frame].size.width
5009 UITable *table = [list_ table];
5010 [table setSeparatorStyle:1];
5011 [table addTableColumn:column];
5012 [table setDelegate:self];
5013 [table setReusesTableCells:YES];
5015 [self addSubview:list_];
5017 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5018 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5022 - (void) setDelegate:(id)delegate {
5023 delegate_ = delegate;
5026 - (bool) hasPackage:(Package *)package {
5030 - (void) reloadData {
5031 NSArray *packages = [database_ packages];
5033 [packages_ removeAllObjects];
5034 [sections_ removeAllObjects];
5036 _profile(PackageTable$reloadData$Filter)
5037 for (Package *package in packages)
5038 if ([self hasPackage:package])
5039 [packages_ addObject:package];
5042 Section *section = nil;
5044 _profile(PackageTable$reloadData$Section)
5045 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5049 _profile(PackageTable$reloadData$Section$Package)
5050 package = [packages_ objectAtIndex:offset];
5051 index = [package index];
5054 if (section == nil || [section index] != index) {
5055 _profile(PackageTable$reloadData$Section$Allocate)
5056 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5059 _profile(PackageTable$reloadData$Section$Add)
5060 [sections_ addObject:section];
5064 [section addToCount];
5068 _profile(PackageTable$reloadData$List)
5073 - (NSString *) title {
5077 - (void) resetViewAnimated:(BOOL)animated {
5078 [list_ resetViewAnimated:animated];
5081 - (void) resetCursor {
5082 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
5085 - (UISectionList *) list {
5089 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5090 [list_ setShouldHideHeaderInShortLists:hide];
5095 /* Filtered Package Table {{{ */
5096 @interface FilteredPackageTable : PackageTable {
5102 - (void) setObject:(id)object;
5104 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5108 @implementation FilteredPackageTable
5116 - (void) setObject:(id)object {
5122 object_ = [object retain];
5125 - (bool) hasPackage:(Package *)package {
5126 _profile(FilteredPackageTable$hasPackage)
5127 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5131 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5132 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5134 object_ = object == nil ? nil : [object retain];
5136 /* XXX: this is an unsafe optimization of doomy hell */
5137 Method method = class_getInstanceMethod([Package class], filter);
5138 _assert(method != NULL);
5139 imp_ = method_getImplementation(method);
5140 _assert(imp_ != NULL);
5149 /* Add Source View {{{ */
5150 @interface AddSourceView : RVPage {
5151 _transient Database *database_;
5154 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5158 @implementation AddSourceView
5160 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5161 if ((self = [super initWithBook:book]) != nil) {
5162 database_ = database;
5168 /* Source Cell {{{ */
5169 @interface SourceCell : UITableCell {
5172 NSString *description_;
5178 - (SourceCell *) initWithSource:(Source *)source;
5182 @implementation SourceCell
5187 [description_ release];
5192 - (SourceCell *) initWithSource:(Source *)source {
5193 if ((self = [super init]) != nil) {
5195 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5197 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5198 icon_ = [icon_ retain];
5200 origin_ = [[source name] retain];
5201 label_ = [[source uri] retain];
5202 description_ = [[source description] retain];
5206 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5208 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5215 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5219 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5223 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5225 [super drawContentInRect:rect selected:selected];
5230 /* Source Table {{{ */
5231 @interface SourceTable : RVPage {
5232 _transient Database *database_;
5233 UISectionList *list_;
5234 NSMutableArray *sources_;
5235 UIActionSheet *alert_;
5239 UIProgressHUD *hud_;
5242 //NSURLConnection *installer_;
5243 NSURLConnection *trivial_bz2_;
5244 NSURLConnection *trivial_gz_;
5245 //NSURLConnection *automatic_;
5250 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5254 @implementation SourceTable
5256 - (void) _deallocConnection:(NSURLConnection *)connection {
5257 if (connection != nil) {
5258 [connection cancel];
5259 //[connection setDelegate:nil];
5260 [connection release];
5265 [[list_ table] setDelegate:nil];
5266 [list_ setDataSource:nil];
5275 //[self _deallocConnection:installer_];
5276 [self _deallocConnection:trivial_gz_];
5277 [self _deallocConnection:trivial_bz2_];
5278 //[self _deallocConnection:automatic_];
5285 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5286 return offset_ == 0 ? 1 : 2;
5289 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5290 switch (section + (offset_ == 0 ? 1 : 0)) {
5291 case 0: return CYLocalize("ENTERED_BY_USER");
5292 case 1: return CYLocalize("INSTALLED_BY_PACKAGE");
5300 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5301 switch (section + (offset_ == 0 ? 1 : 0)) {
5303 case 1: return offset_;
5311 - (int) numberOfRowsInTable:(UITable *)table {
5312 return [sources_ count];
5315 - (float) table:(UITable *)table heightForRow:(int)row {
5316 Source *source = [sources_ objectAtIndex:row];
5317 return [source description] == nil ? 56 : 73;
5320 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5321 Source *source = [sources_ objectAtIndex:row];
5322 // XXX: weird warning, stupid selectors ;P
5323 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5326 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5330 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5334 - (void) tableRowSelected:(NSNotification*)notification {
5335 UITable *table([list_ table]);
5336 int row([table selectedRow]);
5340 Source *source = [sources_ objectAtIndex:row];
5342 PackageTable *packages = [[[FilteredPackageTable alloc]
5345 title:[source label]
5346 filter:@selector(isVisibleInSource:)
5350 [packages setDelegate:delegate_];
5352 [book_ pushPage:packages];
5355 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5356 Source *source = [sources_ objectAtIndex:row];
5357 return [source record] != nil;
5360 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5361 [[list_ table] setDeleteConfirmationRow:row];
5364 - (void) table:(UITable *)table deleteRow:(int)row {
5365 Source *source = [sources_ objectAtIndex:row];
5366 [Sources_ removeObjectForKey:[source key]];
5367 [delegate_ syncData];
5371 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5374 @"./", @"Distribution",
5375 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5377 [delegate_ syncData];
5380 - (NSString *) getWarning {
5381 NSString *href(href_);
5382 NSRange colon([href rangeOfString:@"://"]);
5383 if (colon.location != NSNotFound)
5384 href = [href substringFromIndex:(colon.location + 3)];
5385 href = [href stringByAddingPercentEscapes];
5386 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5387 href = [href stringByCachingURLWithCurrentCDN];
5389 NSURL *url([NSURL URLWithString:href]);
5391 NSStringEncoding encoding;
5392 NSError *error(nil);
5394 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5395 return [warning length] == 0 ? nil : warning;
5399 - (void) _endConnection:(NSURLConnection *)connection {
5400 NSURLConnection **field = NULL;
5401 if (connection == trivial_bz2_)
5402 field = &trivial_bz2_;
5403 else if (connection == trivial_gz_)
5404 field = &trivial_gz_;
5405 _assert(field != NULL);
5406 [connection release];
5410 trivial_bz2_ == nil &&
5416 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5419 UIActionSheet *sheet = [[[UIActionSheet alloc]
5420 initWithTitle:CYLocalize("SOURCE_WARNING")
5421 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_ANYWAY"), CYLocalize("CANCEL"), nil]
5422 defaultButtonIndex:0
5427 [sheet setNumberOfRows:1];
5429 [sheet setBodyText:warning];
5430 [sheet popupAlertAnimated:YES];
5433 } else if (error_ != nil) {
5434 UIActionSheet *sheet = [[[UIActionSheet alloc]
5435 initWithTitle:CYLocalize("VERIFICATION_ERROR")
5436 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5437 defaultButtonIndex:0
5442 [sheet setBodyText:[error_ localizedDescription]];
5443 [sheet popupAlertAnimated:YES];
5445 UIActionSheet *sheet = [[[UIActionSheet alloc]
5446 initWithTitle:CYLocalize("NOT_REPOSITORY")
5447 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5448 defaultButtonIndex:0
5453 [sheet setBodyText:CYLocalize("NOT_REPOSITORY_EX")];
5454 [sheet popupAlertAnimated:YES];
5457 [delegate_ setStatusBarShowsProgress:NO];
5458 [delegate_ removeProgressHUD:hud_];
5468 if (error_ != nil) {
5475 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5476 switch ([response statusCode]) {
5482 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5483 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5485 error_ = [error retain];
5486 [self _endConnection:connection];
5489 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5490 [self _endConnection:connection];
5493 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5494 NSMutableURLRequest *request = [NSMutableURLRequest
5495 requestWithURL:[NSURL URLWithString:href]
5496 cachePolicy:NSURLRequestUseProtocolCachePolicy
5497 timeoutInterval:20.0
5500 [request setHTTPMethod:method];
5502 if (Machine_ != NULL)
5503 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5504 if (UniqueID_ != nil)
5505 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5508 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5510 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5513 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5514 NSString *context([sheet context]);
5516 if ([context isEqualToString:@"source"]) {
5519 NSString *href = [[sheet textField] text];
5521 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5523 if (![href hasSuffix:@"/"])
5524 href_ = [href stringByAppendingString:@"/"];
5527 href_ = [href_ retain];
5529 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5530 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5531 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5535 hud_ = [[delegate_ addProgressHUD] retain];
5536 [hud_ setText:CYLocalize("VERIFYING_URL")];
5547 } else if ([context isEqualToString:@"trivial"])
5549 else if ([context isEqualToString:@"urlerror"])
5551 else if ([context isEqualToString:@"warning"]) {
5571 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5572 if ((self = [super initWithBook:book]) != nil) {
5573 database_ = database;
5574 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5576 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5577 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5578 [list_ setShouldHideHeaderInShortLists:NO];
5580 [self addSubview:list_];
5581 [list_ setDataSource:self];
5583 UITableColumn *column = [[UITableColumn alloc]
5584 initWithTitle:CYLocalize("NAME")
5586 width:[self frame].size.width
5589 UITable *table = [list_ table];
5590 [table setSeparatorStyle:1];
5591 [table addTableColumn:column];
5592 [table setDelegate:self];
5596 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5597 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5601 - (void) reloadData {
5603 _assert(list.ReadMainList());
5605 [sources_ removeAllObjects];
5606 [sources_ addObjectsFromArray:[database_ sources]];
5608 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5611 int count = [sources_ count];
5612 for (offset_ = 0; offset_ != count; ++offset_) {
5613 Source *source = [sources_ objectAtIndex:offset_];
5614 if ([source record] == nil)
5621 - (void) resetViewAnimated:(BOOL)animated {
5622 [list_ resetViewAnimated:animated];
5625 - (void) _leftButtonClicked {
5626 /*[book_ pushPage:[[[AddSourceView alloc]
5631 UIActionSheet *sheet = [[[UIActionSheet alloc]
5632 initWithTitle:CYLocalize("ENTER_APT_URL")
5633 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_SOURCE"), CYLocalize("CANCEL"), nil]
5634 defaultButtonIndex:0
5639 [sheet setNumberOfRows:1];
5641 [sheet addTextFieldWithValue:@"http://" label:@""];
5643 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5644 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5645 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5646 [traits setKeyboardType:UIKeyboardTypeURL];
5647 // XXX: UIReturnKeyDone
5648 [traits setReturnKeyType:UIReturnKeyNext];
5650 [sheet popupAlertAnimated:YES];
5653 - (void) _rightButtonClicked {
5654 UITable *table = [list_ table];
5655 BOOL editing = [table isRowDeletionEnabled];
5656 [table enableRowDeletion:!editing animated:YES];
5657 [book_ reloadButtonsForPage:self];
5660 - (NSString *) title {
5661 return CYLocalize("SOURCES");
5664 - (NSString *) leftButtonTitle {
5665 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("ADD") : nil;
5668 - (id) rightButtonTitle {
5669 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("DONE") : CYLocalize("EDIT");
5672 - (UINavigationButtonStyle) rightButtonStyle {
5673 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5679 /* Installed View {{{ */
5680 @interface InstalledView : RVPage {
5681 _transient Database *database_;
5682 FilteredPackageTable *packages_;
5686 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5690 @implementation InstalledView
5693 [packages_ release];
5697 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5698 if ((self = [super initWithBook:book]) != nil) {
5699 database_ = database;
5701 packages_ = [[FilteredPackageTable alloc]
5705 filter:@selector(isInstalledAndVisible:)
5706 with:[NSNumber numberWithBool:YES]
5709 [self addSubview:packages_];
5711 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5712 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5716 - (void) resetViewAnimated:(BOOL)animated {
5717 [packages_ resetViewAnimated:animated];
5720 - (void) reloadData {
5721 [packages_ reloadData];
5724 - (void) _rightButtonClicked {
5725 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5726 [packages_ reloadData];
5728 [book_ reloadButtonsForPage:self];
5731 - (NSString *) title {
5732 return CYLocalize("INSTALLED");
5735 - (NSString *) backButtonTitle {
5736 return CYLocalize("PACKAGES");
5739 - (id) rightButtonTitle {
5740 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? CYLocalize("EXPERT") : CYLocalize("SIMPLE");
5743 - (UINavigationButtonStyle) rightButtonStyle {
5744 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5747 - (void) setDelegate:(id)delegate {
5748 [super setDelegate:delegate];
5749 [packages_ setDelegate:delegate];
5756 @interface HomeView : BrowserView {
5761 @implementation HomeView
5763 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5764 NSString *context([sheet context]);
5766 if ([context isEqualToString:@"about"])
5769 [super alertSheet:sheet buttonClicked:button];
5772 - (void) _leftButtonClicked {
5773 UIActionSheet *sheet = [[[UIActionSheet alloc]
5774 initWithTitle:CYLocalize("ABOUT_CYDIA")
5775 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
5776 defaultButtonIndex:0
5782 @"Copyright (C) 2008-2009\n"
5783 "Jay Freeman (saurik)\n"
5784 "saurik@saurik.com\n"
5785 "http://www.saurik.com/\n"
5788 "http://www.theokorigroup.com/\n"
5790 "College of Creative Studies,\n"
5791 "University of California,\n"
5793 "http://www.ccs.ucsb.edu/"
5796 [sheet popupAlertAnimated:YES];
5799 - (NSString *) leftButtonTitle {
5800 return CYLocalize("ABOUT");
5805 /* Manage View {{{ */
5806 @interface ManageView : BrowserView {
5811 @implementation ManageView
5813 - (NSString *) title {
5814 return CYLocalize("MANAGE");
5817 - (void) _leftButtonClicked {
5818 [delegate_ askForSettings];
5821 - (NSString *) leftButtonTitle {
5822 return CYLocalize("SETTINGS");
5826 - (id) _rightButtonTitle {
5827 return Queuing_ ? CYLocalize("QUEUE") : nil;
5830 - (UINavigationButtonStyle) rightButtonStyle {
5831 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5834 - (void) _rightButtonClicked {
5839 - (bool) isLoading {
5846 #include <BrowserView.m>
5848 /* Cydia Book {{{ */
5849 @interface CYBook : RVBook <
5852 _transient Database *database_;
5853 UINavigationBar *overlay_;
5854 UINavigationBar *underlay_;
5855 UIProgressIndicator *indicator_;
5856 UITextLabel *prompt_;
5857 UIProgressBar *progress_;
5858 UINavigationButton *cancel_;
5862 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
5868 @implementation CYBook
5872 [indicator_ release];
5874 [progress_ release];
5879 - (NSString *) getTitleForPage:(RVPage *)page {
5880 return [super getTitleForPage:page];
5888 [UIView beginAnimations:nil context:NULL];
5890 CGRect ovrframe = [overlay_ frame];
5891 ovrframe.origin.y = 0;
5892 [overlay_ setFrame:ovrframe];
5894 CGRect barframe = [navbar_ frame];
5895 barframe.origin.y += ovrframe.size.height;
5896 [navbar_ setFrame:barframe];
5898 CGRect trnframe = [transition_ frame];
5899 trnframe.origin.y += ovrframe.size.height;
5900 trnframe.size.height -= ovrframe.size.height;
5901 [transition_ setFrame:trnframe];
5903 [UIView endAnimations];
5905 [indicator_ startAnimation];
5906 [prompt_ setText:CYLocalize("UPDATING_DATABASE")];
5907 [progress_ setProgress:0];
5910 [overlay_ addSubview:cancel_];
5913 detachNewThreadSelector:@selector(_update)
5922 [indicator_ stopAnimation];
5924 [UIView beginAnimations:nil context:NULL];
5926 CGRect ovrframe = [overlay_ frame];
5927 ovrframe.origin.y = -ovrframe.size.height;
5928 [overlay_ setFrame:ovrframe];
5930 CGRect barframe = [navbar_ frame];
5931 barframe.origin.y -= ovrframe.size.height;
5932 [navbar_ setFrame:barframe];
5934 CGRect trnframe = [transition_ frame];
5935 trnframe.origin.y -= ovrframe.size.height;
5936 trnframe.size.height += ovrframe.size.height;
5937 [transition_ setFrame:trnframe];
5939 [UIView commitAnimations];
5941 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
5944 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
5945 if ((self = [super initWithFrame:frame]) != nil) {
5946 database_ = database;
5948 CGRect ovrrect = [navbar_ bounds];
5949 ovrrect.size.height = [UINavigationBar defaultSize].height;
5950 ovrrect.origin.y = -ovrrect.size.height;
5952 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5953 [self addSubview:overlay_];
5955 ovrrect.origin.y = frame.size.height;
5956 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5957 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
5958 [self addSubview:underlay_];
5960 [overlay_ setBarStyle:1];
5961 [underlay_ setBarStyle:1];
5963 int barstyle = [overlay_ _barStyle:NO];
5964 bool ugly = barstyle == 0;
5966 UIProgressIndicatorStyle style = ugly ?
5967 UIProgressIndicatorStyleMediumBrown :
5968 UIProgressIndicatorStyleMediumWhite;
5970 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
5971 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
5972 CGRect indrect = {{indoffset, indoffset}, indsize};
5974 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
5975 [indicator_ setStyle:style];
5976 [overlay_ addSubview:indicator_];
5978 CGSize prmsize = {215, indsize.height + 4};
5981 indoffset * 2 + indsize.width,
5985 unsigned(ovrrect.size.height - prmsize.height) / 2
5988 UIFont *font = [UIFont systemFontOfSize:15];
5990 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
5992 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
5993 [prompt_ setBackgroundColor:[UIColor clearColor]];
5994 [prompt_ setFont:font];
5996 [overlay_ addSubview:prompt_];
5998 CGSize prgsize = {75, 100};
6001 ovrrect.size.width - prgsize.width - 10,
6002 (ovrrect.size.height - prgsize.height) / 2
6005 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6006 [progress_ setStyle:0];
6007 [overlay_ addSubview:progress_];
6009 cancel_ = [[UINavigationButton alloc] initWithTitle:CYLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6010 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6012 CGRect frame = [cancel_ frame];
6013 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6014 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6015 [cancel_ setFrame:frame];
6017 [cancel_ setBarStyle:barstyle];
6021 - (void) _onCancel {
6023 [cancel_ removeFromSuperview];
6026 - (void) _update { _pooled
6028 status.setDelegate(self);
6030 [database_ updateWithStatus:status];
6033 performSelectorOnMainThread:@selector(_update_)
6039 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
6040 [prompt_ setText:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), error]];
6043 - (void) setProgressTitle:(NSString *)title {
6045 performSelectorOnMainThread:@selector(_setProgressTitle:)
6051 - (void) setProgressPercent:(float)percent {
6053 performSelectorOnMainThread:@selector(_setProgressPercent:)
6054 withObject:[NSNumber numberWithFloat:percent]
6059 - (void) startProgress {
6062 - (void) addProgressOutput:(NSString *)output {
6064 performSelectorOnMainThread:@selector(_addProgressOutput:)
6070 - (bool) isCancelling:(size_t)received {
6074 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6078 - (void) _setProgressTitle:(NSString *)title {
6079 [prompt_ setText:title];
6082 - (void) _setProgressPercent:(NSNumber *)percent {
6083 [progress_ setProgress:[percent floatValue]];
6086 - (void) _addProgressOutput:(NSString *)output {
6091 /* Cydia:// Protocol {{{ */
6092 @interface CydiaURLProtocol : NSURLProtocol {
6097 @implementation CydiaURLProtocol
6099 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6100 NSURL *url([request URL]);
6103 NSString *scheme([[url scheme] lowercaseString]);
6104 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6109 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6113 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6114 id<NSURLProtocolClient> client([self client]);
6116 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6118 NSData *data(UIImagePNGRepresentation(icon));
6120 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6121 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6122 [client URLProtocol:self didLoadData:data];
6123 [client URLProtocolDidFinishLoading:self];
6127 - (void) startLoading {
6128 id<NSURLProtocolClient> client([self client]);
6129 NSURLRequest *request([self request]);
6131 NSURL *url([request URL]);
6132 NSString *href([url absoluteString]);
6134 NSString *path([href substringFromIndex:8]);
6135 NSRange slash([path rangeOfString:@"/"]);
6138 if (slash.location == NSNotFound) {
6142 command = [path substringToIndex:slash.location];
6143 path = [path substringFromIndex:(slash.location + 1)];
6146 Database *database([Database sharedInstance]);
6148 if ([command isEqualToString:@"package-icon"]) {
6151 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6152 Package *package([database packageWithName:path]);
6155 UIImage *icon([package icon]);
6156 [self _returnPNGWithImage:icon forRequest:request];
6157 } else if ([command isEqualToString:@"source-icon"]) {
6160 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6161 NSString *source(Simplify(path));
6162 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6164 icon = [UIImage applicationImageNamed:@"unknown.png"];
6165 [self _returnPNGWithImage:icon forRequest:request];
6166 } else if ([command isEqualToString:@"uikit-image"]) {
6169 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6170 UIImage *icon(_UIImageWithName(path));
6171 [self _returnPNGWithImage:icon forRequest:request];
6172 } else if ([command isEqualToString:@"section-icon"]) {
6175 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6176 NSString *section(Simplify(path));
6177 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6179 icon = [UIImage applicationImageNamed:@"unknown.png"];
6180 [self _returnPNGWithImage:icon forRequest:request];
6182 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6186 - (void) stopLoading {
6192 /* Sections View {{{ */
6193 @interface SectionsView : RVPage {
6194 _transient Database *database_;
6195 NSMutableArray *sections_;
6196 NSMutableArray *filtered_;
6197 UITransitionView *transition_;
6203 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6204 - (void) reloadData;
6209 @implementation SectionsView
6212 [list_ setDataSource:nil];
6213 [list_ setDelegate:nil];
6215 [sections_ release];
6216 [filtered_ release];
6217 [transition_ release];
6219 [accessory_ release];
6223 - (int) numberOfRowsInTable:(UITable *)table {
6224 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6227 - (float) table:(UITable *)table heightForRow:(int)row {
6231 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6233 reusing = [[[SectionCell alloc] init] autorelease];
6234 [(SectionCell *)reusing setSection:(editing_ ?
6235 [sections_ objectAtIndex:row] :
6236 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6237 ) editing:editing_];
6241 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6245 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6249 - (void) tableRowSelected:(NSNotification *)notification {
6250 int row = [[notification object] selectedRow];
6261 title = CYLocalize("ALL_PACKAGES");
6263 section = [filtered_ objectAtIndex:(row - 1)];
6264 name = [section name];
6267 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6270 title = CYLocalize("NO_SECTION");
6274 PackageTable *table = [[[FilteredPackageTable alloc]
6278 filter:@selector(isVisiblyUninstalledInSection:)
6282 [table setDelegate:delegate_];
6284 [book_ pushPage:table];
6287 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6288 if ((self = [super initWithBook:book]) != nil) {
6289 database_ = database;
6291 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6292 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6294 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6295 [self addSubview:transition_];
6297 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6298 [transition_ transition:0 toView:list_];
6300 UITableColumn *column = [[[UITableColumn alloc]
6301 initWithTitle:CYLocalize("NAME")
6303 width:[self frame].size.width
6306 [list_ setDataSource:self];
6307 [list_ setSeparatorStyle:1];
6308 [list_ addTableColumn:column];
6309 [list_ setDelegate:self];
6310 [list_ setReusesTableCells:YES];
6314 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6315 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6319 - (void) reloadData {
6320 NSArray *packages = [database_ packages];
6322 [sections_ removeAllObjects];
6323 [filtered_ removeAllObjects];
6326 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6327 SectionMap sections;
6328 sections.resize(64);
6330 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6334 for (Package *package in packages) {
6335 NSString *name([package section]);
6336 NSString *key(name == nil ? @"" : name);
6341 _profile(SectionsView$reloadData$Section)
6342 section = §ions[key];
6343 if (*section == nil) {
6344 _profile(SectionsView$reloadData$Section$Allocate)
6345 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6350 [*section addToCount];
6352 _profile(SectionsView$reloadData$Filter)
6353 if (![package valid] || [package installed] != nil || ![package visible])
6357 [*section addToRow];
6361 _profile(SectionsView$reloadData$Section)
6362 section = [sections objectForKey:key];
6363 if (section == nil) {
6364 _profile(SectionsView$reloadData$Section$Allocate)
6365 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6366 [sections setObject:section forKey:key];
6371 [section addToCount];
6373 _profile(SectionsView$reloadData$Filter)
6374 if (![package valid] || [package installed] != nil || ![package visible])
6384 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6385 [sections_ addObject:i->second];
6387 [sections_ addObjectsFromArray:[sections allValues]];
6390 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6392 for (Section *section in sections_) {
6393 size_t count([section row]);
6397 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6398 [section setCount:count];
6399 [filtered_ addObject:section];
6406 - (void) resetView {
6408 [self _rightButtonClicked];
6411 - (void) resetViewAnimated:(BOOL)animated {
6412 [list_ resetViewAnimated:animated];
6415 - (void) _rightButtonClicked {
6416 if ((editing_ = !editing_))
6419 [delegate_ updateData];
6420 [book_ reloadTitleForPage:self];
6421 [book_ reloadButtonsForPage:self];
6424 - (NSString *) title {
6425 return editing_ ? CYLocalize("SECTION_VISIBILITY") : CYLocalize("INSTALL_BY_SECTION");
6428 - (NSString *) backButtonTitle {
6429 return CYLocalize("SECTIONS");
6432 - (id) rightButtonTitle {
6433 return [sections_ count] == 0 ? nil : editing_ ? CYLocalize("DONE") : CYLocalize("EDIT");
6436 - (UINavigationButtonStyle) rightButtonStyle {
6437 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6440 - (UIView *) accessoryView {
6446 /* Changes View {{{ */
6447 @interface ChangesView : RVPage {
6448 _transient Database *database_;
6449 NSMutableArray *packages_;
6450 NSMutableArray *sections_;
6451 UISectionList *list_;
6455 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6456 - (void) reloadData;
6460 @implementation ChangesView
6463 [[list_ table] setDelegate:nil];
6464 [list_ setDataSource:nil];
6466 [packages_ release];
6467 [sections_ release];
6472 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6473 return [sections_ count];
6476 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6477 return [[sections_ objectAtIndex:section] name];
6480 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6481 return [[sections_ objectAtIndex:section] row];
6484 - (int) numberOfRowsInTable:(UITable *)table {
6485 return [packages_ count];
6488 - (float) table:(UITable *)table heightForRow:(int)row {
6489 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6492 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6494 reusing = [[[PackageCell alloc] init] autorelease];
6495 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6499 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6503 - (void) tableRowSelected:(NSNotification *)notification {
6504 int row = [[notification object] selectedRow];
6507 Package *package = [packages_ objectAtIndex:row];
6508 PackageView *view([delegate_ packageView]);
6509 [view setDelegate:delegate_];
6510 [view setPackage:package];
6511 [book_ pushPage:view];
6514 - (void) _leftButtonClicked {
6515 [(CYBook *)book_ update];
6516 [self reloadButtons];
6519 - (void) _rightButtonClicked {
6520 [delegate_ distUpgrade];
6523 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6524 if ((self = [super initWithBook:book]) != nil) {
6525 database_ = database;
6527 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6528 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6530 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6531 [self addSubview:list_];
6533 [list_ setShouldHideHeaderInShortLists:NO];
6534 [list_ setDataSource:self];
6535 //[list_ setSectionListStyle:1];
6537 UITableColumn *column = [[[UITableColumn alloc]
6538 initWithTitle:CYLocalize("NAME")
6540 width:[self frame].size.width
6543 UITable *table = [list_ table];
6544 [table setSeparatorStyle:1];
6545 [table addTableColumn:column];
6546 [table setDelegate:self];
6547 [table setReusesTableCells:YES];
6551 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6552 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6556 - (void) reloadData {
6557 NSArray *packages = [database_ packages];
6559 [packages_ removeAllObjects];
6560 [sections_ removeAllObjects];
6563 for (Package *package in packages)
6565 [package installed] == nil && [package valid] && [package visible] ||
6566 [package upgradableAndEssential:YES]
6568 [packages_ addObject:package];
6571 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6574 Section *upgradable = [[[Section alloc] initWithName:CYLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6575 Section *ignored = [[[Section alloc] initWithName:CYLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6576 Section *section = nil;
6580 bool unseens = false;
6582 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6584 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6585 Package *package = [packages_ objectAtIndex:offset];
6587 BOOL uae = [package upgradableAndEssential:YES];
6593 _profile(ChangesView$reloadData$Remember)
6594 seen = [package seen];
6597 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6602 name = CYLocalize("UNKNOWN");
6604 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6608 _profile(ChangesView$reloadData$Allocate)
6609 name = [NSString stringWithFormat:CYLocalize("NEW_AT"), name];
6610 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6611 [sections_ addObject:section];
6615 [section addToCount];
6616 } else if ([package ignored])
6617 [ignored addToCount];
6620 [upgradable addToCount];
6625 CFRelease(formatter);
6628 Section *last = [sections_ lastObject];
6629 size_t count = [last count];
6630 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6631 [sections_ removeLastObject];
6634 if ([ignored count] != 0)
6635 [sections_ insertObject:ignored atIndex:0];
6637 [sections_ insertObject:upgradable atIndex:0];
6640 [self reloadButtons];
6643 - (void) resetViewAnimated:(BOOL)animated {
6644 [list_ resetViewAnimated:animated];
6647 - (NSString *) leftButtonTitle {
6648 return [(CYBook *)book_ updating] ? nil : CYLocalize("REFRESH");
6651 - (id) rightButtonTitle {
6652 return upgrades_ == 0 ? nil : [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6655 - (NSString *) title {
6656 return CYLocalize("CHANGES");
6661 /* Search View {{{ */
6662 @protocol SearchViewDelegate
6663 - (void) showKeyboard:(BOOL)show;
6666 @interface SearchView : RVPage {
6668 UISearchField *field_;
6669 UITransitionView *transition_;
6670 FilteredPackageTable *table_;
6671 UIPreferencesTable *advanced_;
6677 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6678 - (void) reloadData;
6682 @implementation SearchView
6685 [field_ setDelegate:nil];
6687 [accessory_ release];
6689 [transition_ release];
6691 [advanced_ release];
6696 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6700 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6702 case 0: return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("ADVANCED_SEARCH"), CYLocalize("COMING_SOON")];
6704 default: _assert(false);
6708 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6712 default: _assert(false);
6716 - (void) _showKeyboard:(BOOL)show {
6717 CGSize keysize = [UIKeyboard defaultSize];
6718 CGRect keydown = [book_ pageBounds];
6719 CGRect keyup = keydown;
6720 keyup.size.height -= keysize.height - ButtonBarHeight_;
6722 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6724 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6725 [animation setSignificantRectFields:8];
6728 [animation setStartFrame:keydown];
6729 [animation setEndFrame:keyup];
6731 [animation setStartFrame:keyup];
6732 [animation setEndFrame:keydown];
6735 UIAnimator *animator = [UIAnimator sharedAnimator];
6738 addAnimations:[NSArray arrayWithObjects:animation, nil]
6739 withDuration:(KeyboardTime_ - delay)
6744 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6746 [delegate_ showKeyboard:show];
6749 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6750 [self _showKeyboard:YES];
6753 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
6754 [self _showKeyboard:NO];
6757 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
6759 NSString *text([field_ text]);
6760 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6766 - (void) textFieldClearButtonPressed:(UITextField *)field {
6770 - (void) keyboardInputShouldDelete:(id)input {
6774 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
6775 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6779 [field_ resignFirstResponder];
6784 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6785 if ((self = [super initWithBook:book]) != nil) {
6786 CGRect pageBounds = [book_ pageBounds];
6788 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6789 [self addSubview:transition_];
6791 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6793 [advanced_ setReusesTableCells:YES];
6794 [advanced_ setDataSource:self];
6795 [advanced_ reloadData];
6797 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6798 CGColor dimmed(space_, 0, 0, 0, 0.5);
6799 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
6801 table_ = [[FilteredPackageTable alloc]
6805 filter:@selector(isUnfilteredAndSearchedForBy:)
6809 [table_ setShouldHideHeaderInShortLists:NO];
6810 [transition_ transition:0 toView:table_];
6819 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
6826 [self bounds].size.width - area.origin.x - 18;
6828 area.size.height = [UISearchField defaultHeight];
6830 field_ = [[UISearchField alloc] initWithFrame:area];
6832 UIFont *font = [UIFont systemFontOfSize:16];
6833 [field_ setFont:font];
6835 [field_ setPlaceholder:CYLocalize("SEARCH_EX")];
6836 [field_ setDelegate:self];
6838 [field_ setPaddingTop:5];
6840 UITextInputTraits *traits([field_ textInputTraits]);
6841 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6842 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6843 [traits setReturnKeyType:UIReturnKeySearch];
6845 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
6847 accessory_ = [[UIView alloc] initWithFrame:accrect];
6848 [accessory_ addSubview:field_];
6850 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
6851 [configure setShowPressFeedback:YES];
6852 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
6853 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
6854 [accessory_ addSubview:configure];*/
6856 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6857 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6863 LKAnimation *animation = [LKTransition animation];
6864 [animation setType:@"oglFlip"];
6865 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
6866 [animation setFillMode:@"extended"];
6867 [animation setTransitionFlags:3];
6868 [animation setDuration:10];
6869 [animation setSpeed:0.35];
6870 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
6871 [[transition_ _layer] addAnimation:animation forKey:0];
6872 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
6873 flipped_ = !flipped_;
6877 - (void) configurePushed {
6878 [field_ resignFirstResponder];
6882 - (void) resetViewAnimated:(BOOL)animated {
6885 [table_ resetViewAnimated:animated];
6888 - (void) _reloadData {
6891 - (void) reloadData {
6894 [table_ setObject:[field_ text]];
6895 _profile(SearchView$reloadData)
6896 [table_ reloadData];
6899 [table_ resetCursor];
6902 - (UIView *) accessoryView {
6906 - (NSString *) title {
6910 - (NSString *) backButtonTitle {
6911 return CYLocalize("SEARCH");
6914 - (void) setDelegate:(id)delegate {
6915 [table_ setDelegate:delegate];
6916 [super setDelegate:delegate];
6922 @interface SettingsView : RVPage {
6923 _transient Database *database_;
6926 UIPreferencesTable *table_;
6927 _UISwitchSlider *subscribedSwitch_;
6928 _UISwitchSlider *ignoredSwitch_;
6929 UIPreferencesControlTableCell *subscribedCell_;
6930 UIPreferencesControlTableCell *ignoredCell_;
6933 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6937 @implementation SettingsView
6940 [table_ setDataSource:nil];
6943 if (package_ != nil)
6946 [subscribedSwitch_ release];
6947 [ignoredSwitch_ release];
6948 [subscribedCell_ release];
6949 [ignoredCell_ release];
6953 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6954 if (package_ == nil)
6960 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6961 if (package_ == nil)
6968 default: _assert(false);
6974 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
6975 if (package_ == nil)
6982 default: _assert(false);
6988 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6989 if (package_ == nil)
6996 default: _assert(false);
7002 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7003 if (package_ == nil)
7006 _UISwitchSlider *slider([cell control]);
7007 BOOL value([slider value] != 0);
7008 NSMutableDictionary *metadata([package_ metadata]);
7011 if (NSNumber *number = [metadata objectForKey:key])
7012 before = [number boolValue];
7016 if (value != before) {
7017 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7019 [delegate_ updateData];
7023 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7024 [self onSomething:cell withKey:@"IsSubscribed"];
7027 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7028 [self onSomething:cell withKey:@"IsIgnored"];
7031 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7032 if (package_ == nil)
7036 case 0: switch (row) {
7038 return subscribedCell_;
7040 return ignoredCell_;
7041 default: _assert(false);
7044 case 1: switch (row) {
7046 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7047 [cell setShowSelection:NO];
7048 [cell setTitle:CYLocalize("SHOW_ALL_CHANGES_EX")];
7052 default: _assert(false);
7055 default: _assert(false);
7061 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7062 if ((self = [super initWithBook:book])) {
7063 database_ = database;
7064 name_ = [package retain];
7066 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7067 [self addSubview:table_];
7069 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7070 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
7072 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7073 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
7075 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7076 [subscribedCell_ setShowSelection:NO];
7077 [subscribedCell_ setTitle:CYLocalize("SHOW_ALL_CHANGES")];
7078 [subscribedCell_ setControl:subscribedSwitch_];
7080 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7081 [ignoredCell_ setShowSelection:NO];
7082 [ignoredCell_ setTitle:CYLocalize("IGNORE_UPGRADES")];
7083 [ignoredCell_ setControl:ignoredSwitch_];
7085 [table_ setDataSource:self];
7090 - (void) resetViewAnimated:(BOOL)animated {
7091 [table_ resetViewAnimated:animated];
7094 - (void) reloadData {
7095 if (package_ != nil)
7096 [package_ autorelease];
7097 package_ = [database_ packageWithName:name_];
7098 if (package_ != nil) {
7100 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7101 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7104 [table_ reloadData];
7107 - (NSString *) title {
7108 return CYLocalize("SETTINGS");
7113 /* Signature View {{{ */
7114 @interface SignatureView : BrowserView {
7115 _transient Database *database_;
7119 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7123 @implementation SignatureView
7130 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7132 [super webView:sender didClearWindowObject:window forFrame:frame];
7135 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7136 if ((self = [super initWithBook:book]) != nil) {
7137 database_ = database;
7138 package_ = [package retain];
7143 - (void) resetViewAnimated:(BOOL)animated {
7146 - (void) reloadData {
7147 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7153 @interface Cydia : UIApplication <
7154 ConfirmationViewDelegate,
7155 ProgressViewDelegate,
7164 UIToolbar *buttonbar_;
7168 NSMutableArray *essential_;
7169 NSMutableArray *broken_;
7171 Database *database_;
7172 ProgressView *progress_;
7176 UIKeyboard *keyboard_;
7177 UIProgressHUD *hud_;
7179 SectionsView *sections_;
7180 ChangesView *changes_;
7181 ManageView *manage_;
7182 SearchView *search_;
7184 PackageView *package_;
7189 @implementation Cydia
7192 if ([broken_ count] != 0) {
7193 int count = [broken_ count];
7195 UIActionSheet *sheet = [[[UIActionSheet alloc]
7196 initWithTitle:(count == 1 ? CYLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:CYLocalize("HALFINSTALLED_PACKAGES"), count])
7197 buttons:[NSArray arrayWithObjects:
7198 CYLocalize("FORCIBLY_CLEAR"),
7199 CYLocalize("TEMPORARY_IGNORE"),
7201 defaultButtonIndex:0
7206 [sheet setBodyText:CYLocalize("HALFINSTALLED_PACKAGE_EX")];
7207 [sheet popupAlertAnimated:YES];
7208 } else if (!Ignored_ && [essential_ count] != 0) {
7209 int count = [essential_ count];
7211 UIActionSheet *sheet = [[[UIActionSheet alloc]
7212 initWithTitle:(count == 1 ? CYLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:CYLocalize("ESSENTIAL_UPGRADES"), count])
7213 buttons:[NSArray arrayWithObjects:
7214 CYLocalize("UPGRADE_ESSENTIAL"),
7215 CYLocalize("COMPLETE_UPGRADE"),
7216 CYLocalize("TEMPORARY_IGNORE"),
7218 defaultButtonIndex:0
7223 [sheet setBodyText:CYLocalize("ESSENTIAL_UPGRADE_EX")];
7224 [sheet popupAlertAnimated:YES];
7228 - (void) _reloadData {
7231 static bool loaded(false);
7232 UIProgressHUD *hud([self addProgressHUD]);
7233 [hud setText:(loaded ? CYLocalize("RELOADING_DATA") : CYLocalize("LOADING_DATA"))];
7236 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7239 [self removeProgressHUD:hud];
7243 [essential_ removeAllObjects];
7244 [broken_ removeAllObjects];
7246 NSArray *packages = [database_ packages];
7247 for (Package *package in packages) {
7249 [broken_ addObject:package];
7250 if ([package upgradableAndEssential:NO]) {
7251 if ([package essential])
7252 [essential_ addObject:package];
7258 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7259 [buttonbar_ setBadgeValue:badge forButton:3];
7260 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7261 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7262 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7263 [self setApplicationBadge:badge];
7265 [self setApplicationBadgeString:badge];
7267 [buttonbar_ setBadgeValue:nil forButton:3];
7268 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7269 [buttonbar_ setBadgeAnimated:NO forButton:3];
7270 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7271 [self removeApplicationBadge];
7272 else // XXX: maybe use setApplicationBadgeString also?
7273 [self setApplicationIconBadgeNumber:0];
7277 [buttonbar_ setBadgeValue:nil forButton:4];
7281 // XXX: what is this line of code for?
7282 if ([packages count] == 0);
7283 else if (Loaded_ || ManualRefresh) loaded:
7288 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7289 NSTimeInterval interval([update timeIntervalSinceNow]);
7290 if (interval <= 0 && interval > -600)
7298 - (void) _saveConfig {
7301 NSString *error(nil);
7302 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7304 NSError *error(nil);
7305 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7306 NSLog(@"failure to save metadata data: %@", error);
7309 NSLog(@"failure to serialize metadata: %@", error);
7317 - (void) updateData {
7320 /* XXX: this is just stupid */
7321 if (tag_ != 2 && sections_ != nil)
7322 [sections_ reloadData];
7323 if (tag_ != 3 && changes_ != nil)
7324 [changes_ reloadData];
7325 if (tag_ != 5 && search_ != nil)
7326 [search_ reloadData];
7336 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7337 _assert(file != NULL);
7339 NSArray *keys = [Sources_ allKeys];
7341 for (NSString *key in keys) {
7342 NSDictionary *source = [Sources_ objectForKey:key];
7344 fprintf(file, "%s %s %s\n",
7345 [[source objectForKey:@"Type"] UTF8String],
7346 [[source objectForKey:@"URI"] UTF8String],
7347 [[source objectForKey:@"Distribution"] UTF8String]
7356 detachNewThreadSelector:@selector(update_)
7359 title:CYLocalize("UPDATING_SOURCES")
7363 - (void) reloadData {
7364 @synchronized (self) {
7365 if (confirm_ == nil)
7371 pkgProblemResolver *resolver = [database_ resolver];
7373 resolver->InstallProtect();
7374 if (!resolver->Resolve(true))
7378 - (void) popUpBook:(RVBook *)book {
7379 [underlay_ popSubview:book];
7382 - (CGRect) popUpBounds {
7383 return [underlay_ bounds];
7387 [database_ prepare];
7389 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7390 [confirm_ setDelegate:self];
7392 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7393 [page setDelegate:self];
7395 [confirm_ setPage:page];
7396 [self popUpBook:confirm_];
7400 @synchronized (self) {
7405 - (void) clearPackage:(Package *)package {
7406 @synchronized (self) {
7413 - (void) installPackage:(Package *)package {
7414 @synchronized (self) {
7421 - (void) removePackage:(Package *)package {
7422 @synchronized (self) {
7429 - (void) distUpgrade {
7430 @synchronized (self) {
7431 [database_ upgrade];
7437 [self slideUp:[[[UIActionSheet alloc]
7439 buttons:[NSArray arrayWithObjects:CYLocalize("CONTINUE_QUEUING"), CYLocalize("CANCEL_CLEAR"), nil]
7440 defaultButtonIndex:1
7447 @synchronized (self) {
7450 if (confirm_ != nil) {
7458 [overlay_ removeFromSuperview];
7462 detachNewThreadSelector:@selector(perform)
7465 title:CYLocalize("RUNNING")
7469 - (void) bootstrap_ {
7471 [database_ upgrade];
7472 [database_ prepare];
7473 [database_ perform];
7476 /* XXX: replace and localize */
7477 - (void) bootstrap {
7479 detachNewThreadSelector:@selector(bootstrap_)
7482 title:@"Bootstrap Install"
7486 - (void) progressViewIsComplete:(ProgressView *)progress {
7487 if (confirm_ != nil) {
7488 [underlay_ addSubview:overlay_];
7489 [confirm_ popFromSuperviewAnimated:NO];
7495 - (void) setPage:(RVPage *)page {
7496 [page resetViewAnimated:NO];
7497 [page setDelegate:self];
7498 [book_ setPage:page];
7501 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7502 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7503 [browser loadURL:url];
7507 - (void) _setHomePage {
7508 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7511 - (SectionsView *) sectionsView {
7512 if (sections_ == nil)
7513 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7517 - (void) buttonBarItemTapped:(id)sender {
7518 unsigned tag = [sender tag];
7520 [book_ resetViewAnimated:YES];
7522 } else if (tag_ == 2 && tag != 2)
7523 [[self sectionsView] resetView];
7526 case 1: [self _setHomePage]; break;
7528 case 2: [self setPage:[self sectionsView]]; break;
7529 case 3: [self setPage:changes_]; break;
7530 case 4: [self setPage:manage_]; break;
7531 case 5: [self setPage:search_]; break;
7533 default: _assert(false);
7539 - (void) applicationWillSuspend {
7541 [super applicationWillSuspend];
7544 - (void) askForSettings {
7545 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
7547 UIActionSheet *role = [[[UIActionSheet alloc]
7548 initWithTitle:CYLocalize("WHO_ARE_YOU")
7549 buttons:[NSArray arrayWithObjects:
7550 [NSString stringWithFormat:parenthetical, CYLocalize("USER"), CYLocalize("USER_EX")],
7551 [NSString stringWithFormat:parenthetical, CYLocalize("HACKER"), CYLocalize("HACKER_EX")],
7552 [NSString stringWithFormat:parenthetical, CYLocalize("DEVELOPER"), CYLocalize("DEVELOPER_EX")],
7554 defaultButtonIndex:-1
7559 [role setBodyText:CYLocalize("ROLE_EX")];
7560 [role popupAlertAnimated:YES];
7563 - (void) setPackageView:(PackageView *)view {
7564 if (package_ == nil)
7565 package_ = [view retain];
7568 - (PackageView *) packageView {
7571 if (package_ == nil)
7572 view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7575 view = [package_ autorelease];
7584 [self setStatusBarShowsProgress:NO];
7585 [self removeProgressHUD:hud_];
7590 pid_t pid = ExecFork();
7592 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7593 perror("launchctl stop");
7600 [self askForSettings];
7605 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7607 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7608 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7609 0, 0, screenrect.size.width, screenrect.size.height - 48
7610 ) database:database_];
7612 [book_ setDelegate:self];
7614 [overlay_ addSubview:book_];
7616 NSArray *buttonitems = [NSArray arrayWithObjects:
7617 [NSDictionary dictionaryWithObjectsAndKeys:
7618 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7619 @"home-up.png", kUIButtonBarButtonInfo,
7620 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7621 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7622 self, kUIButtonBarButtonTarget,
7623 @"Cydia", kUIButtonBarButtonTitle,
7624 @"0", kUIButtonBarButtonType,
7627 [NSDictionary dictionaryWithObjectsAndKeys:
7628 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7629 @"install-up.png", kUIButtonBarButtonInfo,
7630 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7631 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7632 self, kUIButtonBarButtonTarget,
7633 CYLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7634 @"0", kUIButtonBarButtonType,
7637 [NSDictionary dictionaryWithObjectsAndKeys:
7638 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7639 @"changes-up.png", kUIButtonBarButtonInfo,
7640 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7641 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7642 self, kUIButtonBarButtonTarget,
7643 CYLocalize("CHANGES"), kUIButtonBarButtonTitle,
7644 @"0", kUIButtonBarButtonType,
7647 [NSDictionary dictionaryWithObjectsAndKeys:
7648 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7649 @"manage-up.png", kUIButtonBarButtonInfo,
7650 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7651 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7652 self, kUIButtonBarButtonTarget,
7653 CYLocalize("MANAGE"), kUIButtonBarButtonTitle,
7654 @"0", kUIButtonBarButtonType,
7657 [NSDictionary dictionaryWithObjectsAndKeys:
7658 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7659 @"search-up.png", kUIButtonBarButtonInfo,
7660 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7661 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7662 self, kUIButtonBarButtonTarget,
7663 CYLocalize("SEARCH"), kUIButtonBarButtonTitle,
7664 @"0", kUIButtonBarButtonType,
7668 buttonbar_ = [[UIToolbar alloc]
7670 withFrame:CGRectMake(
7671 0, screenrect.size.height - ButtonBarHeight_,
7672 screenrect.size.width, ButtonBarHeight_
7674 withItemList:buttonitems
7677 [buttonbar_ setDelegate:self];
7678 [buttonbar_ setBarStyle:1];
7679 [buttonbar_ setButtonBarTrackingMode:2];
7681 int buttons[5] = {1, 2, 3, 4, 5};
7682 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7683 [buttonbar_ showButtonGroup:0 withDuration:0];
7685 for (int i = 0; i != 5; ++i)
7686 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7687 i * 64 + 2, 1, 60, ButtonBarHeight_
7690 [buttonbar_ showSelectionForButton:1];
7691 [overlay_ addSubview:buttonbar_];
7693 [UIKeyboard initImplementationNow];
7694 CGSize keysize = [UIKeyboard defaultSize];
7695 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7696 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7697 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
7698 [overlay_ addSubview:keyboard_];
7701 [underlay_ addSubview:overlay_];
7705 [self sectionsView];
7706 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7707 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7709 manage_ = (ManageView *) [[self
7710 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7711 withClass:[ManageView class]
7714 [self setPackageView:[self packageView]];
7721 [self _setHomePage];
7724 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7725 NSString *context([sheet context]);
7727 if ([context isEqualToString:@"missing"])
7729 else if ([context isEqualToString:@"cancel"]) {
7747 @synchronized (self) {
7752 [buttonbar_ setBadgeValue:CYLocalize("Q_D") forButton:4];
7756 if (confirm_ != nil) {
7761 } else if ([context isEqualToString:@"fixhalf"]) {
7764 @synchronized (self) {
7765 for (Package *broken in broken_) {
7768 NSString *id = [broken id];
7769 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7770 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7771 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7772 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7781 [broken_ removeAllObjects];
7790 } else if ([context isEqualToString:@"role"]) {
7792 case 1: Role_ = @"User"; break;
7793 case 2: Role_ = @"Hacker"; break;
7794 case 3: Role_ = @"Developer"; break;
7801 bool reset = Settings_ != nil;
7803 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7807 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7817 } else if ([context isEqualToString:@"upgrade"]) {
7820 @synchronized (self) {
7821 for (Package *essential in essential_)
7822 [essential install];
7845 - (void) reorganize { _pooled
7846 system("/usr/libexec/cydia/free.sh");
7847 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
7850 - (void) applicationSuspend:(__GSEvent *)event {
7851 if (hud_ == nil && ![progress_ isRunning])
7852 [super applicationSuspend:event];
7855 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7857 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7860 - (void) _setSuspended:(BOOL)value {
7862 [super _setSuspended:value];
7865 - (UIProgressHUD *) addProgressHUD {
7866 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
7867 [window_ setUserInteractionEnabled:NO];
7869 [progress_ addSubview:hud];
7873 - (void) removeProgressHUD:(UIProgressHUD *)hud {
7875 [hud removeFromSuperview];
7876 [window_ setUserInteractionEnabled:YES];
7879 - (void) openMailToURL:(NSURL *)url {
7880 // XXX: this makes me sad
7882 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
7884 [UIApp openURL:url];// asPanel:YES];
7888 - (void) clearFirstResponder {
7889 if (id responder = [window_ firstResponder])
7890 [responder resignFirstResponder];
7893 - (RVPage *) pageForPackage:(NSString *)name {
7894 if (Package *package = [database_ packageWithName:name]) {
7895 PackageView *view([self packageView]);
7896 [view setPackage:package];
7899 UIActionSheet *sheet = [[[UIActionSheet alloc]
7900 initWithTitle:CYLocalize("CANNOT_LOCATE_PACKAGE")
7901 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
7902 defaultButtonIndex:0
7907 [sheet setBodyText:[NSString stringWithFormat:CYLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
7909 [sheet popupAlertAnimated:YES];
7914 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
7918 NSString *scheme([[url scheme] lowercaseString]);
7919 if (![scheme isEqualToString:@"cydia"])
7921 NSString *path([url absoluteString]);
7922 if ([path length] < 8)
7924 path = [path substringFromIndex:8];
7925 if (![path hasPrefix:@"/"])
7926 path = [@"/" stringByAppendingString:path];
7928 if ([path isEqualToString:@"/add-source"])
7929 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
7930 else if ([path isEqualToString:@"/storage"])
7931 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[BrowserView class]];
7932 else if ([path isEqualToString:@"/sources"])
7933 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
7934 else if ([path isEqualToString:@"/packages"])
7935 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
7936 else if ([path hasPrefix:@"/url/"])
7937 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[BrowserView class]];
7938 else if ([path hasPrefix:@"/launch/"])
7939 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
7940 else if ([path hasPrefix:@"/package-settings/"])
7941 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
7942 else if ([path hasPrefix:@"/package-signature/"])
7943 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
7944 else if ([path hasPrefix:@"/package/"])
7945 return [self pageForPackage:[path substringFromIndex:9]];
7946 else if ([path hasPrefix:@"/files/"]) {
7947 NSString *name = [path substringFromIndex:7];
7949 if (Package *package = [database_ packageWithName:name]) {
7950 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
7951 [files setPackage:package];
7959 - (void) applicationOpenURL:(NSURL *)url {
7960 [super applicationOpenURL:url];
7962 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
7963 [self setPage:page];
7964 [buttonbar_ showSelectionForButton:tag];
7969 - (void) applicationDidFinishLaunching:(id)unused {
7971 Font12_ = [[UIFont systemFontOfSize:12] retain];
7972 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
7973 Font14_ = [[UIFont systemFontOfSize:14] retain];
7974 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
7975 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
7979 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
7980 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
7982 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
7984 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7985 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
7987 [window_ orderFront:self];
7988 [window_ makeKey:self];
7989 [window_ setHidden:NO];
7991 database_ = [Database sharedInstance];
7992 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
7993 [database_ setDelegate:progress_];
7994 [window_ setContentView:progress_];
7996 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
7997 [progress_ setContentView:underlay_];
7999 [progress_ resetView];
8002 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8003 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8004 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8005 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8006 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8007 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
8008 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
8010 [self setIdleTimerDisabled:YES];
8012 hud_ = [[self addProgressHUD] retain];
8013 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8015 [self setStatusBarShowsProgress:YES];
8018 detachNewThreadSelector:@selector(reorganize)
8026 - (void) showKeyboard:(BOOL)show {
8027 CGSize keysize = [UIKeyboard defaultSize];
8028 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8029 CGRect keyup = keydown;
8030 keyup.origin.y -= keysize.height;
8032 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
8033 [animation setSignificantRectFields:2];
8036 [animation setStartFrame:keydown];
8037 [animation setEndFrame:keyup];
8038 [keyboard_ activate];
8040 [animation setStartFrame:keyup];
8041 [animation setEndFrame:keydown];
8042 [keyboard_ deactivate];
8045 [[UIAnimator sharedAnimator]
8046 addAnimations:[NSArray arrayWithObjects:animation, nil]
8047 withDuration:KeyboardTime_
8052 - (void) slideUp:(UIActionSheet *)alert {
8054 [alert presentSheetFromButtonBar:buttonbar_];
8056 [alert presentSheetInView:overlay_];
8061 void AddPreferences(NSString *plist) { _pooled
8062 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
8063 _assert(settings != NULL);
8064 NSMutableArray *items = [settings objectForKey:@"items"];
8068 for (NSMutableDictionary *item in items) {
8069 NSString *label = [item objectForKey:@"label"];
8070 if (label != nil && [label isEqualToString:@"Cydia"]) {
8077 for (size_t i(0); i != [items count]; ++i) {
8078 NSDictionary *item([items objectAtIndex:i]);
8079 NSString *label = [item objectForKey:@"label"];
8080 if (label != nil && [label isEqualToString:@"General"]) {
8081 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
8082 @"CydiaSettings", @"bundle",
8083 @"PSLinkCell", @"cell",
8084 [NSNumber numberWithBool:YES], @"hasIcon",
8085 [NSNumber numberWithBool:YES], @"isController",
8087 nil] atIndex:(i + 1)];
8093 _assert([settings writeToFile:plist atomically:YES] == YES);
8098 id Alloc_(id self, SEL selector) {
8099 id object = alloc_(self, selector);
8100 lprintf("[%s]A-%p\n", self->isa->name, object);
8105 id Dealloc_(id self, SEL selector) {
8106 id object = dealloc_(self, selector);
8107 lprintf("[%s]D-%p\n", self->isa->name, object);
8111 Class $WebDefaultUIKitDelegate;
8113 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
8115 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
8116 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8117 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8118 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
8121 int main(int argc, char *argv[]) { _pooled
8124 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8126 /* Library Hacks {{{ */
8127 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8129 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8130 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8131 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8132 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8133 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8136 /* Set Locale {{{ */
8137 Locale_ = CFLocaleCopyCurrent();
8138 Languages_ = [NSLocale preferredLanguages];
8139 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8140 //NSLog(@"%@", [Languages_ description]);
8142 if (Languages_ == nil || [Languages_ count] == 0)
8145 lang = [[Languages_ objectAtIndex:0] UTF8String];
8146 setenv("LANG", lang, true);
8147 //std::setlocale(LC_ALL, lang);
8148 NSLog(@"Setting Language: %s", lang);
8151 // XXX: apr_app_initialize?
8154 /* Parse Arguments {{{ */
8155 bool substrate(false);
8161 for (int argi(1); argi != argc; ++argi)
8162 if (strcmp(argv[argi], "--") == 0) {
8164 argv[argi] = argv[0];
8170 for (int argi(1); argi != arge; ++argi)
8171 if (strcmp(args[argi], "--bootstrap") == 0)
8173 else if (strcmp(args[argi], "--substrate") == 0)
8176 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8181 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
8182 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
8183 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
8184 Sounds_Keyboard_ = [keyboard boolValue];
8187 App_ = [[NSBundle mainBundle] bundlePath];
8188 Home_ = NSHomeDirectory();
8193 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8194 alloc_ = alloc->method_imp;
8195 alloc->method_imp = (IMP) &Alloc_;*/
8197 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8198 dealloc_ = dealloc->method_imp;
8199 dealloc->method_imp = (IMP) &Dealloc_;*/
8204 size = sizeof(maxproc);
8205 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8206 perror("sysctlbyname(\"kern.maxproc\", ?)");
8207 else if (maxproc < 64) {
8209 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8210 perror("sysctlbyname(\"kern.maxproc\", #)");
8213 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8214 char *machine = new char[size];
8215 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8216 perror("sysctlbyname(\"hw.machine\", ?)");
8220 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8222 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8223 Build_ = [system objectForKey:@"ProductBuildVersion"];
8224 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8225 Product_ = [info objectForKey:@"SafariProductVersion"];
8226 Safari_ = [info objectForKey:@"CFBundleVersion"];
8229 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8230 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
8232 /* Load Database {{{ */
8234 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8236 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8239 if (Metadata_ == NULL)
8240 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8242 Settings_ = [Metadata_ objectForKey:@"Settings"];
8244 Packages_ = [Metadata_ objectForKey:@"Packages"];
8245 Sections_ = [Metadata_ objectForKey:@"Sections"];
8246 Sources_ = [Metadata_ objectForKey:@"Sources"];
8249 if (Settings_ != nil)
8250 Role_ = [Settings_ objectForKey:@"Role"];
8252 if (Packages_ == nil) {
8253 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8254 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8257 if (Sections_ == nil) {
8258 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8259 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8262 if (Sources_ == nil) {
8263 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8264 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8269 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8272 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8273 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8274 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8275 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8277 if (access("/User", F_OK) != 0) {
8279 system("/usr/libexec/cydia/firmware.sh");
8283 _assert([[NSFileManager defaultManager]
8284 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8285 withIntermediateDirectories:YES
8290 if (access("/tmp/cydia.chk", F_OK) == 0) {
8291 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8292 _assert(errno == ENOENT);
8293 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8294 _assert(errno == ENOENT);
8297 _assert(pkgInitConfig(*_config));
8298 _assert(pkgInitSystem(*_config, _system));
8301 _config->Set("APT::Acquire::Translation", lang);
8302 _config->Set("Acquire::http::Timeout", 15);
8303 _config->Set("Acquire::http::MaxParallel", 4);
8305 /* Color Choices {{{ */
8306 space_ = CGColorSpaceCreateDeviceRGB();
8308 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8309 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8310 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8311 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8312 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8313 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8314 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8315 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8316 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8317 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8318 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8319 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8320 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8321 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8322 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8325 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8326 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8329 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8331 /* UIKit Configuration {{{ */
8332 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8333 if ($GSFontSetUseLegacyFontMetrics != NULL)
8334 $GSFontSetUseLegacyFontMetrics(YES);
8336 UIKeyboardDisableAutomaticAppearance();
8340 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8342 CGColorSpaceRelease(space_);