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 CFStringRef StripVersion(const char *version) {
1142 const char *colon(strchr(version, ':'));
1144 version = colon + 1;
1145 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(version), strlen(version), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
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_ = (NSString *) StripVersion(version_.VerStr());
2044 pkgCache::VerIterator current;
2045 _profile(Package$initWithVersion$Versions)
2046 current = iterator_.CurrentVer();
2048 installed_ = (NSString *) StripVersion(current.VerStr());
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) {
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) {
3104 [packages_ removeAllObjects];
3130 apr_pool_clear(pool_);
3131 NSRecycleZone(zone_);
3133 int chk(creat("/tmp/cydia.chk", 0644));
3138 if (!cache_.Open(progress_, true)) {
3140 if (!_error->PopMessage(error))
3143 lprintf("cache_.Open():[%s]\n", error.c_str());
3145 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3146 [delegate_ repairWithSelector:@selector(configure)];
3147 else if (error == "The package lists or status file could not be parsed or opened.")
3148 [delegate_ repairWithSelector:@selector(update)];
3149 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3150 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3151 // else if (error == "The list of sources could not be read.")
3152 else _assert(false);
3158 unlink("/tmp/cydia.chk");
3160 now_ = [[NSDate date] retain];
3162 policy_ = new pkgDepCache::Policy();
3163 records_ = new pkgRecords(cache_);
3164 resolver_ = new pkgProblemResolver(cache_);
3165 fetcher_ = new pkgAcquire(&status_);
3168 list_ = new pkgSourceList();
3169 _assert(list_->ReadMainList());
3171 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3172 _assert(pkgApplyStatus(cache_));
3174 if (cache_->BrokenCount() != 0) {
3175 _assert(pkgFixBroken(cache_));
3176 _assert(cache_->BrokenCount() == 0);
3177 _assert(pkgMinimizeUpgrade(cache_));
3182 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3183 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3184 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3185 // XXX: this could be more intelligent
3186 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3187 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3189 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source] autorelease];
3196 /*std::vector<Package *> packages;
3197 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3198 [packages_ release];
3203 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3204 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3205 //packages.push_back(package);
3206 [packages_ addObject:package];
3210 /*if (packages.empty())
3211 packages_ = [[NSArray alloc] init];
3213 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3216 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3217 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3218 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3226 /*if (!packages.empty())
3227 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3228 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3230 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3232 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3234 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3240 - (void) configure {
3241 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3242 system([dpkg UTF8String]);
3250 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3251 _assert(!_error->PendingError());
3254 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3257 public pkgArchiveCleaner
3260 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3265 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3267 while (_error->PopMessage(error))
3268 lprintf("ArchiveCleaner: %s\n", error.c_str());
3273 pkgRecords records(cache_);
3275 lock_ = new FileFd();
3276 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3277 _assert(!_error->PendingError());
3280 // XXX: explain this with an error message
3281 _assert(list.ReadMainList());
3283 manager_ = (_system->CreatePM(cache_));
3284 _assert(manager_->GetArchives(fetcher_, &list, &records));
3285 _assert(!_error->PendingError());
3289 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3291 _assert(list.ReadMainList());
3292 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3293 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3296 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3301 bool failed = false;
3302 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3303 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3306 std::string uri = (*item)->DescURI();
3307 std::string error = (*item)->ErrorText;
3309 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3312 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3313 withObject:[NSArray arrayWithObjects:
3314 [NSString stringWithUTF8String:error.c_str()],
3326 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3328 if (_error->PendingError()) {
3333 if (result == pkgPackageManager::Failed) {
3338 if (result != pkgPackageManager::Completed) {
3343 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3345 _assert(list.ReadMainList());
3346 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3347 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3350 if (![before isEqualToArray:after])
3355 _assert(pkgDistUpgrade(cache_));
3359 [self updateWithStatus:status_];
3362 - (void) updateWithStatus:(Status &)status {
3364 _assert(list.ReadMainList());
3367 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3368 _assert(!_error->PendingError());
3370 pkgAcquire fetcher(&status);
3371 _assert(list.GetIndexes(&fetcher));
3373 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3374 bool failed = false;
3375 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3376 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3377 (*item)->Finished();
3381 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3382 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3383 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3386 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3391 - (void) setDelegate:(id)delegate {
3392 delegate_ = delegate;
3393 status_.setDelegate(delegate);
3394 progress_.setDelegate(delegate);
3397 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3398 return sources_[file->ID];
3404 /* PopUp Windows {{{ */
3405 @interface PopUpView : UIView {
3406 _transient id delegate_;
3407 UITransitionView *transition_;
3412 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3416 @implementation PopUpView
3419 [transition_ setDelegate:nil];
3420 [transition_ release];
3426 [transition_ transition:UITransitionPushFromTop toView:nil];
3429 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3430 if (from != nil && to == nil)
3431 [self removeFromSuperview];
3434 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3435 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3436 delegate_ = delegate;
3438 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3439 [self addSubview:transition_];
3441 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3443 [view addSubview:self];
3445 [transition_ setDelegate:self];
3447 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3448 [transition_ transition:UITransitionNone toView:blank];
3449 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3457 /* Mail Composition {{{ */
3458 @interface MailToView : PopUpView {
3459 MailComposeController *controller_;
3462 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
3466 @implementation MailToView
3469 [controller_ release];
3473 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
3477 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
3478 NSLog(@"did:%@", delivery);
3479 // [UIApp setStatusBarShowsProgress:NO];
3480 if ([controller error]){
3481 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3482 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3483 [mailAlertSheet setBodyText:[controller error]];
3484 [mailAlertSheet popupAlertAnimated:YES];
3488 - (void) showError {
3489 NSLog(@"%@", [controller_ error]);
3490 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3491 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3492 [mailAlertSheet setBodyText:[controller_ error]];
3493 [mailAlertSheet popupAlertAnimated:YES];
3496 - (void) deliverMessage { _pooled
3500 if (![controller_ deliverMessage])
3501 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
3504 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
3505 if ([controller_ needsDelivery])
3506 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
3511 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
3512 if ((self = [super initWithView:view delegate:delegate]) != nil) {
3513 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
3514 [controller_ setDelegate:self];
3515 [controller_ initializeUI];
3516 [controller_ setupForURL:url];
3518 UIView *view([controller_ view]);
3519 [overlay_ addSubview:view];
3527 /* Confirmation View {{{ */
3528 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3529 if (!iterator.end())
3530 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3531 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3533 pkgCache::PkgIterator package(dep.TargetPkg());
3536 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3543 @protocol ConfirmationViewDelegate
3549 @interface ConfirmationView : BrowserView {
3550 _transient Database *database_;
3551 UIActionSheet *essential_;
3558 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3562 @implementation ConfirmationView
3569 if (essential_ != nil)
3570 [essential_ release];
3576 [book_ popFromSuperviewAnimated:YES];
3579 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3580 NSString *context([sheet context]);
3582 if ([context isEqualToString:@"remove"]) {
3590 [delegate_ confirm];
3597 } else if ([context isEqualToString:@"unable"]) {
3601 [super alertSheet:sheet buttonClicked:button];
3604 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3605 [super webView:sender didClearWindowObject:window forFrame:frame];
3606 [window setValue:changes_ forKey:@"changes"];
3607 [window setValue:issues_ forKey:@"issues"];
3608 [window setValue:sizes_ forKey:@"sizes"];
3611 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3612 if ((self = [super initWithBook:book]) != nil) {
3613 database_ = database;
3615 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3616 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3617 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3618 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3619 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3623 pkgDepCache::Policy *policy([database_ policy]);
3625 pkgCacheFile &cache([database_ cache]);
3626 NSArray *packages = [database_ packages];
3627 for (Package *package in packages) {
3628 pkgCache::PkgIterator iterator = [package iterator];
3629 pkgDepCache::StateCache &state(cache[iterator]);
3631 NSString *name([package name]);
3633 if (state.NewInstall())
3634 [installing addObject:name];
3635 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3636 [reinstalling addObject:name];
3637 else if (state.Upgrade())
3638 [upgrading addObject:name];
3639 else if (state.Downgrade())
3640 [downgrading addObject:name];
3641 else if (state.Delete()) {
3642 if ([package essential])
3644 [removing addObject:name];
3647 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3648 substrate_ |= DepSubstrate(iterator.CurrentVer());
3653 else if (Advanced_ || true) {
3654 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
3656 essential_ = [[UIActionSheet alloc]
3657 initWithTitle:CYLocalize("REMOVING_ESSENTIALS")
3658 buttons:[NSArray arrayWithObjects:
3659 [NSString stringWithFormat:parenthetical, CYLocalize("CANCEL_OPERATION"), CYLocalize("SAFE")],
3660 [NSString stringWithFormat:parenthetical, CYLocalize("FORCE_REMOVAL"), CYLocalize("UNSAFE")],
3662 defaultButtonIndex:0
3668 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3670 [essential_ setBodyText:CYLocalize("REMOVING_ESSENTIALS_EX")];
3672 essential_ = [[UIActionSheet alloc]
3673 initWithTitle:CYLocalize("UNABLE_TO_COMPLY")
3674 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3675 defaultButtonIndex:0
3680 [essential_ setBodyText:CYLocalize("UNABLE_TO_COMPLY_EX")];
3683 changes_ = [[NSArray alloc] initWithObjects:
3691 issues_ = [database_ issues];
3693 issues_ = [issues_ retain];
3695 sizes_ = [[NSArray alloc] initWithObjects:
3696 SizeString([database_ fetcher].FetchNeeded()),
3697 SizeString([database_ fetcher].PartialPresent()),
3698 SizeString([database_ cache]->UsrSize()),
3701 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3705 - (NSString *) backButtonTitle {
3706 return CYLocalize("CONFIRM");
3709 - (NSString *) leftButtonTitle {
3710 return [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("CANCEL"), CYLocalize("QUEUE")];
3713 - (id) rightButtonTitle {
3714 return issues_ != nil ? nil : [super rightButtonTitle];
3717 - (id) _rightButtonTitle {
3718 #if AlwaysReload || IgnoreInstall
3719 return [super _rightButtonTitle];
3721 return CYLocalize("CONFIRM");
3725 - (void) _leftButtonClicked {
3730 - (void) _rightButtonClicked {
3732 return [super _rightButtonClicked];
3734 if (essential_ != nil)
3735 [essential_ popupAlertAnimated:YES];
3739 [delegate_ confirm];
3747 /* Progress Data {{{ */
3748 @interface ProgressData : NSObject {
3754 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3761 @implementation ProgressData
3763 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3764 if ((self = [super init]) != nil) {
3765 selector_ = selector;
3785 /* Progress View {{{ */
3786 @interface ProgressView : UIView <
3787 ConfigurationDelegate,
3790 _transient Database *database_;
3792 UIView *background_;
3793 UITransitionView *transition_;
3795 UINavigationBar *navbar_;
3796 UIProgressBar *progress_;
3797 UITextView *output_;
3798 UITextLabel *status_;
3799 UIPushButton *close_;
3802 SHA1SumValue springlist_;
3803 SHA1SumValue notifyconf_;
3804 SHA1SumValue sandplate_;
3807 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
3809 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
3810 - (void) setContentView:(UIView *)view;
3813 - (void) _retachThread;
3814 - (void) _detachNewThreadData:(ProgressData *)data;
3815 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
3821 @protocol ProgressViewDelegate
3822 - (void) progressViewIsComplete:(ProgressView *)sender;
3825 @implementation ProgressView
3828 [transition_ setDelegate:nil];
3829 [navbar_ setDelegate:nil];
3832 if (background_ != nil)
3833 [background_ release];
3834 [transition_ release];
3837 [progress_ release];
3844 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3845 if (bootstrap_ && from == overlay_ && to == view_)
3849 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
3850 if ((self = [super initWithFrame:frame]) != nil) {
3851 database_ = database;
3852 delegate_ = delegate;
3854 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3855 [transition_ setDelegate:self];
3857 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3860 [overlay_ setBackgroundColor:[UIColor blackColor]];
3862 background_ = [[UIView alloc] initWithFrame:[self bounds]];
3863 [background_ setBackgroundColor:[UIColor blackColor]];
3864 [self addSubview:background_];
3867 [self addSubview:transition_];
3869 CGSize navsize = [UINavigationBar defaultSize];
3870 CGRect navrect = {{0, 0}, navsize};
3872 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
3873 [overlay_ addSubview:navbar_];
3875 [navbar_ setBarStyle:1];
3876 [navbar_ setDelegate:self];
3878 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
3879 [navbar_ pushNavigationItem:navitem];
3881 CGRect bounds = [overlay_ bounds];
3882 CGSize prgsize = [UIProgressBar defaultSize];
3885 (bounds.size.width - prgsize.width) / 2,
3886 bounds.size.height - prgsize.height - 20
3889 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3890 [progress_ setStyle:0];
3892 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3894 bounds.size.height - prgsize.height - 50,
3895 bounds.size.width - 20,
3899 [status_ setColor:[UIColor whiteColor]];
3900 [status_ setBackgroundColor:[UIColor clearColor]];
3902 [status_ setCentersHorizontally:YES];
3903 //[status_ setFont:font];
3906 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3908 navrect.size.height + 20,
3909 bounds.size.width - 20,
3910 bounds.size.height - navsize.height - 62 - navrect.size.height
3914 //[output_ setTextFont:@"Courier New"];
3915 [output_ setTextSize:12];
3917 [output_ setTextColor:[UIColor whiteColor]];
3918 [output_ setBackgroundColor:[UIColor clearColor]];
3920 [output_ setMarginTop:0];
3921 [output_ setAllowsRubberBanding:YES];
3922 [output_ setEditable:NO];
3924 [overlay_ addSubview:output_];
3926 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3928 bounds.size.height - prgsize.height - 50,
3929 bounds.size.width - 20,
3933 [close_ setAutosizesToFit:NO];
3934 [close_ setDrawsShadow:YES];
3935 [close_ setStretchBackground:YES];
3936 [close_ setEnabled:YES];
3938 UIFont *bold = [UIFont boldSystemFontOfSize:22];
3939 [close_ setTitleFont:bold];
3941 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
3942 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
3943 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
3947 - (void) setContentView:(UIView *)view {
3948 view_ = [view retain];
3951 - (void) resetView {
3952 [transition_ transition:6 toView:view_];
3955 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3956 NSString *context([sheet context]);
3958 if ([context isEqualToString:@"error"])
3960 else if ([context isEqualToString:@"conffile"]) {
3961 FILE *input = [database_ input];
3965 fprintf(input, "N\n");
3969 fprintf(input, "Y\n");
3980 - (void) closeButtonPushed {
3989 [delegate_ suspendWithAnimation:YES];
3993 system("launchctl stop com.apple.SpringBoard");
3997 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4006 - (void) _retachThread {
4007 UINavigationItem *item = [navbar_ topItem];
4008 [item setTitle:CYLocalize("COMPLETE")];
4010 [overlay_ addSubview:close_];
4011 [progress_ removeFromSuperview];
4012 [status_ removeFromSuperview];
4014 [delegate_ progressViewIsComplete:self];
4017 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4018 MMap mmap(file, MMap::ReadOnly);
4020 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4021 if (!(sandplate_ == sha1.Result()))
4026 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4027 MMap mmap(file, MMap::ReadOnly);
4029 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4030 if (!(notifyconf_ == sha1.Result()))
4035 FileFd file(SpringBoard_, FileFd::ReadOnly);
4036 MMap mmap(file, MMap::ReadOnly);
4038 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4039 if (!(springlist_ == sha1.Result()))
4044 case 0: [close_ setTitle:CYLocalize("RETURN_TO_CYDIA")]; break;
4045 case 1: [close_ setTitle:CYLocalize("CLOSE_CYDIA")]; break;
4046 case 2: [close_ setTitle:CYLocalize("RESTART_SPRINGBOARD")]; break;
4047 case 3: [close_ setTitle:CYLocalize("RELOAD_SPRINGBOARD")]; break;
4048 case 4: [close_ setTitle:CYLocalize("REBOOT_DEVICE")]; break;
4051 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4053 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
4054 [cache autorelease];
4056 NSFileManager *manager = [NSFileManager defaultManager];
4057 NSError *error = nil;
4059 id system = [cache objectForKey:@"System"];
4064 if (stat(Cache_, &info) == -1)
4067 [system removeAllObjects];
4069 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4070 for (NSString *app in apps)
4071 if ([app hasSuffix:@".app"]) {
4072 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4073 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4074 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4076 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4077 [info setObject:path forKey:@"Path"];
4078 [info setObject:@"System" forKey:@"ApplicationType"];
4079 [system addInfoDictionary:info];
4085 [cache writeToFile:@Cache_ atomically:YES];
4087 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
4089 if (chmod(Cache_, info.st_mode) == -1)
4093 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4096 notify_post("com.apple.mobile.application_installed");
4098 [delegate_ setStatusBarShowsProgress:NO];
4101 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4102 [[data target] performSelector:[data selector] withObject:[data object]];
4105 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4108 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4109 UINavigationItem *item = [navbar_ topItem];
4110 [item setTitle:title];
4112 [status_ setText:nil];
4113 [output_ setText:@""];
4114 [progress_ setProgress:0];
4116 [close_ removeFromSuperview];
4117 [overlay_ addSubview:progress_];
4118 [overlay_ addSubview:status_];
4120 [delegate_ setStatusBarShowsProgress:YES];
4124 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4125 MMap mmap(file, MMap::ReadOnly);
4127 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4128 sandplate_ = sha1.Result();
4132 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4133 MMap mmap(file, MMap::ReadOnly);
4135 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4136 notifyconf_ = sha1.Result();
4140 FileFd file(SpringBoard_, FileFd::ReadOnly);
4141 MMap mmap(file, MMap::ReadOnly);
4143 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4144 springlist_ = sha1.Result();
4147 [transition_ transition:6 toView:overlay_];
4150 detachNewThreadSelector:@selector(_detachNewThreadData:)
4152 withObject:[[ProgressData alloc]
4153 initWithSelector:selector
4160 - (void) repairWithSelector:(SEL)selector {
4162 detachNewThreadSelector:selector
4165 title:CYLocalize("REPAIRING")
4169 - (void) setConfigurationData:(NSString *)data {
4171 performSelectorOnMainThread:@selector(_setConfigurationData:)
4177 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4178 Package *package = id == nil ? nil : [database_ packageWithName:id];
4180 UIActionSheet *sheet = [[[UIActionSheet alloc]
4181 initWithTitle:(package == nil ? id : [package name])
4182 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
4183 defaultButtonIndex:0
4188 [sheet setBodyText:error];
4189 [sheet popupAlertAnimated:YES];
4192 - (void) setProgressTitle:(NSString *)title {
4194 performSelectorOnMainThread:@selector(_setProgressTitle:)
4200 - (void) setProgressPercent:(float)percent {
4202 performSelectorOnMainThread:@selector(_setProgressPercent:)
4203 withObject:[NSNumber numberWithFloat:percent]
4208 - (void) startProgress {
4211 - (void) addProgressOutput:(NSString *)output {
4213 performSelectorOnMainThread:@selector(_addProgressOutput:)
4219 - (bool) isCancelling:(size_t)received {
4223 - (void) _setConfigurationData:(NSString *)data {
4224 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4226 _assert(conffile_r(data));
4228 NSString *ofile = conffile_r[1];
4229 //NSString *nfile = conffile_r[2];
4231 UIActionSheet *sheet = [[[UIActionSheet alloc]
4232 initWithTitle:CYLocalize("CONFIGURATION_UPGRADE")
4233 buttons:[NSArray arrayWithObjects:
4234 CYLocalize("KEEP_OLD_COPY"),
4235 CYLocalize("ACCEPT_NEW_COPY"),
4236 // XXX: CYLocalize("SEE_WHAT_CHANGED"),
4238 defaultButtonIndex:0
4243 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", CYLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4244 [sheet popupAlertAnimated:YES];
4247 - (void) _setProgressTitle:(NSString *)title {
4248 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4249 for (size_t i(0), e([words count]); i != e; ++i) {
4250 NSString *word([words objectAtIndex:i]);
4251 if (Package *package = [database_ packageWithName:word])
4252 [words replaceObjectAtIndex:i withObject:[package name]];
4255 [status_ setText:[words componentsJoinedByString:@" "]];
4258 - (void) _setProgressPercent:(NSNumber *)percent {
4259 [progress_ setProgress:[percent floatValue]];
4262 - (void) _addProgressOutput:(NSString *)output {
4263 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4264 CGSize size = [output_ contentSize];
4265 CGRect rect = {{0, size.height}, {size.width, 0}};
4266 [output_ scrollRectToVisible:rect animated:YES];
4269 - (BOOL) isRunning {
4276 /* Package Cell {{{ */
4277 @interface PackageCell : UITableCell {
4280 NSString *description_;
4287 UITextLabel *status_;
4291 - (PackageCell *) init;
4292 - (void) setPackage:(Package *)package;
4294 + (int) heightForPackage:(Package *)package;
4298 @implementation PackageCell
4300 - (void) clearPackage {
4311 if (description_ != nil) {
4312 [description_ release];
4316 if (source_ != nil) {
4321 if (badge_ != nil) {
4331 [self clearPackage];
4338 - (PackageCell *) init {
4339 if ((self = [super init]) != nil) {
4341 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4342 [status_ setBackgroundColor:[UIColor clearColor]];
4343 [status_ setFont:small];
4348 - (void) setPackage:(Package *)package {
4349 [self clearPackage];
4352 Source *source = [package source];
4354 icon_ = [[package icon] retain];
4355 name_ = [[package name] retain];
4356 description_ = [[package shortDescription] retain];
4357 commercial_ = [package isCommercial];
4359 package_ = [package retain];
4361 NSString *label = nil;
4362 bool trusted = false;
4364 if (source != nil) {
4365 label = [source label];
4366 trusted = [source trusted];
4367 } else if ([[package id] isEqualToString:@"firmware"])
4368 label = CYLocalize("APPLE");
4370 label = [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("UNKNOWN"), CYLocalize("LOCAL")];
4372 NSString *from(label);
4374 NSString *section = [package simpleSection];
4375 if (section != nil && ![section isEqualToString:label]) {
4376 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4377 from = [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), from, section];
4380 from = [NSString stringWithFormat:CYLocalize("FROM"), from];
4381 source_ = [from retain];
4383 if (NSString *purpose = [package primaryPurpose])
4384 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4385 badge_ = [badge_ retain];
4388 if (NSString *mode = [package mode]) {
4389 [badge_ setImage:[UIImage applicationImageNamed:
4390 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4393 [status_ setText:[NSString stringWithFormat:CYLocalize("QUEUED_FOR"), CYLocalize(mode)]];
4394 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4395 } else if ([package half]) {
4396 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4397 [status_ setText:CYLocalize("PACKAGE_DAMAGED")];
4398 [status_ setColor:[UIColor redColor]];
4400 [badge_ setImage:nil];
4401 [status_ setText:nil];
4408 - (void) drawRect:(CGRect)rect {
4412 if (NSString *mode = [package_ mode]) {
4413 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4414 color = remove ? RemovingColor_ : InstallingColor_;
4416 color = [UIColor whiteColor];
4418 [self setBackgroundColor:color];
4422 [super drawRect:rect];
4425 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4427 CGContextRef context(UIGraphicsGetCurrentContext());
4428 [[self backgroundColor] set];
4430 back.size.height -= 1;
4431 CGContextFillRect(context, back);
4434 [super drawBackgroundInRect:rect withFade:fade];
4437 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4440 rect.size = [icon_ size];
4442 rect.size.width /= 2;
4443 rect.size.height /= 2;
4445 rect.origin.x = 25 - rect.size.width / 2;
4446 rect.origin.y = 25 - rect.size.height / 2;
4448 [icon_ drawInRect:rect];
4451 if (badge_ != nil) {
4452 CGSize size = [badge_ size];
4454 [badge_ drawAtPoint:CGPointMake(
4455 36 - size.width / 2,
4456 36 - size.height / 2
4464 UISetColor(commercial_ ? Purple_ : Black_);
4465 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4466 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4469 UISetColor(commercial_ ? Purplish_ : Gray_);
4470 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4472 [super drawContentInRect:rect selected:selected];
4475 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4477 [super setSelected:selected withFade:fade];
4480 + (int) heightForPackage:(Package *)package {
4486 /* Section Cell {{{ */
4487 @interface SectionCell : UISimpleTableCell {
4492 _UISwitchSlider *switch_;
4497 - (void) setSection:(Section *)section editing:(BOOL)editing;
4501 @implementation SectionCell
4503 - (void) clearSection {
4504 if (section_ != nil) {
4514 if (count_ != nil) {
4521 [self clearSection];
4528 if ((self = [super init]) != nil) {
4529 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4531 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4532 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4536 - (void) onSwitch:(id)sender {
4537 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4538 if (metadata == nil) {
4539 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4540 [Sections_ setObject:metadata forKey:section_];
4544 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4547 - (void) setSection:(Section *)section editing:(BOOL)editing {
4548 if (editing != editing_) {
4550 [switch_ removeFromSuperview];
4552 [self addSubview:switch_];
4556 [self clearSection];
4558 if (section == nil) {
4559 name_ = [CYLocalize("ALL_PACKAGES") retain];
4562 section_ = [section localized];
4563 if (section_ != nil)
4564 section_ = [section_ retain];
4565 name_ = [(section_ == nil ? CYLocalize("NO_SECTION") : section_) retain];
4566 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4569 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4573 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4574 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4581 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4583 CGSize size = [count_ sizeWithFont:Font14_];
4587 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4589 [super drawContentInRect:rect selected:selected];
4595 /* File Table {{{ */
4596 @interface FileTable : RVPage {
4597 _transient Database *database_;
4600 NSMutableArray *files_;
4604 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4605 - (void) setPackage:(Package *)package;
4609 @implementation FileTable
4612 if (package_ != nil)
4621 - (int) numberOfRowsInTable:(UITable *)table {
4622 return files_ == nil ? 0 : [files_ count];
4625 - (float) table:(UITable *)table heightForRow:(int)row {
4629 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4630 if (reusing == nil) {
4631 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4632 UIFont *font = [UIFont systemFontOfSize:16];
4633 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4635 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4639 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4643 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4644 if ((self = [super initWithBook:book]) != nil) {
4645 database_ = database;
4647 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4649 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4650 [self addSubview:list_];
4652 UITableColumn *column = [[[UITableColumn alloc]
4653 initWithTitle:CYLocalize("NAME")
4655 width:[self frame].size.width
4658 [list_ setDataSource:self];
4659 [list_ setSeparatorStyle:1];
4660 [list_ addTableColumn:column];
4661 [list_ setDelegate:self];
4662 [list_ setReusesTableCells:YES];
4666 - (void) setPackage:(Package *)package {
4667 if (package_ != nil) {
4668 [package_ autorelease];
4677 [files_ removeAllObjects];
4679 if (package != nil) {
4680 package_ = [package retain];
4681 name_ = [[package id] retain];
4683 if (NSArray *files = [package files])
4684 [files_ addObjectsFromArray:files];
4686 if ([files_ count] != 0) {
4687 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4688 [files_ removeObjectAtIndex:0];
4689 [files_ sortUsingSelector:@selector(compareByPath:)];
4691 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4692 [stack addObject:@"/"];
4694 for (int i(0), e([files_ count]); i != e; ++i) {
4695 NSString *file = [files_ objectAtIndex:i];
4696 while (![file hasPrefix:[stack lastObject]])
4697 [stack removeLastObject];
4698 NSString *directory = [stack lastObject];
4699 [stack addObject:[file stringByAppendingString:@"/"]];
4700 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4701 ([stack count] - 2) * 3, "",
4702 [file substringFromIndex:[directory length]]
4711 - (void) resetViewAnimated:(BOOL)animated {
4712 [list_ resetViewAnimated:animated];
4715 - (void) reloadData {
4716 [self setPackage:[database_ packageWithName:name_]];
4717 [self reloadButtons];
4720 - (NSString *) title {
4721 return CYLocalize("INSTALLED_FILES");
4724 - (NSString *) backButtonTitle {
4725 return CYLocalize("FILES");
4730 /* Package View {{{ */
4731 @interface PackageView : BrowserView {
4732 _transient Database *database_;
4736 NSMutableArray *buttons_;
4739 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4740 - (void) setPackage:(Package *)package;
4744 @implementation PackageView
4747 if (package_ != nil)
4756 if ([self retainCount] == 1)
4757 [delegate_ setPackageView:self];
4761 /* XXX: this is not safe at all... localization of /fail/ */
4762 - (void) _clickButtonWithName:(NSString *)name {
4763 if ([name isEqualToString:CYLocalize("CLEAR")])
4764 [delegate_ clearPackage:package_];
4765 else if ([name isEqualToString:CYLocalize("INSTALL")])
4766 [delegate_ installPackage:package_];
4767 else if ([name isEqualToString:CYLocalize("REINSTALL")])
4768 [delegate_ installPackage:package_];
4769 else if ([name isEqualToString:CYLocalize("REMOVE")])
4770 [delegate_ removePackage:package_];
4771 else if ([name isEqualToString:CYLocalize("UPGRADE")])
4772 [delegate_ installPackage:package_];
4773 else _assert(false);
4776 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4777 NSString *context([sheet context]);
4779 if ([context isEqualToString:@"modify"]) {
4780 int count = [buttons_ count];
4781 _assert(count != 0);
4782 _assert(button <= count + 1);
4784 if (count != button - 1)
4785 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
4789 [super alertSheet:sheet buttonClicked:button];
4792 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
4793 return [super webView:sender didFinishLoadForFrame:frame];
4796 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4797 [super webView:sender didClearWindowObject:window forFrame:frame];
4798 [window setValue:package_ forKey:@"package"];
4801 - (bool) _allowJavaScriptPanel {
4806 - (void) __rightButtonClicked {
4807 int count = [buttons_ count];
4808 _assert(count != 0);
4811 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
4813 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
4814 [buttons addObjectsFromArray:buttons_];
4815 [buttons addObject:CYLocalize("CANCEL")];
4817 [delegate_ slideUp:[[[UIActionSheet alloc]
4820 defaultButtonIndex:([buttons count] - 1)
4827 - (void) _rightButtonClicked {
4829 [super _rightButtonClicked];
4831 [self __rightButtonClicked];
4835 - (id) _rightButtonTitle {
4836 int count = [buttons_ count];
4837 return count == 0 ? nil : count != 1 ? CYLocalize("MODIFY") : [buttons_ objectAtIndex:0];
4840 - (NSString *) backButtonTitle {
4844 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4845 if ((self = [super initWithBook:book]) != nil) {
4846 database_ = database;
4847 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
4848 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
4852 - (void) setPackage:(Package *)package {
4853 if (package_ != nil) {
4854 [package_ autorelease];
4863 [buttons_ removeAllObjects];
4865 if (package != nil) {
4868 package_ = [package retain];
4869 name_ = [[package id] retain];
4870 commercial_ = [package isCommercial];
4872 if ([package_ mode] != nil)
4873 [buttons_ addObject:CYLocalize("CLEAR")];
4874 if ([package_ source] == nil);
4875 else if ([package_ upgradableAndEssential:NO])
4876 [buttons_ addObject:CYLocalize("UPGRADE")];
4877 else if ([package_ installed] == nil)
4878 [buttons_ addObject:CYLocalize("INSTALL")];
4880 [buttons_ addObject:CYLocalize("REINSTALL")];
4881 if ([package_ installed] != nil)
4882 [buttons_ addObject:CYLocalize("REMOVE")];
4884 if (special_ != NULL) {
4885 CGRect frame([webview_ frame]);
4886 frame.size.width = 320;
4887 frame.size.height = 0;
4888 [webview_ setFrame:frame];
4890 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
4893 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
4895 [self setButtonTitle:nil withStyle:nil toFunction:nil];
4897 [self setFinishHook:nil];
4898 [self setPopupHook:nil];
4901 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
4902 [super callFunction:special_];
4906 [self reloadButtons];
4909 - (bool) isLoading {
4910 return commercial_ ? [super isLoading] : false;
4913 - (void) reloadData {
4914 [self setPackage:[database_ packageWithName:name_]];
4919 /* Package Table {{{ */
4920 @interface PackageTable : RVPage {
4921 _transient Database *database_;
4923 NSMutableArray *packages_;
4924 NSMutableArray *sections_;
4925 UISectionList *list_;
4928 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
4930 - (void) setDelegate:(id)delegate;
4932 - (void) reloadData;
4933 - (void) resetCursor;
4935 - (UISectionList *) list;
4937 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
4941 @implementation PackageTable
4944 [list_ setDataSource:nil];
4947 [packages_ release];
4948 [sections_ release];
4953 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
4954 return [sections_ count];
4957 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
4958 return [[sections_ objectAtIndex:section] name];
4961 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
4962 return [[sections_ objectAtIndex:section] row];
4965 - (int) numberOfRowsInTable:(UITable *)table {
4966 return [packages_ count];
4969 - (float) table:(UITable *)table heightForRow:(int)row {
4970 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
4973 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4975 reusing = [[[PackageCell alloc] init] autorelease];
4976 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
4980 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
4984 - (void) tableRowSelected:(NSNotification *)notification {
4985 int row = [[notification object] selectedRow];
4989 Package *package = [packages_ objectAtIndex:row];
4990 package = [database_ packageWithName:[package id]];
4991 PackageView *view([delegate_ packageView]);
4992 [view setPackage:package];
4993 [view setDelegate:delegate_];
4994 [book_ pushPage:view];
4997 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
4998 if ((self = [super initWithBook:book]) != nil) {
4999 database_ = database;
5000 title_ = [title retain];
5002 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5003 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5005 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
5006 [list_ setDataSource:self];
5008 UITableColumn *column = [[[UITableColumn alloc]
5009 initWithTitle:CYLocalize("NAME")
5011 width:[self frame].size.width
5014 UITable *table = [list_ table];
5015 [table setSeparatorStyle:1];
5016 [table addTableColumn:column];
5017 [table setDelegate:self];
5018 [table setReusesTableCells:YES];
5020 [self addSubview:list_];
5022 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5023 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5027 - (void) setDelegate:(id)delegate {
5028 delegate_ = delegate;
5031 - (bool) hasPackage:(Package *)package {
5035 - (void) reloadData {
5036 NSArray *packages = [database_ packages];
5038 [packages_ removeAllObjects];
5039 [sections_ removeAllObjects];
5041 _profile(PackageTable$reloadData$Filter)
5042 for (Package *package in packages)
5043 if ([self hasPackage:package])
5044 [packages_ addObject:package];
5047 Section *section = nil;
5049 _profile(PackageTable$reloadData$Section)
5050 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5054 _profile(PackageTable$reloadData$Section$Package)
5055 package = [packages_ objectAtIndex:offset];
5056 index = [package index];
5059 if (section == nil || [section index] != index) {
5060 _profile(PackageTable$reloadData$Section$Allocate)
5061 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5064 _profile(PackageTable$reloadData$Section$Add)
5065 [sections_ addObject:section];
5069 [section addToCount];
5073 _profile(PackageTable$reloadData$List)
5078 - (NSString *) title {
5082 - (void) resetViewAnimated:(BOOL)animated {
5083 [list_ resetViewAnimated:animated];
5086 - (void) resetCursor {
5087 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
5090 - (UISectionList *) list {
5094 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5095 [list_ setShouldHideHeaderInShortLists:hide];
5100 /* Filtered Package Table {{{ */
5101 @interface FilteredPackageTable : PackageTable {
5107 - (void) setObject:(id)object;
5109 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5113 @implementation FilteredPackageTable
5121 - (void) setObject:(id)object {
5127 object_ = [object retain];
5130 - (bool) hasPackage:(Package *)package {
5131 _profile(FilteredPackageTable$hasPackage)
5132 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5136 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5137 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5139 object_ = object == nil ? nil : [object retain];
5141 /* XXX: this is an unsafe optimization of doomy hell */
5142 Method method = class_getInstanceMethod([Package class], filter);
5143 _assert(method != NULL);
5144 imp_ = method_getImplementation(method);
5145 _assert(imp_ != NULL);
5154 /* Add Source View {{{ */
5155 @interface AddSourceView : RVPage {
5156 _transient Database *database_;
5159 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5163 @implementation AddSourceView
5165 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5166 if ((self = [super initWithBook:book]) != nil) {
5167 database_ = database;
5173 /* Source Cell {{{ */
5174 @interface SourceCell : UITableCell {
5177 NSString *description_;
5183 - (SourceCell *) initWithSource:(Source *)source;
5187 @implementation SourceCell
5192 [description_ release];
5197 - (SourceCell *) initWithSource:(Source *)source {
5198 if ((self = [super init]) != nil) {
5200 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5202 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5203 icon_ = [icon_ retain];
5205 origin_ = [[source name] retain];
5206 label_ = [[source uri] retain];
5207 description_ = [[source description] retain];
5211 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5213 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5220 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5224 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5228 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5230 [super drawContentInRect:rect selected:selected];
5235 /* Source Table {{{ */
5236 @interface SourceTable : RVPage {
5237 _transient Database *database_;
5238 UISectionList *list_;
5239 NSMutableArray *sources_;
5240 UIActionSheet *alert_;
5244 UIProgressHUD *hud_;
5247 //NSURLConnection *installer_;
5248 NSURLConnection *trivial_bz2_;
5249 NSURLConnection *trivial_gz_;
5250 //NSURLConnection *automatic_;
5255 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5259 @implementation SourceTable
5261 - (void) _deallocConnection:(NSURLConnection *)connection {
5262 if (connection != nil) {
5263 [connection cancel];
5264 //[connection setDelegate:nil];
5265 [connection release];
5270 [[list_ table] setDelegate:nil];
5271 [list_ setDataSource:nil];
5280 //[self _deallocConnection:installer_];
5281 [self _deallocConnection:trivial_gz_];
5282 [self _deallocConnection:trivial_bz2_];
5283 //[self _deallocConnection:automatic_];
5290 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5291 return offset_ == 0 ? 1 : 2;
5294 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5295 switch (section + (offset_ == 0 ? 1 : 0)) {
5296 case 0: return CYLocalize("ENTERED_BY_USER");
5297 case 1: return CYLocalize("INSTALLED_BY_PACKAGE");
5305 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5306 switch (section + (offset_ == 0 ? 1 : 0)) {
5308 case 1: return offset_;
5316 - (int) numberOfRowsInTable:(UITable *)table {
5317 return [sources_ count];
5320 - (float) table:(UITable *)table heightForRow:(int)row {
5321 Source *source = [sources_ objectAtIndex:row];
5322 return [source description] == nil ? 56 : 73;
5325 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5326 Source *source = [sources_ objectAtIndex:row];
5327 // XXX: weird warning, stupid selectors ;P
5328 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5331 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5335 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5339 - (void) tableRowSelected:(NSNotification*)notification {
5340 UITable *table([list_ table]);
5341 int row([table selectedRow]);
5345 Source *source = [sources_ objectAtIndex:row];
5347 PackageTable *packages = [[[FilteredPackageTable alloc]
5350 title:[source label]
5351 filter:@selector(isVisibleInSource:)
5355 [packages setDelegate:delegate_];
5357 [book_ pushPage:packages];
5360 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5361 Source *source = [sources_ objectAtIndex:row];
5362 return [source record] != nil;
5365 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5366 [[list_ table] setDeleteConfirmationRow:row];
5369 - (void) table:(UITable *)table deleteRow:(int)row {
5370 Source *source = [sources_ objectAtIndex:row];
5371 [Sources_ removeObjectForKey:[source key]];
5372 [delegate_ syncData];
5376 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5379 @"./", @"Distribution",
5380 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5382 [delegate_ syncData];
5385 - (NSString *) getWarning {
5386 NSString *href(href_);
5387 NSRange colon([href rangeOfString:@"://"]);
5388 if (colon.location != NSNotFound)
5389 href = [href substringFromIndex:(colon.location + 3)];
5390 href = [href stringByAddingPercentEscapes];
5391 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5392 href = [href stringByCachingURLWithCurrentCDN];
5394 NSURL *url([NSURL URLWithString:href]);
5396 NSStringEncoding encoding;
5397 NSError *error(nil);
5399 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5400 return [warning length] == 0 ? nil : warning;
5404 - (void) _endConnection:(NSURLConnection *)connection {
5405 NSURLConnection **field = NULL;
5406 if (connection == trivial_bz2_)
5407 field = &trivial_bz2_;
5408 else if (connection == trivial_gz_)
5409 field = &trivial_gz_;
5410 _assert(field != NULL);
5411 [connection release];
5415 trivial_bz2_ == nil &&
5421 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5424 UIActionSheet *sheet = [[[UIActionSheet alloc]
5425 initWithTitle:CYLocalize("SOURCE_WARNING")
5426 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_ANYWAY"), CYLocalize("CANCEL"), nil]
5427 defaultButtonIndex:0
5432 [sheet setNumberOfRows:1];
5434 [sheet setBodyText:warning];
5435 [sheet popupAlertAnimated:YES];
5438 } else if (error_ != nil) {
5439 UIActionSheet *sheet = [[[UIActionSheet alloc]
5440 initWithTitle:CYLocalize("VERIFICATION_ERROR")
5441 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5442 defaultButtonIndex:0
5447 [sheet setBodyText:[error_ localizedDescription]];
5448 [sheet popupAlertAnimated:YES];
5450 UIActionSheet *sheet = [[[UIActionSheet alloc]
5451 initWithTitle:CYLocalize("NOT_REPOSITORY")
5452 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5453 defaultButtonIndex:0
5458 [sheet setBodyText:CYLocalize("NOT_REPOSITORY_EX")];
5459 [sheet popupAlertAnimated:YES];
5462 [delegate_ setStatusBarShowsProgress:NO];
5463 [delegate_ removeProgressHUD:hud_];
5473 if (error_ != nil) {
5480 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5481 switch ([response statusCode]) {
5487 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5488 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5490 error_ = [error retain];
5491 [self _endConnection:connection];
5494 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5495 [self _endConnection:connection];
5498 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5499 NSMutableURLRequest *request = [NSMutableURLRequest
5500 requestWithURL:[NSURL URLWithString:href]
5501 cachePolicy:NSURLRequestUseProtocolCachePolicy
5502 timeoutInterval:20.0
5505 [request setHTTPMethod:method];
5507 if (Machine_ != NULL)
5508 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5509 if (UniqueID_ != nil)
5510 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5513 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5515 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5518 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5519 NSString *context([sheet context]);
5521 if ([context isEqualToString:@"source"]) {
5524 NSString *href = [[sheet textField] text];
5526 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5528 if (![href hasSuffix:@"/"])
5529 href_ = [href stringByAppendingString:@"/"];
5532 href_ = [href_ retain];
5534 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5535 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5536 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5540 hud_ = [[delegate_ addProgressHUD] retain];
5541 [hud_ setText:CYLocalize("VERIFYING_URL")];
5552 } else if ([context isEqualToString:@"trivial"])
5554 else if ([context isEqualToString:@"urlerror"])
5556 else if ([context isEqualToString:@"warning"]) {
5576 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5577 if ((self = [super initWithBook:book]) != nil) {
5578 database_ = database;
5579 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5581 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5582 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5583 [list_ setShouldHideHeaderInShortLists:NO];
5585 [self addSubview:list_];
5586 [list_ setDataSource:self];
5588 UITableColumn *column = [[UITableColumn alloc]
5589 initWithTitle:CYLocalize("NAME")
5591 width:[self frame].size.width
5594 UITable *table = [list_ table];
5595 [table setSeparatorStyle:1];
5596 [table addTableColumn:column];
5597 [table setDelegate:self];
5601 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5602 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5606 - (void) reloadData {
5608 _assert(list.ReadMainList());
5610 [sources_ removeAllObjects];
5611 [sources_ addObjectsFromArray:[database_ sources]];
5613 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5616 int count = [sources_ count];
5617 for (offset_ = 0; offset_ != count; ++offset_) {
5618 Source *source = [sources_ objectAtIndex:offset_];
5619 if ([source record] == nil)
5626 - (void) resetViewAnimated:(BOOL)animated {
5627 [list_ resetViewAnimated:animated];
5630 - (void) _leftButtonClicked {
5631 /*[book_ pushPage:[[[AddSourceView alloc]
5636 UIActionSheet *sheet = [[[UIActionSheet alloc]
5637 initWithTitle:CYLocalize("ENTER_APT_URL")
5638 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_SOURCE"), CYLocalize("CANCEL"), nil]
5639 defaultButtonIndex:0
5644 [sheet setNumberOfRows:1];
5646 [sheet addTextFieldWithValue:@"http://" label:@""];
5648 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5649 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5650 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5651 [traits setKeyboardType:UIKeyboardTypeURL];
5652 // XXX: UIReturnKeyDone
5653 [traits setReturnKeyType:UIReturnKeyNext];
5655 [sheet popupAlertAnimated:YES];
5658 - (void) _rightButtonClicked {
5659 UITable *table = [list_ table];
5660 BOOL editing = [table isRowDeletionEnabled];
5661 [table enableRowDeletion:!editing animated:YES];
5662 [book_ reloadButtonsForPage:self];
5665 - (NSString *) title {
5666 return CYLocalize("SOURCES");
5669 - (NSString *) leftButtonTitle {
5670 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("ADD") : nil;
5673 - (id) rightButtonTitle {
5674 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("DONE") : CYLocalize("EDIT");
5677 - (UINavigationButtonStyle) rightButtonStyle {
5678 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5684 /* Installed View {{{ */
5685 @interface InstalledView : RVPage {
5686 _transient Database *database_;
5687 FilteredPackageTable *packages_;
5691 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5695 @implementation InstalledView
5698 [packages_ release];
5702 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5703 if ((self = [super initWithBook:book]) != nil) {
5704 database_ = database;
5706 packages_ = [[FilteredPackageTable alloc]
5710 filter:@selector(isInstalledAndVisible:)
5711 with:[NSNumber numberWithBool:YES]
5714 [self addSubview:packages_];
5716 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5717 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5721 - (void) resetViewAnimated:(BOOL)animated {
5722 [packages_ resetViewAnimated:animated];
5725 - (void) reloadData {
5726 [packages_ reloadData];
5729 - (void) _rightButtonClicked {
5730 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5731 [packages_ reloadData];
5733 [book_ reloadButtonsForPage:self];
5736 - (NSString *) title {
5737 return CYLocalize("INSTALLED");
5740 - (NSString *) backButtonTitle {
5741 return CYLocalize("PACKAGES");
5744 - (id) rightButtonTitle {
5745 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? CYLocalize("EXPERT") : CYLocalize("SIMPLE");
5748 - (UINavigationButtonStyle) rightButtonStyle {
5749 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5752 - (void) setDelegate:(id)delegate {
5753 [super setDelegate:delegate];
5754 [packages_ setDelegate:delegate];
5761 @interface HomeView : BrowserView {
5766 @implementation HomeView
5768 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5769 NSString *context([sheet context]);
5771 if ([context isEqualToString:@"about"])
5774 [super alertSheet:sheet buttonClicked:button];
5777 - (void) _leftButtonClicked {
5778 UIActionSheet *sheet = [[[UIActionSheet alloc]
5779 initWithTitle:CYLocalize("ABOUT_CYDIA")
5780 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
5781 defaultButtonIndex:0
5787 @"Copyright (C) 2008-2009\n"
5788 "Jay Freeman (saurik)\n"
5789 "saurik@saurik.com\n"
5790 "http://www.saurik.com/\n"
5793 "http://www.theokorigroup.com/\n"
5795 "College of Creative Studies,\n"
5796 "University of California,\n"
5798 "http://www.ccs.ucsb.edu/"
5801 [sheet popupAlertAnimated:YES];
5804 - (NSString *) leftButtonTitle {
5805 return CYLocalize("ABOUT");
5810 /* Manage View {{{ */
5811 @interface ManageView : BrowserView {
5816 @implementation ManageView
5818 - (NSString *) title {
5819 return CYLocalize("MANAGE");
5822 - (void) _leftButtonClicked {
5823 [delegate_ askForSettings];
5826 - (NSString *) leftButtonTitle {
5827 return CYLocalize("SETTINGS");
5831 - (id) _rightButtonTitle {
5832 return Queuing_ ? CYLocalize("QUEUE") : nil;
5835 - (UINavigationButtonStyle) rightButtonStyle {
5836 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5839 - (void) _rightButtonClicked {
5844 - (bool) isLoading {
5851 #include <BrowserView.m>
5853 /* Cydia Book {{{ */
5854 @interface CYBook : RVBook <
5857 _transient Database *database_;
5858 UINavigationBar *overlay_;
5859 UINavigationBar *underlay_;
5860 UIProgressIndicator *indicator_;
5861 UITextLabel *prompt_;
5862 UIProgressBar *progress_;
5863 UINavigationButton *cancel_;
5867 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
5873 @implementation CYBook
5877 [indicator_ release];
5879 [progress_ release];
5884 - (NSString *) getTitleForPage:(RVPage *)page {
5885 return [super getTitleForPage:page];
5893 [UIView beginAnimations:nil context:NULL];
5895 CGRect ovrframe = [overlay_ frame];
5896 ovrframe.origin.y = 0;
5897 [overlay_ setFrame:ovrframe];
5899 CGRect barframe = [navbar_ frame];
5900 barframe.origin.y += ovrframe.size.height;
5901 [navbar_ setFrame:barframe];
5903 CGRect trnframe = [transition_ frame];
5904 trnframe.origin.y += ovrframe.size.height;
5905 trnframe.size.height -= ovrframe.size.height;
5906 [transition_ setFrame:trnframe];
5908 [UIView endAnimations];
5910 [indicator_ startAnimation];
5911 [prompt_ setText:CYLocalize("UPDATING_DATABASE")];
5912 [progress_ setProgress:0];
5915 [overlay_ addSubview:cancel_];
5918 detachNewThreadSelector:@selector(_update)
5927 [indicator_ stopAnimation];
5929 [UIView beginAnimations:nil context:NULL];
5931 CGRect ovrframe = [overlay_ frame];
5932 ovrframe.origin.y = -ovrframe.size.height;
5933 [overlay_ setFrame:ovrframe];
5935 CGRect barframe = [navbar_ frame];
5936 barframe.origin.y -= ovrframe.size.height;
5937 [navbar_ setFrame:barframe];
5939 CGRect trnframe = [transition_ frame];
5940 trnframe.origin.y -= ovrframe.size.height;
5941 trnframe.size.height += ovrframe.size.height;
5942 [transition_ setFrame:trnframe];
5944 [UIView commitAnimations];
5946 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
5949 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
5950 if ((self = [super initWithFrame:frame]) != nil) {
5951 database_ = database;
5953 CGRect ovrrect = [navbar_ bounds];
5954 ovrrect.size.height = [UINavigationBar defaultSize].height;
5955 ovrrect.origin.y = -ovrrect.size.height;
5957 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5958 [self addSubview:overlay_];
5960 ovrrect.origin.y = frame.size.height;
5961 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5962 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
5963 [self addSubview:underlay_];
5965 [overlay_ setBarStyle:1];
5966 [underlay_ setBarStyle:1];
5968 int barstyle = [overlay_ _barStyle:NO];
5969 bool ugly = barstyle == 0;
5971 UIProgressIndicatorStyle style = ugly ?
5972 UIProgressIndicatorStyleMediumBrown :
5973 UIProgressIndicatorStyleMediumWhite;
5975 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
5976 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
5977 CGRect indrect = {{indoffset, indoffset}, indsize};
5979 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
5980 [indicator_ setStyle:style];
5981 [overlay_ addSubview:indicator_];
5983 CGSize prmsize = {215, indsize.height + 4};
5986 indoffset * 2 + indsize.width,
5990 unsigned(ovrrect.size.height - prmsize.height) / 2
5993 UIFont *font = [UIFont systemFontOfSize:15];
5995 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
5997 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
5998 [prompt_ setBackgroundColor:[UIColor clearColor]];
5999 [prompt_ setFont:font];
6001 [overlay_ addSubview:prompt_];
6003 CGSize prgsize = {75, 100};
6006 ovrrect.size.width - prgsize.width - 10,
6007 (ovrrect.size.height - prgsize.height) / 2
6010 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6011 [progress_ setStyle:0];
6012 [overlay_ addSubview:progress_];
6014 cancel_ = [[UINavigationButton alloc] initWithTitle:CYLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6015 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6017 CGRect frame = [cancel_ frame];
6018 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6019 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6020 [cancel_ setFrame:frame];
6022 [cancel_ setBarStyle:barstyle];
6026 - (void) _onCancel {
6028 [cancel_ removeFromSuperview];
6031 - (void) _update { _pooled
6033 status.setDelegate(self);
6035 [database_ updateWithStatus:status];
6038 performSelectorOnMainThread:@selector(_update_)
6044 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
6045 [prompt_ setText:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), error]];
6048 - (void) setProgressTitle:(NSString *)title {
6050 performSelectorOnMainThread:@selector(_setProgressTitle:)
6056 - (void) setProgressPercent:(float)percent {
6058 performSelectorOnMainThread:@selector(_setProgressPercent:)
6059 withObject:[NSNumber numberWithFloat:percent]
6064 - (void) startProgress {
6067 - (void) addProgressOutput:(NSString *)output {
6069 performSelectorOnMainThread:@selector(_addProgressOutput:)
6075 - (bool) isCancelling:(size_t)received {
6079 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6083 - (void) _setProgressTitle:(NSString *)title {
6084 [prompt_ setText:title];
6087 - (void) _setProgressPercent:(NSNumber *)percent {
6088 [progress_ setProgress:[percent floatValue]];
6091 - (void) _addProgressOutput:(NSString *)output {
6096 /* Cydia:// Protocol {{{ */
6097 @interface CydiaURLProtocol : NSURLProtocol {
6102 @implementation CydiaURLProtocol
6104 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6105 NSURL *url([request URL]);
6108 NSString *scheme([[url scheme] lowercaseString]);
6109 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6114 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6118 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6119 id<NSURLProtocolClient> client([self client]);
6121 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6123 NSData *data(UIImagePNGRepresentation(icon));
6125 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6126 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6127 [client URLProtocol:self didLoadData:data];
6128 [client URLProtocolDidFinishLoading:self];
6132 - (void) startLoading {
6133 id<NSURLProtocolClient> client([self client]);
6134 NSURLRequest *request([self request]);
6136 NSURL *url([request URL]);
6137 NSString *href([url absoluteString]);
6139 NSString *path([href substringFromIndex:8]);
6140 NSRange slash([path rangeOfString:@"/"]);
6143 if (slash.location == NSNotFound) {
6147 command = [path substringToIndex:slash.location];
6148 path = [path substringFromIndex:(slash.location + 1)];
6151 Database *database([Database sharedInstance]);
6153 if ([command isEqualToString:@"package-icon"]) {
6156 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6157 Package *package([database packageWithName:path]);
6160 UIImage *icon([package icon]);
6161 [self _returnPNGWithImage:icon forRequest:request];
6162 } else if ([command isEqualToString:@"source-icon"]) {
6165 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6166 NSString *source(Simplify(path));
6167 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6169 icon = [UIImage applicationImageNamed:@"unknown.png"];
6170 [self _returnPNGWithImage:icon forRequest:request];
6171 } else if ([command isEqualToString:@"uikit-image"]) {
6174 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6175 UIImage *icon(_UIImageWithName(path));
6176 [self _returnPNGWithImage:icon forRequest:request];
6177 } else if ([command isEqualToString:@"section-icon"]) {
6180 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6181 NSString *section(Simplify(path));
6182 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6184 icon = [UIImage applicationImageNamed:@"unknown.png"];
6185 [self _returnPNGWithImage:icon forRequest:request];
6187 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6191 - (void) stopLoading {
6197 /* Sections View {{{ */
6198 @interface SectionsView : RVPage {
6199 _transient Database *database_;
6200 NSMutableArray *sections_;
6201 NSMutableArray *filtered_;
6202 UITransitionView *transition_;
6208 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6209 - (void) reloadData;
6214 @implementation SectionsView
6217 [list_ setDataSource:nil];
6218 [list_ setDelegate:nil];
6220 [sections_ release];
6221 [filtered_ release];
6222 [transition_ release];
6224 [accessory_ release];
6228 - (int) numberOfRowsInTable:(UITable *)table {
6229 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6232 - (float) table:(UITable *)table heightForRow:(int)row {
6236 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6238 reusing = [[[SectionCell alloc] init] autorelease];
6239 [(SectionCell *)reusing setSection:(editing_ ?
6240 [sections_ objectAtIndex:row] :
6241 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6242 ) editing:editing_];
6246 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6250 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6254 - (void) tableRowSelected:(NSNotification *)notification {
6255 int row = [[notification object] selectedRow];
6266 title = CYLocalize("ALL_PACKAGES");
6268 section = [filtered_ objectAtIndex:(row - 1)];
6269 name = [section name];
6272 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6275 title = CYLocalize("NO_SECTION");
6279 PackageTable *table = [[[FilteredPackageTable alloc]
6283 filter:@selector(isVisiblyUninstalledInSection:)
6287 [table setDelegate:delegate_];
6289 [book_ pushPage:table];
6292 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6293 if ((self = [super initWithBook:book]) != nil) {
6294 database_ = database;
6296 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6297 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6299 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6300 [self addSubview:transition_];
6302 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6303 [transition_ transition:0 toView:list_];
6305 UITableColumn *column = [[[UITableColumn alloc]
6306 initWithTitle:CYLocalize("NAME")
6308 width:[self frame].size.width
6311 [list_ setDataSource:self];
6312 [list_ setSeparatorStyle:1];
6313 [list_ addTableColumn:column];
6314 [list_ setDelegate:self];
6315 [list_ setReusesTableCells:YES];
6319 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6320 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6324 - (void) reloadData {
6325 NSArray *packages = [database_ packages];
6327 [sections_ removeAllObjects];
6328 [filtered_ removeAllObjects];
6331 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6332 SectionMap sections;
6333 sections.resize(64);
6335 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6339 for (Package *package in packages) {
6340 NSString *name([package section]);
6341 NSString *key(name == nil ? @"" : name);
6346 _profile(SectionsView$reloadData$Section)
6347 section = §ions[key];
6348 if (*section == nil) {
6349 _profile(SectionsView$reloadData$Section$Allocate)
6350 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6355 [*section addToCount];
6357 _profile(SectionsView$reloadData$Filter)
6358 if (![package valid] || [package installed] != nil || ![package visible])
6362 [*section addToRow];
6366 _profile(SectionsView$reloadData$Section)
6367 section = [sections objectForKey:key];
6368 if (section == nil) {
6369 _profile(SectionsView$reloadData$Section$Allocate)
6370 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6371 [sections setObject:section forKey:key];
6376 [section addToCount];
6378 _profile(SectionsView$reloadData$Filter)
6379 if (![package valid] || [package installed] != nil || ![package visible])
6389 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6390 [sections_ addObject:i->second];
6392 [sections_ addObjectsFromArray:[sections allValues]];
6395 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6397 for (Section *section in sections_) {
6398 size_t count([section row]);
6402 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6403 [section setCount:count];
6404 [filtered_ addObject:section];
6411 - (void) resetView {
6413 [self _rightButtonClicked];
6416 - (void) resetViewAnimated:(BOOL)animated {
6417 [list_ resetViewAnimated:animated];
6420 - (void) _rightButtonClicked {
6421 if ((editing_ = !editing_))
6424 [delegate_ updateData];
6425 [book_ reloadTitleForPage:self];
6426 [book_ reloadButtonsForPage:self];
6429 - (NSString *) title {
6430 return editing_ ? CYLocalize("SECTION_VISIBILITY") : CYLocalize("INSTALL_BY_SECTION");
6433 - (NSString *) backButtonTitle {
6434 return CYLocalize("SECTIONS");
6437 - (id) rightButtonTitle {
6438 return [sections_ count] == 0 ? nil : editing_ ? CYLocalize("DONE") : CYLocalize("EDIT");
6441 - (UINavigationButtonStyle) rightButtonStyle {
6442 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6445 - (UIView *) accessoryView {
6451 /* Changes View {{{ */
6452 @interface ChangesView : RVPage {
6453 _transient Database *database_;
6454 NSMutableArray *packages_;
6455 NSMutableArray *sections_;
6456 UISectionList *list_;
6460 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6461 - (void) reloadData;
6465 @implementation ChangesView
6468 [[list_ table] setDelegate:nil];
6469 [list_ setDataSource:nil];
6471 [packages_ release];
6472 [sections_ release];
6477 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6478 return [sections_ count];
6481 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6482 return [[sections_ objectAtIndex:section] name];
6485 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6486 return [[sections_ objectAtIndex:section] row];
6489 - (int) numberOfRowsInTable:(UITable *)table {
6490 return [packages_ count];
6493 - (float) table:(UITable *)table heightForRow:(int)row {
6494 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6497 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6499 reusing = [[[PackageCell alloc] init] autorelease];
6500 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6504 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6508 - (void) tableRowSelected:(NSNotification *)notification {
6509 int row = [[notification object] selectedRow];
6512 Package *package = [packages_ objectAtIndex:row];
6513 PackageView *view([delegate_ packageView]);
6514 [view setDelegate:delegate_];
6515 [view setPackage:package];
6516 [book_ pushPage:view];
6519 - (void) _leftButtonClicked {
6520 [(CYBook *)book_ update];
6521 [self reloadButtons];
6524 - (void) _rightButtonClicked {
6525 [delegate_ distUpgrade];
6528 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6529 if ((self = [super initWithBook:book]) != nil) {
6530 database_ = database;
6532 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6533 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6535 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6536 [self addSubview:list_];
6538 [list_ setShouldHideHeaderInShortLists:NO];
6539 [list_ setDataSource:self];
6540 //[list_ setSectionListStyle:1];
6542 UITableColumn *column = [[[UITableColumn alloc]
6543 initWithTitle:CYLocalize("NAME")
6545 width:[self frame].size.width
6548 UITable *table = [list_ table];
6549 [table setSeparatorStyle:1];
6550 [table addTableColumn:column];
6551 [table setDelegate:self];
6552 [table setReusesTableCells:YES];
6556 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6557 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6561 - (void) reloadData {
6562 NSArray *packages = [database_ packages];
6564 [packages_ removeAllObjects];
6565 [sections_ removeAllObjects];
6568 for (Package *package in packages)
6570 [package installed] == nil && [package valid] && [package visible] ||
6571 [package upgradableAndEssential:YES]
6573 [packages_ addObject:package];
6576 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6579 Section *upgradable = [[[Section alloc] initWithName:CYLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6580 Section *ignored = [[[Section alloc] initWithName:CYLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6581 Section *section = nil;
6585 bool unseens = false;
6587 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6589 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6590 Package *package = [packages_ objectAtIndex:offset];
6592 BOOL uae = [package upgradableAndEssential:YES];
6598 _profile(ChangesView$reloadData$Remember)
6599 seen = [package seen];
6602 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6607 name = CYLocalize("UNKNOWN");
6609 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6613 _profile(ChangesView$reloadData$Allocate)
6614 name = [NSString stringWithFormat:CYLocalize("NEW_AT"), name];
6615 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6616 [sections_ addObject:section];
6620 [section addToCount];
6621 } else if ([package ignored])
6622 [ignored addToCount];
6625 [upgradable addToCount];
6630 CFRelease(formatter);
6633 Section *last = [sections_ lastObject];
6634 size_t count = [last count];
6635 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6636 [sections_ removeLastObject];
6639 if ([ignored count] != 0)
6640 [sections_ insertObject:ignored atIndex:0];
6642 [sections_ insertObject:upgradable atIndex:0];
6645 [self reloadButtons];
6648 - (void) resetViewAnimated:(BOOL)animated {
6649 [list_ resetViewAnimated:animated];
6652 - (NSString *) leftButtonTitle {
6653 return [(CYBook *)book_ updating] ? nil : CYLocalize("REFRESH");
6656 - (id) rightButtonTitle {
6657 return upgrades_ == 0 ? nil : [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6660 - (NSString *) title {
6661 return CYLocalize("CHANGES");
6666 /* Search View {{{ */
6667 @protocol SearchViewDelegate
6668 - (void) showKeyboard:(BOOL)show;
6671 @interface SearchView : RVPage {
6673 UISearchField *field_;
6674 UITransitionView *transition_;
6675 FilteredPackageTable *table_;
6676 UIPreferencesTable *advanced_;
6682 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6683 - (void) reloadData;
6687 @implementation SearchView
6690 [field_ setDelegate:nil];
6692 [accessory_ release];
6694 [transition_ release];
6696 [advanced_ release];
6701 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6705 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6707 case 0: return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("ADVANCED_SEARCH"), CYLocalize("COMING_SOON")];
6709 default: _assert(false);
6713 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6717 default: _assert(false);
6721 - (void) _showKeyboard:(BOOL)show {
6722 CGSize keysize = [UIKeyboard defaultSize];
6723 CGRect keydown = [book_ pageBounds];
6724 CGRect keyup = keydown;
6725 keyup.size.height -= keysize.height - ButtonBarHeight_;
6727 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6729 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6730 [animation setSignificantRectFields:8];
6733 [animation setStartFrame:keydown];
6734 [animation setEndFrame:keyup];
6736 [animation setStartFrame:keyup];
6737 [animation setEndFrame:keydown];
6740 UIAnimator *animator = [UIAnimator sharedAnimator];
6743 addAnimations:[NSArray arrayWithObjects:animation, nil]
6744 withDuration:(KeyboardTime_ - delay)
6749 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6751 [delegate_ showKeyboard:show];
6754 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6755 [self _showKeyboard:YES];
6758 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
6759 [self _showKeyboard:NO];
6762 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
6764 NSString *text([field_ text]);
6765 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6771 - (void) textFieldClearButtonPressed:(UITextField *)field {
6775 - (void) keyboardInputShouldDelete:(id)input {
6779 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
6780 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6784 [field_ resignFirstResponder];
6789 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6790 if ((self = [super initWithBook:book]) != nil) {
6791 CGRect pageBounds = [book_ pageBounds];
6793 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6794 [self addSubview:transition_];
6796 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6798 [advanced_ setReusesTableCells:YES];
6799 [advanced_ setDataSource:self];
6800 [advanced_ reloadData];
6802 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6803 CGColor dimmed(space_, 0, 0, 0, 0.5);
6804 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
6806 table_ = [[FilteredPackageTable alloc]
6810 filter:@selector(isUnfilteredAndSearchedForBy:)
6814 [table_ setShouldHideHeaderInShortLists:NO];
6815 [transition_ transition:0 toView:table_];
6824 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
6831 [self bounds].size.width - area.origin.x - 18;
6833 area.size.height = [UISearchField defaultHeight];
6835 field_ = [[UISearchField alloc] initWithFrame:area];
6837 UIFont *font = [UIFont systemFontOfSize:16];
6838 [field_ setFont:font];
6840 [field_ setPlaceholder:CYLocalize("SEARCH_EX")];
6841 [field_ setDelegate:self];
6843 [field_ setPaddingTop:5];
6845 UITextInputTraits *traits([field_ textInputTraits]);
6846 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6847 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6848 [traits setReturnKeyType:UIReturnKeySearch];
6850 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
6852 accessory_ = [[UIView alloc] initWithFrame:accrect];
6853 [accessory_ addSubview:field_];
6855 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
6856 [configure setShowPressFeedback:YES];
6857 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
6858 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
6859 [accessory_ addSubview:configure];*/
6861 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6862 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6868 LKAnimation *animation = [LKTransition animation];
6869 [animation setType:@"oglFlip"];
6870 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
6871 [animation setFillMode:@"extended"];
6872 [animation setTransitionFlags:3];
6873 [animation setDuration:10];
6874 [animation setSpeed:0.35];
6875 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
6876 [[transition_ _layer] addAnimation:animation forKey:0];
6877 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
6878 flipped_ = !flipped_;
6882 - (void) configurePushed {
6883 [field_ resignFirstResponder];
6887 - (void) resetViewAnimated:(BOOL)animated {
6890 [table_ resetViewAnimated:animated];
6893 - (void) _reloadData {
6896 - (void) reloadData {
6899 [table_ setObject:[field_ text]];
6900 _profile(SearchView$reloadData)
6901 [table_ reloadData];
6904 [table_ resetCursor];
6907 - (UIView *) accessoryView {
6911 - (NSString *) title {
6915 - (NSString *) backButtonTitle {
6916 return CYLocalize("SEARCH");
6919 - (void) setDelegate:(id)delegate {
6920 [table_ setDelegate:delegate];
6921 [super setDelegate:delegate];
6927 @interface SettingsView : RVPage {
6928 _transient Database *database_;
6931 UIPreferencesTable *table_;
6932 _UISwitchSlider *subscribedSwitch_;
6933 _UISwitchSlider *ignoredSwitch_;
6934 UIPreferencesControlTableCell *subscribedCell_;
6935 UIPreferencesControlTableCell *ignoredCell_;
6938 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6942 @implementation SettingsView
6945 [table_ setDataSource:nil];
6948 if (package_ != nil)
6951 [subscribedSwitch_ release];
6952 [ignoredSwitch_ release];
6953 [subscribedCell_ release];
6954 [ignoredCell_ release];
6958 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6959 if (package_ == nil)
6965 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6966 if (package_ == nil)
6973 default: _assert(false);
6979 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
6980 if (package_ == nil)
6987 default: _assert(false);
6993 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6994 if (package_ == nil)
7001 default: _assert(false);
7007 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7008 if (package_ == nil)
7011 _UISwitchSlider *slider([cell control]);
7012 BOOL value([slider value] != 0);
7013 NSMutableDictionary *metadata([package_ metadata]);
7016 if (NSNumber *number = [metadata objectForKey:key])
7017 before = [number boolValue];
7021 if (value != before) {
7022 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7024 [delegate_ updateData];
7028 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7029 [self onSomething:cell withKey:@"IsSubscribed"];
7032 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7033 [self onSomething:cell withKey:@"IsIgnored"];
7036 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7037 if (package_ == nil)
7041 case 0: switch (row) {
7043 return subscribedCell_;
7045 return ignoredCell_;
7046 default: _assert(false);
7049 case 1: switch (row) {
7051 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7052 [cell setShowSelection:NO];
7053 [cell setTitle:CYLocalize("SHOW_ALL_CHANGES_EX")];
7057 default: _assert(false);
7060 default: _assert(false);
7066 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7067 if ((self = [super initWithBook:book])) {
7068 database_ = database;
7069 name_ = [package retain];
7071 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7072 [self addSubview:table_];
7074 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7075 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
7077 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7078 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
7080 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7081 [subscribedCell_ setShowSelection:NO];
7082 [subscribedCell_ setTitle:CYLocalize("SHOW_ALL_CHANGES")];
7083 [subscribedCell_ setControl:subscribedSwitch_];
7085 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7086 [ignoredCell_ setShowSelection:NO];
7087 [ignoredCell_ setTitle:CYLocalize("IGNORE_UPGRADES")];
7088 [ignoredCell_ setControl:ignoredSwitch_];
7090 [table_ setDataSource:self];
7095 - (void) resetViewAnimated:(BOOL)animated {
7096 [table_ resetViewAnimated:animated];
7099 - (void) reloadData {
7100 if (package_ != nil)
7101 [package_ autorelease];
7102 package_ = [database_ packageWithName:name_];
7103 if (package_ != nil) {
7105 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7106 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7109 [table_ reloadData];
7112 - (NSString *) title {
7113 return CYLocalize("SETTINGS");
7118 /* Signature View {{{ */
7119 @interface SignatureView : BrowserView {
7120 _transient Database *database_;
7124 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7128 @implementation SignatureView
7135 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7137 [super webView:sender didClearWindowObject:window forFrame:frame];
7140 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7141 if ((self = [super initWithBook:book]) != nil) {
7142 database_ = database;
7143 package_ = [package retain];
7148 - (void) resetViewAnimated:(BOOL)animated {
7151 - (void) reloadData {
7152 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7158 @interface Cydia : UIApplication <
7159 ConfirmationViewDelegate,
7160 ProgressViewDelegate,
7169 UIToolbar *buttonbar_;
7173 NSMutableArray *essential_;
7174 NSMutableArray *broken_;
7176 Database *database_;
7177 ProgressView *progress_;
7181 UIKeyboard *keyboard_;
7182 UIProgressHUD *hud_;
7184 SectionsView *sections_;
7185 ChangesView *changes_;
7186 ManageView *manage_;
7187 SearchView *search_;
7189 PackageView *package_;
7194 @implementation Cydia
7197 if ([broken_ count] != 0) {
7198 int count = [broken_ count];
7200 UIActionSheet *sheet = [[[UIActionSheet alloc]
7201 initWithTitle:(count == 1 ? CYLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:CYLocalize("HALFINSTALLED_PACKAGES"), count])
7202 buttons:[NSArray arrayWithObjects:
7203 CYLocalize("FORCIBLY_CLEAR"),
7204 CYLocalize("TEMPORARY_IGNORE"),
7206 defaultButtonIndex:0
7211 [sheet setBodyText:CYLocalize("HALFINSTALLED_PACKAGE_EX")];
7212 [sheet popupAlertAnimated:YES];
7213 } else if (!Ignored_ && [essential_ count] != 0) {
7214 int count = [essential_ count];
7216 UIActionSheet *sheet = [[[UIActionSheet alloc]
7217 initWithTitle:(count == 1 ? CYLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:CYLocalize("ESSENTIAL_UPGRADES"), count])
7218 buttons:[NSArray arrayWithObjects:
7219 CYLocalize("UPGRADE_ESSENTIAL"),
7220 CYLocalize("COMPLETE_UPGRADE"),
7221 CYLocalize("TEMPORARY_IGNORE"),
7223 defaultButtonIndex:0
7228 [sheet setBodyText:CYLocalize("ESSENTIAL_UPGRADE_EX")];
7229 [sheet popupAlertAnimated:YES];
7233 - (void) _reloadData {
7236 static bool loaded(false);
7237 UIProgressHUD *hud([self addProgressHUD]);
7238 [hud setText:(loaded ? CYLocalize("RELOADING_DATA") : CYLocalize("LOADING_DATA"))];
7241 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7244 [self removeProgressHUD:hud];
7248 [essential_ removeAllObjects];
7249 [broken_ removeAllObjects];
7251 NSArray *packages = [database_ packages];
7252 for (Package *package in packages) {
7254 [broken_ addObject:package];
7255 if ([package upgradableAndEssential:NO]) {
7256 if ([package essential])
7257 [essential_ addObject:package];
7263 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7264 [buttonbar_ setBadgeValue:badge forButton:3];
7265 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7266 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7267 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7268 [self setApplicationBadge:badge];
7270 [self setApplicationBadgeString:badge];
7272 [buttonbar_ setBadgeValue:nil forButton:3];
7273 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7274 [buttonbar_ setBadgeAnimated:NO forButton:3];
7275 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7276 [self removeApplicationBadge];
7277 else // XXX: maybe use setApplicationBadgeString also?
7278 [self setApplicationIconBadgeNumber:0];
7282 [buttonbar_ setBadgeValue:nil forButton:4];
7286 // XXX: what is this line of code for?
7287 if ([packages count] == 0);
7288 else if (Loaded_ || ManualRefresh) loaded:
7293 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7294 NSTimeInterval interval([update timeIntervalSinceNow]);
7295 if (interval <= 0 && interval > -600)
7303 - (void) _saveConfig {
7306 NSString *error(nil);
7307 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7309 NSError *error(nil);
7310 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7311 NSLog(@"failure to save metadata data: %@", error);
7314 NSLog(@"failure to serialize metadata: %@", error);
7322 - (void) updateData {
7325 /* XXX: this is just stupid */
7326 if (tag_ != 2 && sections_ != nil)
7327 [sections_ reloadData];
7328 if (tag_ != 3 && changes_ != nil)
7329 [changes_ reloadData];
7330 if (tag_ != 5 && search_ != nil)
7331 [search_ reloadData];
7341 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7342 _assert(file != NULL);
7344 NSArray *keys = [Sources_ allKeys];
7346 for (NSString *key in keys) {
7347 NSDictionary *source = [Sources_ objectForKey:key];
7349 fprintf(file, "%s %s %s\n",
7350 [[source objectForKey:@"Type"] UTF8String],
7351 [[source objectForKey:@"URI"] UTF8String],
7352 [[source objectForKey:@"Distribution"] UTF8String]
7361 detachNewThreadSelector:@selector(update_)
7364 title:CYLocalize("UPDATING_SOURCES")
7368 - (void) reloadData {
7369 @synchronized (self) {
7370 if (confirm_ == nil)
7376 pkgProblemResolver *resolver = [database_ resolver];
7378 resolver->InstallProtect();
7379 if (!resolver->Resolve(true))
7383 - (void) popUpBook:(RVBook *)book {
7384 [underlay_ popSubview:book];
7387 - (CGRect) popUpBounds {
7388 return [underlay_ bounds];
7392 [database_ prepare];
7394 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7395 [confirm_ setDelegate:self];
7397 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7398 [page setDelegate:self];
7400 [confirm_ setPage:page];
7401 [self popUpBook:confirm_];
7405 @synchronized (self) {
7410 - (void) clearPackage:(Package *)package {
7411 @synchronized (self) {
7418 - (void) installPackage:(Package *)package {
7419 @synchronized (self) {
7426 - (void) removePackage:(Package *)package {
7427 @synchronized (self) {
7434 - (void) distUpgrade {
7435 @synchronized (self) {
7436 [database_ upgrade];
7442 [self slideUp:[[[UIActionSheet alloc]
7444 buttons:[NSArray arrayWithObjects:CYLocalize("CONTINUE_QUEUING"), CYLocalize("CANCEL_CLEAR"), nil]
7445 defaultButtonIndex:1
7452 @synchronized (self) {
7455 if (confirm_ != nil) {
7463 [overlay_ removeFromSuperview];
7467 detachNewThreadSelector:@selector(perform)
7470 title:CYLocalize("RUNNING")
7474 - (void) bootstrap_ {
7476 [database_ upgrade];
7477 [database_ prepare];
7478 [database_ perform];
7481 /* XXX: replace and localize */
7482 - (void) bootstrap {
7484 detachNewThreadSelector:@selector(bootstrap_)
7487 title:@"Bootstrap Install"
7491 - (void) progressViewIsComplete:(ProgressView *)progress {
7492 if (confirm_ != nil) {
7493 [underlay_ addSubview:overlay_];
7494 [confirm_ popFromSuperviewAnimated:NO];
7500 - (void) setPage:(RVPage *)page {
7501 [page resetViewAnimated:NO];
7502 [page setDelegate:self];
7503 [book_ setPage:page];
7506 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7507 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7508 [browser loadURL:url];
7512 - (void) _setHomePage {
7513 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7516 - (SectionsView *) sectionsView {
7517 if (sections_ == nil)
7518 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7522 - (void) buttonBarItemTapped:(id)sender {
7523 unsigned tag = [sender tag];
7525 [book_ resetViewAnimated:YES];
7527 } else if (tag_ == 2 && tag != 2)
7528 [[self sectionsView] resetView];
7531 case 1: [self _setHomePage]; break;
7533 case 2: [self setPage:[self sectionsView]]; break;
7534 case 3: [self setPage:changes_]; break;
7535 case 4: [self setPage:manage_]; break;
7536 case 5: [self setPage:search_]; break;
7538 default: _assert(false);
7544 - (void) applicationWillSuspend {
7546 [super applicationWillSuspend];
7549 - (void) askForSettings {
7550 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
7552 UIActionSheet *role = [[[UIActionSheet alloc]
7553 initWithTitle:CYLocalize("WHO_ARE_YOU")
7554 buttons:[NSArray arrayWithObjects:
7555 [NSString stringWithFormat:parenthetical, CYLocalize("USER"), CYLocalize("USER_EX")],
7556 [NSString stringWithFormat:parenthetical, CYLocalize("HACKER"), CYLocalize("HACKER_EX")],
7557 [NSString stringWithFormat:parenthetical, CYLocalize("DEVELOPER"), CYLocalize("DEVELOPER_EX")],
7559 defaultButtonIndex:-1
7564 [role setBodyText:CYLocalize("ROLE_EX")];
7565 [role popupAlertAnimated:YES];
7568 - (void) setPackageView:(PackageView *)view {
7569 if (package_ == nil)
7570 package_ = [view retain];
7573 - (PackageView *) packageView {
7576 if (package_ == nil)
7577 view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7580 view = [package_ autorelease];
7589 [self setStatusBarShowsProgress:NO];
7590 [self removeProgressHUD:hud_];
7595 pid_t pid = ExecFork();
7597 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7598 perror("launchctl stop");
7605 [self askForSettings];
7610 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7612 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7613 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7614 0, 0, screenrect.size.width, screenrect.size.height - 48
7615 ) database:database_];
7617 [book_ setDelegate:self];
7619 [overlay_ addSubview:book_];
7621 NSArray *buttonitems = [NSArray arrayWithObjects:
7622 [NSDictionary dictionaryWithObjectsAndKeys:
7623 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7624 @"home-up.png", kUIButtonBarButtonInfo,
7625 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7626 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7627 self, kUIButtonBarButtonTarget,
7628 @"Cydia", kUIButtonBarButtonTitle,
7629 @"0", kUIButtonBarButtonType,
7632 [NSDictionary dictionaryWithObjectsAndKeys:
7633 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7634 @"install-up.png", kUIButtonBarButtonInfo,
7635 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7636 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7637 self, kUIButtonBarButtonTarget,
7638 CYLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7639 @"0", kUIButtonBarButtonType,
7642 [NSDictionary dictionaryWithObjectsAndKeys:
7643 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7644 @"changes-up.png", kUIButtonBarButtonInfo,
7645 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7646 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7647 self, kUIButtonBarButtonTarget,
7648 CYLocalize("CHANGES"), kUIButtonBarButtonTitle,
7649 @"0", kUIButtonBarButtonType,
7652 [NSDictionary dictionaryWithObjectsAndKeys:
7653 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7654 @"manage-up.png", kUIButtonBarButtonInfo,
7655 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7656 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7657 self, kUIButtonBarButtonTarget,
7658 CYLocalize("MANAGE"), kUIButtonBarButtonTitle,
7659 @"0", kUIButtonBarButtonType,
7662 [NSDictionary dictionaryWithObjectsAndKeys:
7663 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7664 @"search-up.png", kUIButtonBarButtonInfo,
7665 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7666 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7667 self, kUIButtonBarButtonTarget,
7668 CYLocalize("SEARCH"), kUIButtonBarButtonTitle,
7669 @"0", kUIButtonBarButtonType,
7673 buttonbar_ = [[UIToolbar alloc]
7675 withFrame:CGRectMake(
7676 0, screenrect.size.height - ButtonBarHeight_,
7677 screenrect.size.width, ButtonBarHeight_
7679 withItemList:buttonitems
7682 [buttonbar_ setDelegate:self];
7683 [buttonbar_ setBarStyle:1];
7684 [buttonbar_ setButtonBarTrackingMode:2];
7686 int buttons[5] = {1, 2, 3, 4, 5};
7687 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7688 [buttonbar_ showButtonGroup:0 withDuration:0];
7690 for (int i = 0; i != 5; ++i)
7691 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7692 i * 64 + 2, 1, 60, ButtonBarHeight_
7695 [buttonbar_ showSelectionForButton:1];
7696 [overlay_ addSubview:buttonbar_];
7698 [UIKeyboard initImplementationNow];
7699 CGSize keysize = [UIKeyboard defaultSize];
7700 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7701 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7702 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
7703 [overlay_ addSubview:keyboard_];
7706 [underlay_ addSubview:overlay_];
7710 [self sectionsView];
7711 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7712 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7714 manage_ = (ManageView *) [[self
7715 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7716 withClass:[ManageView class]
7719 [self setPackageView:[self packageView]];
7726 [self _setHomePage];
7729 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7730 NSString *context([sheet context]);
7732 if ([context isEqualToString:@"missing"])
7734 else if ([context isEqualToString:@"cancel"]) {
7752 @synchronized (self) {
7757 [buttonbar_ setBadgeValue:CYLocalize("Q_D") forButton:4];
7761 if (confirm_ != nil) {
7766 } else if ([context isEqualToString:@"fixhalf"]) {
7769 @synchronized (self) {
7770 for (Package *broken in broken_) {
7773 NSString *id = [broken id];
7774 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7775 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7776 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7777 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7786 [broken_ removeAllObjects];
7795 } else if ([context isEqualToString:@"role"]) {
7797 case 1: Role_ = @"User"; break;
7798 case 2: Role_ = @"Hacker"; break;
7799 case 3: Role_ = @"Developer"; break;
7806 bool reset = Settings_ != nil;
7808 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7812 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7822 } else if ([context isEqualToString:@"upgrade"]) {
7825 @synchronized (self) {
7826 for (Package *essential in essential_)
7827 [essential install];
7850 - (void) reorganize { _pooled
7851 system("/usr/libexec/cydia/free.sh");
7852 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
7855 - (void) applicationSuspend:(__GSEvent *)event {
7856 if (hud_ == nil && ![progress_ isRunning])
7857 [super applicationSuspend:event];
7860 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7862 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7865 - (void) _setSuspended:(BOOL)value {
7867 [super _setSuspended:value];
7870 - (UIProgressHUD *) addProgressHUD {
7871 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
7872 [window_ setUserInteractionEnabled:NO];
7874 [progress_ addSubview:hud];
7878 - (void) removeProgressHUD:(UIProgressHUD *)hud {
7880 [hud removeFromSuperview];
7881 [window_ setUserInteractionEnabled:YES];
7884 - (void) openMailToURL:(NSURL *)url {
7885 // XXX: this makes me sad
7887 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
7889 [UIApp openURL:url];// asPanel:YES];
7893 - (void) clearFirstResponder {
7894 if (id responder = [window_ firstResponder])
7895 [responder resignFirstResponder];
7898 - (RVPage *) pageForPackage:(NSString *)name {
7899 if (Package *package = [database_ packageWithName:name]) {
7900 PackageView *view([self packageView]);
7901 [view setPackage:package];
7904 UIActionSheet *sheet = [[[UIActionSheet alloc]
7905 initWithTitle:CYLocalize("CANNOT_LOCATE_PACKAGE")
7906 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
7907 defaultButtonIndex:0
7912 [sheet setBodyText:[NSString stringWithFormat:CYLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
7914 [sheet popupAlertAnimated:YES];
7919 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
7923 NSString *scheme([[url scheme] lowercaseString]);
7924 if (![scheme isEqualToString:@"cydia"])
7926 NSString *path([url absoluteString]);
7927 if ([path length] < 8)
7929 path = [path substringFromIndex:8];
7930 if (![path hasPrefix:@"/"])
7931 path = [@"/" stringByAppendingString:path];
7933 if ([path isEqualToString:@"/add-source"])
7934 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
7935 else if ([path isEqualToString:@"/storage"])
7936 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[BrowserView class]];
7937 else if ([path isEqualToString:@"/sources"])
7938 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
7939 else if ([path isEqualToString:@"/packages"])
7940 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
7941 else if ([path hasPrefix:@"/url/"])
7942 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[BrowserView class]];
7943 else if ([path hasPrefix:@"/launch/"])
7944 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
7945 else if ([path hasPrefix:@"/package-settings/"])
7946 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
7947 else if ([path hasPrefix:@"/package-signature/"])
7948 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
7949 else if ([path hasPrefix:@"/package/"])
7950 return [self pageForPackage:[path substringFromIndex:9]];
7951 else if ([path hasPrefix:@"/files/"]) {
7952 NSString *name = [path substringFromIndex:7];
7954 if (Package *package = [database_ packageWithName:name]) {
7955 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
7956 [files setPackage:package];
7964 - (void) applicationOpenURL:(NSURL *)url {
7965 [super applicationOpenURL:url];
7967 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
7968 [self setPage:page];
7969 [buttonbar_ showSelectionForButton:tag];
7974 - (void) applicationDidFinishLaunching:(id)unused {
7976 Font12_ = [[UIFont systemFontOfSize:12] retain];
7977 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
7978 Font14_ = [[UIFont systemFontOfSize:14] retain];
7979 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
7980 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
7984 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
7985 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
7987 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
7989 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7990 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
7992 [window_ orderFront:self];
7993 [window_ makeKey:self];
7994 [window_ setHidden:NO];
7996 database_ = [Database sharedInstance];
7997 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
7998 [database_ setDelegate:progress_];
7999 [window_ setContentView:progress_];
8001 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8002 [progress_ setContentView:underlay_];
8004 [progress_ resetView];
8007 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8008 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8009 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8010 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8011 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8012 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
8013 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
8015 [self setIdleTimerDisabled:YES];
8017 hud_ = [[self addProgressHUD] retain];
8018 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8020 [self setStatusBarShowsProgress:YES];
8023 detachNewThreadSelector:@selector(reorganize)
8031 - (void) showKeyboard:(BOOL)show {
8032 CGSize keysize = [UIKeyboard defaultSize];
8033 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8034 CGRect keyup = keydown;
8035 keyup.origin.y -= keysize.height;
8037 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
8038 [animation setSignificantRectFields:2];
8041 [animation setStartFrame:keydown];
8042 [animation setEndFrame:keyup];
8043 [keyboard_ activate];
8045 [animation setStartFrame:keyup];
8046 [animation setEndFrame:keydown];
8047 [keyboard_ deactivate];
8050 [[UIAnimator sharedAnimator]
8051 addAnimations:[NSArray arrayWithObjects:animation, nil]
8052 withDuration:KeyboardTime_
8057 - (void) slideUp:(UIActionSheet *)alert {
8059 [alert presentSheetFromButtonBar:buttonbar_];
8061 [alert presentSheetInView:overlay_];
8066 void AddPreferences(NSString *plist) { _pooled
8067 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
8068 _assert(settings != NULL);
8069 NSMutableArray *items = [settings objectForKey:@"items"];
8073 for (NSMutableDictionary *item in items) {
8074 NSString *label = [item objectForKey:@"label"];
8075 if (label != nil && [label isEqualToString:@"Cydia"]) {
8082 for (size_t i(0); i != [items count]; ++i) {
8083 NSDictionary *item([items objectAtIndex:i]);
8084 NSString *label = [item objectForKey:@"label"];
8085 if (label != nil && [label isEqualToString:@"General"]) {
8086 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
8087 @"CydiaSettings", @"bundle",
8088 @"PSLinkCell", @"cell",
8089 [NSNumber numberWithBool:YES], @"hasIcon",
8090 [NSNumber numberWithBool:YES], @"isController",
8092 nil] atIndex:(i + 1)];
8098 _assert([settings writeToFile:plist atomically:YES] == YES);
8103 id Alloc_(id self, SEL selector) {
8104 id object = alloc_(self, selector);
8105 lprintf("[%s]A-%p\n", self->isa->name, object);
8110 id Dealloc_(id self, SEL selector) {
8111 id object = dealloc_(self, selector);
8112 lprintf("[%s]D-%p\n", self->isa->name, object);
8116 Class $WebDefaultUIKitDelegate;
8118 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
8120 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
8121 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8122 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8123 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
8126 int main(int argc, char *argv[]) { _pooled
8129 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8131 /* Library Hacks {{{ */
8132 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8134 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8135 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8136 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8137 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8138 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8141 /* Set Locale {{{ */
8142 Locale_ = CFLocaleCopyCurrent();
8143 Languages_ = [NSLocale preferredLanguages];
8144 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8145 //NSLog(@"%@", [Languages_ description]);
8147 if (Languages_ == nil || [Languages_ count] == 0)
8150 lang = [[Languages_ objectAtIndex:0] UTF8String];
8151 setenv("LANG", lang, true);
8152 //std::setlocale(LC_ALL, lang);
8153 NSLog(@"Setting Language: %s", lang);
8156 // XXX: apr_app_initialize?
8159 /* Parse Arguments {{{ */
8160 bool substrate(false);
8166 for (int argi(1); argi != argc; ++argi)
8167 if (strcmp(argv[argi], "--") == 0) {
8169 argv[argi] = argv[0];
8175 for (int argi(1); argi != arge; ++argi)
8176 if (strcmp(args[argi], "--bootstrap") == 0)
8178 else if (strcmp(args[argi], "--substrate") == 0)
8181 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8186 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
8187 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
8188 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
8189 Sounds_Keyboard_ = [keyboard boolValue];
8192 App_ = [[NSBundle mainBundle] bundlePath];
8193 Home_ = NSHomeDirectory();
8198 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8199 alloc_ = alloc->method_imp;
8200 alloc->method_imp = (IMP) &Alloc_;*/
8202 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8203 dealloc_ = dealloc->method_imp;
8204 dealloc->method_imp = (IMP) &Dealloc_;*/
8209 size = sizeof(maxproc);
8210 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8211 perror("sysctlbyname(\"kern.maxproc\", ?)");
8212 else if (maxproc < 64) {
8214 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8215 perror("sysctlbyname(\"kern.maxproc\", #)");
8218 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8219 char *machine = new char[size];
8220 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8221 perror("sysctlbyname(\"hw.machine\", ?)");
8225 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8227 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8228 Build_ = [system objectForKey:@"ProductBuildVersion"];
8229 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8230 Product_ = [info objectForKey:@"SafariProductVersion"];
8231 Safari_ = [info objectForKey:@"CFBundleVersion"];
8234 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8235 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
8237 /* Load Database {{{ */
8239 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8241 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8244 if (Metadata_ == NULL)
8245 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8247 Settings_ = [Metadata_ objectForKey:@"Settings"];
8249 Packages_ = [Metadata_ objectForKey:@"Packages"];
8250 Sections_ = [Metadata_ objectForKey:@"Sections"];
8251 Sources_ = [Metadata_ objectForKey:@"Sources"];
8254 if (Settings_ != nil)
8255 Role_ = [Settings_ objectForKey:@"Role"];
8257 if (Packages_ == nil) {
8258 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8259 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8262 if (Sections_ == nil) {
8263 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8264 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8267 if (Sources_ == nil) {
8268 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8269 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8274 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8277 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8278 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8279 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8280 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8282 if (access("/User", F_OK) != 0) {
8284 system("/usr/libexec/cydia/firmware.sh");
8288 _assert([[NSFileManager defaultManager]
8289 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8290 withIntermediateDirectories:YES
8295 if (access("/tmp/cydia.chk", F_OK) == 0) {
8296 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8297 _assert(errno == ENOENT);
8298 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8299 _assert(errno == ENOENT);
8302 _assert(pkgInitConfig(*_config));
8303 _assert(pkgInitSystem(*_config, _system));
8306 _config->Set("APT::Acquire::Translation", lang);
8307 _config->Set("Acquire::http::Timeout", 15);
8308 _config->Set("Acquire::http::MaxParallel", 4);
8310 /* Color Choices {{{ */
8311 space_ = CGColorSpaceCreateDeviceRGB();
8313 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8314 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8315 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8316 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8317 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8318 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8319 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8320 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8321 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8322 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8323 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8324 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8325 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8326 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8327 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8330 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8331 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8334 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8336 /* UIKit Configuration {{{ */
8337 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8338 if ($GSFontSetUseLegacyFontMetrics != NULL)
8339 $GSFontSetUseLegacyFontMetrics(YES);
8341 UIKeyboardDisableAutomaticAppearance();
8345 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8347 CGColorSpaceRelease(space_);