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>
90 #include <apt-pkg/tagfile.h>
92 #include <apr-1/apr_pools.h>
94 #include <sys/types.h>
96 #include <sys/sysctl.h>
97 #include <sys/param.h>
98 #include <sys/mount.h>
104 #include <mach-o/nlist.h>
114 #include <ext/hash_map>
116 #import "BrowserView.h"
117 #import "ResetView.h"
119 #import "substrate.h"
122 //#define _finline __attribute__((force_inline))
123 #define _finline inline
128 #define _limit(count) do { \
129 static size_t _count(0); \
130 if (++_count == count) \
135 #define _timestamp ({ \
137 gettimeofday(&tv, NULL); \
138 tv.tv_sec * 1000000 + tv.tv_usec; \
141 typedef std::vector<class ProfileTime *> TimeList;
151 ProfileTime(const char *name) :
155 times_.push_back(this);
158 void AddTime(uint64_t time) {
165 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
177 ProfileTimer(ProfileTime &time) :
184 time_.AddTime(_timestamp - start_);
189 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
191 std::cerr << "========" << std::endl;
194 #define _profile(name) { \
195 static ProfileTime name(#name); \
196 ProfileTimer _ ## name(name);
200 /* Objective-C Handle<> {{{ */
201 template <typename Type_>
203 typedef _H<Type_> This_;
208 _finline void Retain_() {
213 _finline void Clear_() {
219 _finline _H(Type_ *value = NULL, bool mended = false) :
230 _finline operator Type_ *() const {
234 _finline This_ &operator =(Type_ *value) {
235 if (value_ != value) {
246 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
248 void NSLogPoint(const char *fix, const CGPoint &point) {
249 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
252 void NSLogRect(const char *fix, const CGRect &rect) {
253 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
256 @interface NSObject (Cydia)
257 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
258 - (id) yieldToSelector:(SEL)selector;
261 @implementation NSObject (Cydia)
266 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
267 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
268 id object([[context objectAtIndex:1] nonretainedObjectValue]);
269 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
271 /* XXX: deal with exceptions */
272 id value([self performSelector:selector withObject:object]);
274 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
275 [context removeAllObjects];
276 if ([signature methodReturnLength] != 0 && value != nil)
277 [context addObject:value];
282 performSelectorOnMainThread:@selector(doNothing)
288 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
289 /*return [self performSelector:selector withObject:object];*/
291 volatile bool stopped(false);
293 NSMutableArray *context([NSMutableArray arrayWithObjects:
294 [NSValue valueWithPointer:selector],
295 [NSValue valueWithNonretainedObject:object],
296 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
299 NSThread *thread([[[NSThread alloc]
301 selector:@selector(_yieldToContext:)
307 NSRunLoop *loop([NSRunLoop currentRunLoop]);
308 NSDate *future([NSDate distantFuture]);
310 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
312 return [context count] == 0 ? nil : [context objectAtIndex:0];
315 - (id) yieldToSelector:(SEL)selector {
316 return [self yieldToSelector:selector withObject:nil];
321 /* NSForcedOrderingSearch doesn't work on the iPhone */
322 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
323 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
324 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
326 /* iPhoneOS 2.0 Compatibility {{{ */
328 @interface UITextView (iPhoneOS)
329 - (void) setTextSize:(float)size;
332 @implementation UITextView (iPhoneOS)
334 - (void) setTextSize:(float)size {
335 [self setFont:[[self font] fontWithSize:size]];
342 extern NSString * const kCAFilterNearest;
344 /* Information Dictionaries {{{ */
345 @interface NSMutableArray (Cydia)
346 - (void) addInfoDictionary:(NSDictionary *)info;
349 @implementation NSMutableArray (Cydia)
351 - (void) addInfoDictionary:(NSDictionary *)info {
352 [self addObject:info];
357 @interface NSMutableDictionary (Cydia)
358 - (void) addInfoDictionary:(NSDictionary *)info;
361 @implementation NSMutableDictionary (Cydia)
363 - (void) addInfoDictionary:(NSDictionary *)info {
364 NSString *bundle = [info objectForKey:@"CFBundleIdentifier"];
365 [self setObject:info forKey:bundle];
370 /* Pop Transitions {{{ */
371 @interface PopTransitionView : UITransitionView {
376 @implementation PopTransitionView
378 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
379 if (from != nil && to == nil)
380 [self removeFromSuperview];
385 @implementation UIView (PopUpView)
387 - (void) popFromSuperviewAnimated:(BOOL)animated {
388 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
391 - (void) popSubview:(UIView *)view {
392 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
393 [transition setDelegate:transition];
394 [self addSubview:transition];
396 UIView *blank = [[[UIView alloc] initWithFrame:[transition bounds]] autorelease];
397 [transition transition:UITransitionNone toView:blank];
398 [transition transition:UITransitionPushFromBottom toView:view];
404 #define lprintf(args...) fprintf(stderr, args)
407 #define TraceLogging (1 && !ForRelease)
408 #define HistogramInsertionSort (0 && !ForRelease)
409 #define ProfileTimes (0 && !ForRelease)
410 #define ForSaurik (0 && !ForRelease)
411 #define LogBrowser (1 && !ForRelease)
412 #define TrackResize (0 && !ForRelease)
413 #define ManualRefresh (1 && !ForRelease)
414 #define ShowInternals (0 && !ForRelease)
415 #define IgnoreInstall (0 && !ForRelease)
416 #define RecycleWebViews 0
417 #define AlwaysReload (1 && !ForRelease)
421 #define _trace(args...)
426 #define _profile(name) {
429 #define PrintTimes() do {} while (false)
433 typedef uint32_t (*SKRadixFunction)(id, void *);
435 @interface NSMutableArray (Radix)
436 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
437 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
445 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
446 struct RadixItem_ *lhs(swap), *rhs(swap + count);
448 static const size_t width = 32;
449 static const size_t bits = 11;
450 static const size_t slots = 1 << bits;
451 static const size_t passes = (width + (bits - 1)) / bits;
453 size_t *hist(new size_t[slots]);
455 for (size_t pass(0); pass != passes; ++pass) {
456 memset(hist, 0, sizeof(size_t) * slots);
458 for (size_t i(0); i != count; ++i) {
459 uint32_t key(lhs[i].key);
461 key &= _not(uint32_t) >> width - bits;
466 for (size_t i(0); i != slots; ++i) {
467 size_t local(offset);
472 for (size_t i(0); i != count; ++i) {
473 uint32_t key(lhs[i].key);
475 key &= _not(uint32_t) >> width - bits;
476 rhs[hist[key]++] = lhs[i];
479 RadixItem_ *tmp(lhs);
486 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
487 for (size_t i(0); i != count; ++i)
488 [values addObject:[self objectAtIndex:lhs[i].index]];
489 [self setArray:values];
494 @implementation NSMutableArray (Radix)
496 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
497 size_t count([self count]);
502 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
503 [invocation setSelector:selector];
504 [invocation setArgument:&object atIndex:2];
506 /* XXX: this is an unsafe optimization of doomy hell */
507 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
508 _assert(method != NULL);
509 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
510 _assert(imp != NULL);
513 struct RadixItem_ *swap(new RadixItem_[count * 2]);
515 for (size_t i(0); i != count; ++i) {
516 RadixItem_ &item(swap[i]);
519 id object([self objectAtIndex:i]);
522 [invocation setTarget:object];
524 [invocation getReturnValue:&item.key];
526 item.key = imp(object, selector, object);
530 RadixSort_(self, count, swap);
533 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
534 size_t count([self count]);
535 struct RadixItem_ *swap(new RadixItem_[count * 2]);
537 for (size_t i(0); i != count; ++i) {
538 RadixItem_ &item(swap[i]);
541 id object([self objectAtIndex:i]);
542 item.key = function(object, argument);
545 RadixSort_(self, count, swap);
550 /* Insertion Sort {{{ */
552 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
553 const char *ptr = (const char *)list;
555 CFIndex half = count / 2;
556 const char *probe = ptr + elementSize * half;
557 CFComparisonResult cr = comparator(element, probe, context);
558 if (0 == cr) return (probe - (const char *)list) / elementSize;
559 ptr = (cr < 0) ? ptr : probe + elementSize;
560 count = (cr < 0) ? half : (half + (count & 1) - 1);
562 return (ptr - (const char *)list) / elementSize;
565 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
566 const char *ptr = (const char *)list;
568 CFIndex half = count / 2;
569 const char *probe = ptr + elementSize * half;
570 CFComparisonResult cr = comparator(element, probe, context);
571 if (0 == cr) return (probe - (const char *)list) / elementSize;
572 ptr = (cr < 0) ? ptr : probe + elementSize;
573 count = (cr < 0) ? half : (half + (count & 1) - 1);
575 return (ptr - (const char *)list) / elementSize;
578 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
579 if (range.length == 0)
581 const void **values(new const void *[range.length]);
582 CFArrayGetValues(array, range, values);
584 #if HistogramInsertionSort
585 uint32_t total(0), *offsets(new uint32_t[range.length]);
588 for (CFIndex index(1); index != range.length; ++index) {
589 const void *value(values[index]);
590 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
591 CFIndex correct(index);
592 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
595 if (correct != index) {
596 size_t offset(index - correct);
597 #if HistogramInsertionSort
601 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
603 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
604 values[correct] = value;
608 CFArrayReplaceValues(array, range, values, range.length);
611 #if HistogramInsertionSort
612 for (CFIndex index(0); index != range.length; ++index)
613 if (offsets[index] != 0)
614 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
615 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
622 /* Apple Bug Fixes {{{ */
623 @implementation UIWebDocumentView (Cydia)
625 - (void) _setScrollerOffset:(CGPoint)offset {
626 UIScroller *scroller([self _scroller]);
628 CGSize size([scroller contentSize]);
629 CGSize bounds([scroller bounds].size);
632 max.x = size.width - bounds.width;
633 max.y = size.height - bounds.height;
641 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
642 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
644 [scroller setOffset:offset];
651 kUIControlEventMouseDown = 1 << 0,
652 kUIControlEventMouseMovedInside = 1 << 2, // mouse moved inside control target
653 kUIControlEventMouseMovedOutside = 1 << 3, // mouse moved outside control target
654 kUIControlEventMouseUpInside = 1 << 6, // mouse up inside control target
655 kUIControlEventMouseUpOutside = 1 << 7, // mouse up outside control target
656 kUIControlAllEvents = (kUIControlEventMouseDown | kUIControlEventMouseMovedInside | kUIControlEventMouseMovedOutside | kUIControlEventMouseUpInside | kUIControlEventMouseUpOutside)
657 } UIControlEventMasks;
659 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
660 size_t length([self length] - state->state);
663 else if (length > count)
665 for (size_t i(0); i != length; ++i)
666 objects[i] = [self item:state->state++];
667 state->itemsPtr = objects;
668 state->mutationsPtr = (unsigned long *) self;
672 @interface NSString (UIKit)
673 - (NSString *) stringByAddingPercentEscapes;
674 - (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
677 @interface NSString (Cydia)
678 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
679 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
680 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
681 - (NSComparisonResult) compareByPath:(NSString *)other;
682 - (NSString *) stringByCachingURLWithCurrentCDN;
683 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
686 @implementation NSString (Cydia)
688 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
689 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
692 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
693 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
694 memcpy(data, bytes, length);
695 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
698 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
699 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
702 - (NSComparisonResult) compareByPath:(NSString *)other {
703 NSString *prefix = [self commonPrefixWithString:other options:0];
704 size_t length = [prefix length];
706 NSRange lrange = NSMakeRange(length, [self length] - length);
707 NSRange rrange = NSMakeRange(length, [other length] - length);
709 lrange = [self rangeOfString:@"/" options:0 range:lrange];
710 rrange = [other rangeOfString:@"/" options:0 range:rrange];
712 NSComparisonResult value;
714 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
715 value = NSOrderedSame;
716 else if (lrange.location == NSNotFound)
717 value = NSOrderedAscending;
718 else if (rrange.location == NSNotFound)
719 value = NSOrderedDescending;
721 value = NSOrderedSame;
723 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
724 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
725 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
726 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
728 NSComparisonResult result = [lpath compare:rpath];
729 return result == NSOrderedSame ? value : result;
732 - (NSString *) stringByCachingURLWithCurrentCDN {
734 stringByReplacingOccurrencesOfString:@"://"
735 withString:@"://ne.edgecastcdn.net/8003A4/"
737 /* XXX: this is somewhat inaccurate */
738 range:NSMakeRange(0, 10)
742 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
743 return [(id)CFURLCreateStringByAddingPercentEscapes(
748 kCFStringEncodingUTF8
754 static inline NSString *CYLocalizeEx(NSString *key, NSString *value = nil) {
755 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:nil];
758 #define CYLocalize(key) CYLocalizeEx(@ key)
766 _finline void clear_() {
772 _finline bool empty() const {
776 _finline size_t size() const {
780 _finline char *data() const {
784 _finline void clear() {
789 _finline CYString() :
796 _finline ~CYString() {
800 void operator =(const CYString &rhs) {
804 if (rhs.cache_ == nil)
807 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
810 void set(apr_pool_t *pool, const char *data, size_t size) {
816 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
817 memcpy(temp, data, size);
824 _finline void set(apr_pool_t *pool, const char *data) {
825 set(pool, data, data == NULL ? 0 : strlen(data));
828 _finline void set(apr_pool_t *pool, const std::string &rhs) {
829 set(pool, rhs.data(), rhs.size());
832 bool operator ==(const CYString &rhs) const {
833 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
836 operator CFStringRef() {
837 if (cache_ == NULL) {
840 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
844 _finline operator id() {
845 return (NSString *) static_cast<CFStringRef>(*this);
850 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
853 struct NSStringMapHash :
854 std::unary_function<NSString *, size_t>
856 _finline size_t operator ()(NSString *value) const {
857 return CFStringHashNSString((CFStringRef) value);
861 struct NSStringMapLess :
862 std::binary_function<NSString *, NSString *, bool>
864 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
865 return [lhs compare:rhs] == NSOrderedAscending;
869 struct NSStringMapEqual :
870 std::binary_function<NSString *, NSString *, bool>
872 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
873 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
874 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
875 //[lhs isEqualToString:rhs];
879 /* Perl-Compatible RegEx {{{ */
889 Pcre(const char *regex) :
894 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
897 lprintf("%d:%s\n", offset, error);
901 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
902 matches_ = new int[(capture_ + 1) * 3];
910 NSString *operator [](size_t match) {
911 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
914 bool operator ()(NSString *data) {
915 // XXX: length is for characters, not for bytes
916 return operator ()([data UTF8String], [data length]);
919 bool operator ()(const char *data, size_t size) {
921 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
925 /* Mime Addresses {{{ */
926 @interface Address : NSObject {
932 - (NSString *) address;
934 - (void) setAddress:(NSString *)address;
936 + (Address *) addressWithString:(NSString *)string;
937 - (Address *) initWithString:(NSString *)string;
940 @implementation Address
949 - (NSString *) name {
953 - (NSString *) address {
957 - (void) setAddress:(NSString *)address {
959 [address_ autorelease];
963 address_ = [address retain];
966 + (Address *) addressWithString:(NSString *)string {
967 return [[[Address alloc] initWithString:string] autorelease];
970 + (NSArray *) _attributeKeys {
971 return [NSArray arrayWithObjects:@"address", @"name", nil];
974 - (NSArray *) attributeKeys {
975 return [[self class] _attributeKeys];
978 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
979 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
982 - (Address *) initWithString:(NSString *)string {
983 if ((self = [super init]) != nil) {
984 const char *data = [string UTF8String];
985 size_t size = [string length];
987 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
989 if (address_r(data, size)) {
990 name_ = [address_r[1] retain];
991 address_ = [address_r[2] retain];
993 name_ = [string retain];
1001 /* CoreGraphics Primitives {{{ */
1012 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
1015 Set(space, red, green, blue, alpha);
1020 CGColorRelease(color_);
1027 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1029 float color[] = {red, green, blue, alpha};
1030 color_ = CGColorCreate(space, color);
1033 operator CGColorRef() {
1039 extern "C" void UISetColor(CGColorRef color);
1041 /* Random Global Variables {{{ */
1042 static const int PulseInterval_ = 50000;
1043 static const int ButtonBarHeight_ = 48;
1044 static const float KeyboardTime_ = 0.3f;
1046 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1047 #define SandboxTemplate_ "/usr/share/sandbox/SandboxTemplate.sb"
1048 #define NotifyConfig_ "/etc/notify.conf"
1050 static bool Queuing_;
1052 static CGColor Blue_;
1053 static CGColor Blueish_;
1054 static CGColor Black_;
1055 static CGColor Off_;
1056 static CGColor White_;
1057 static CGColor Gray_;
1058 static CGColor Green_;
1059 static CGColor Purple_;
1060 static CGColor Purplish_;
1062 static UIColor *InstallingColor_;
1063 static UIColor *RemovingColor_;
1065 static NSString *App_;
1066 static NSString *Home_;
1067 static BOOL Sounds_Keyboard_;
1069 static BOOL Advanced_;
1070 static BOOL Loaded_;
1071 static BOOL Ignored_;
1073 static UIFont *Font12_;
1074 static UIFont *Font12Bold_;
1075 static UIFont *Font14_;
1076 static UIFont *Font18Bold_;
1077 static UIFont *Font22Bold_;
1079 static const char *Machine_ = NULL;
1080 static const NSString *UniqueID_ = nil;
1081 static const NSString *Build_ = nil;
1082 static const NSString *Product_ = nil;
1083 static const NSString *Safari_ = nil;
1085 CFLocaleRef Locale_;
1086 NSArray *Languages_;
1087 CGColorSpaceRef space_;
1092 static NSDictionary *SectionMap_;
1093 static NSMutableDictionary *Metadata_;
1094 static _transient NSMutableDictionary *Settings_;
1095 static _transient NSString *Role_;
1096 static _transient NSMutableDictionary *Packages_;
1097 static _transient NSMutableDictionary *Sections_;
1098 static _transient NSMutableDictionary *Sources_;
1099 static bool Changed_;
1100 static NSDate *now_;
1103 static NSMutableArray *Documents_;
1106 NSString *GetLastUpdate() {
1107 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1110 return CYLocalize("NEVER_OR_UNKNOWN");
1112 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1113 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1115 CFRelease(formatter);
1117 return [(NSString *) formatted autorelease];
1120 /* Display Helpers {{{ */
1121 inline float Interpolate(float begin, float end, float fraction) {
1122 return (end - begin) * fraction + begin;
1125 /* XXX: localize this! */
1126 NSString *SizeString(double size) {
1127 bool negative = size < 0;
1132 while (size > 1024) {
1137 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1139 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1142 static _finline CFStringRef CFCString(const char *value) {
1143 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1146 CFStringRef StripVersion(const char *version) {
1147 const char *colon(strchr(version, ':'));
1149 version = colon + 1;
1150 return CFCString(version);
1153 NSString *LocalizeSection(NSString *section) {
1154 static Pcre title_r("^(.*?) \\((.*)\\)$");
1155 if (title_r(section)) {
1156 NSString *parent(title_r[1]);
1157 NSString *child(title_r[2]);
1159 return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"),
1160 LocalizeSection(parent),
1161 LocalizeSection(child)
1165 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1168 NSString *Simplify(NSString *title) {
1169 const char *data = [title UTF8String];
1170 size_t size = [title length];
1172 static Pcre square_r("^\\[(.*)\\]$");
1173 if (square_r(data, size))
1174 return Simplify(square_r[1]);
1176 static Pcre paren_r("^\\((.*)\\)$");
1177 if (paren_r(data, size))
1178 return Simplify(paren_r[1]);
1180 static Pcre title_r("^(.*?) \\((.*)\\)$");
1181 if (title_r(data, size))
1182 return Simplify(title_r[1]);
1188 bool isSectionVisible(NSString *section) {
1189 NSDictionary *metadata([Sections_ objectForKey:section]);
1190 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1191 return hidden == nil || ![hidden boolValue];
1194 /* Delegate Prototypes {{{ */
1198 @interface NSObject (ProgressDelegate)
1201 @implementation NSObject(ProgressDelegate)
1203 - (void) _setProgressError:(NSArray *)args {
1204 [self performSelector:@selector(setProgressError:forPackage:)
1205 withObject:[args objectAtIndex:0]
1206 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1212 @protocol ProgressDelegate
1213 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1214 - (void) setProgressTitle:(NSString *)title;
1215 - (void) setProgressPercent:(float)percent;
1216 - (void) startProgress;
1217 - (void) addProgressOutput:(NSString *)output;
1218 - (bool) isCancelling:(size_t)received;
1221 @protocol ConfigurationDelegate
1222 - (void) repairWithSelector:(SEL)selector;
1223 - (void) setConfigurationData:(NSString *)data;
1228 @protocol CydiaDelegate
1229 - (void) setPackageView:(PackageView *)view;
1230 - (void) clearPackage:(Package *)package;
1231 - (void) installPackage:(Package *)package;
1232 - (void) removePackage:(Package *)package;
1233 - (void) slideUp:(UIActionSheet *)alert;
1234 - (void) distUpgrade;
1235 - (void) updateData;
1237 - (void) askForSettings;
1238 - (UIProgressHUD *) addProgressHUD;
1239 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1240 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag;
1241 - (RVPage *) pageForPackage:(NSString *)name;
1242 - (void) openMailToURL:(NSURL *)url;
1243 - (void) clearFirstResponder;
1244 - (PackageView *) packageView;
1248 /* Status Delegation {{{ */
1250 public pkgAcquireStatus
1253 _transient NSObject<ProgressDelegate> *delegate_;
1261 void setDelegate(id delegate) {
1262 delegate_ = delegate;
1265 virtual bool MediaChange(std::string media, std::string drive) {
1269 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1272 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1273 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1274 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
1277 virtual void Done(pkgAcquire::ItemDesc &item) {
1280 virtual void Fail(pkgAcquire::ItemDesc &item) {
1282 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1283 item.Owner->Status == pkgAcquire::Item::StatDone
1287 std::string &error(item.Owner->ErrorText);
1291 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1292 NSArray *fields([description componentsSeparatedByString:@" "]);
1293 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1295 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1296 withObject:[NSArray arrayWithObjects:
1297 [NSString stringWithUTF8String:error.c_str()],
1304 virtual bool Pulse(pkgAcquire *Owner) {
1305 bool value = pkgAcquireStatus::Pulse(Owner);
1308 double(CurrentBytes + CurrentItems) /
1309 double(TotalBytes + TotalItems)
1312 [delegate_ setProgressPercent:percent];
1313 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1316 virtual void Start() {
1317 [delegate_ startProgress];
1320 virtual void Stop() {
1324 /* Progress Delegation {{{ */
1329 _transient id<ProgressDelegate> delegate_;
1332 virtual void Update() {
1333 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1334 [delegate_ setProgressPercent:(Percent / 100)];*/
1343 void setDelegate(id delegate) {
1344 delegate_ = delegate;
1347 virtual void Done() {
1348 //[delegate_ setProgressPercent:1];
1353 /* Database Interface {{{ */
1354 typedef std::map< unsigned long, _H<Source> > SourceMap;
1356 @interface Database : NSObject {
1362 pkgCacheFile cache_;
1363 pkgDepCache::Policy *policy_;
1364 pkgRecords *records_;
1365 pkgProblemResolver *resolver_;
1366 pkgAcquire *fetcher_;
1368 SPtr<pkgPackageManager> manager_;
1369 pkgSourceList *list_;
1372 NSMutableArray *packages_;
1374 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1383 + (Database *) sharedInstance;
1386 - (void) _readCydia:(NSNumber *)fd;
1387 - (void) _readStatus:(NSNumber *)fd;
1388 - (void) _readOutput:(NSNumber *)fd;
1392 - (Package *) packageWithName:(NSString *)name;
1394 - (pkgCacheFile &) cache;
1395 - (pkgDepCache::Policy *) policy;
1396 - (pkgRecords *) records;
1397 - (pkgProblemResolver *) resolver;
1398 - (pkgAcquire &) fetcher;
1399 - (pkgSourceList &) list;
1400 - (NSArray *) packages;
1401 - (NSArray *) sources;
1402 - (void) reloadData;
1410 - (void) updateWithStatus:(Status &)status;
1412 - (void) setDelegate:(id)delegate;
1413 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1417 /* Source Class {{{ */
1418 @interface Source : NSObject {
1419 CYString description_;
1425 CYString distribution_;
1431 CYString defaultIcon_;
1433 NSDictionary *record_;
1437 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1439 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1441 - (NSString *) supportForPackage:(NSString *)package;
1443 - (NSDictionary *) record;
1447 - (NSString *) distribution;
1448 - (NSString *) type;
1450 - (NSString *) host;
1452 - (NSString *) name;
1453 - (NSString *) description;
1454 - (NSString *) label;
1455 - (NSString *) origin;
1456 - (NSString *) version;
1458 - (NSString *) defaultIcon;
1462 @implementation Source
1466 distribution_.clear();
1469 description_.clear();
1474 defaultIcon_.clear();
1476 if (record_ != nil) {
1492 + (NSArray *) _attributeKeys {
1493 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1496 - (NSArray *) attributeKeys {
1497 return [[self class] _attributeKeys];
1500 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1501 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1504 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1507 trusted_ = index->IsTrusted();
1509 uri_.set(pool, index->GetURI());
1510 distribution_.set(pool, index->GetDist());
1511 type_.set(pool, index->GetType());
1513 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1514 if (dindex != NULL) {
1515 FileFd fd(dindex->MetaIndexFile("Release"), FileFd::ReadOnly);
1516 pkgTagFile tags(&fd);
1518 pkgTagSection section;
1525 {"default-icon", &defaultIcon_},
1526 {"description", &description_},
1528 {"origin", &origin_},
1529 {"support", &support_},
1530 {"version", &version_},
1533 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1534 const char *start, *end;
1536 if (section.Find(names[i].name_, start, end)) {
1537 CYString &value(*names[i].value_);
1538 value.set(pool, start, end - start);
1543 record_ = [Sources_ objectForKey:[self key]];
1545 record_ = [record_ retain];
1547 host_ = [[[[NSURL URLWithString:uri_] host] lowercaseString] retain];
1550 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1551 if ((self = [super init]) != nil) {
1552 [self setMetaIndex:index inPool:pool];
1556 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1557 NSDictionary *lhr = [self record];
1558 NSDictionary *rhr = [source record];
1561 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1563 NSString *lhs = [self name];
1564 NSString *rhs = [source name];
1566 if ([lhs length] != 0 && [rhs length] != 0) {
1567 unichar lhc = [lhs characterAtIndex:0];
1568 unichar rhc = [rhs characterAtIndex:0];
1570 if (isalpha(lhc) && !isalpha(rhc))
1571 return NSOrderedAscending;
1572 else if (!isalpha(lhc) && isalpha(rhc))
1573 return NSOrderedDescending;
1576 return [lhs compare:rhs options:LaxCompareOptions_];
1579 - (NSString *) supportForPackage:(NSString *)package {
1580 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1583 - (NSDictionary *) record {
1591 - (NSString *) uri {
1595 - (NSString *) distribution {
1596 return distribution_;
1599 - (NSString *) type {
1603 - (NSString *) key {
1604 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1607 - (NSString *) host {
1611 - (NSString *) name {
1612 return origin_.empty() ? host_ : origin_;
1615 - (NSString *) description {
1616 return description_;
1619 - (NSString *) label {
1620 return label_.empty() ? host_ : label_;
1623 - (NSString *) origin {
1627 - (NSString *) version {
1631 - (NSString *) defaultIcon {
1632 return defaultIcon_;
1637 /* Relationship Class {{{ */
1638 @interface Relationship : NSObject {
1643 - (NSString *) type;
1645 - (NSString *) name;
1649 @implementation Relationship
1657 - (NSString *) type {
1665 - (NSString *) name {
1672 /* Package Class {{{ */
1673 @interface Package : NSObject {
1677 pkgCache::VerIterator version_;
1678 pkgCache::PkgIterator iterator_;
1679 _transient Database *database_;
1680 pkgCache::VerFileIterator file_;
1687 NSString *section$_;
1692 NSString *installed_;
1698 CYString depiction_;
1708 NSMutableArray *tags_;
1711 NSArray *relationships_;
1713 NSMutableDictionary *metadata_;
1714 _transient NSDate *firstSeen_;
1715 _transient NSDate *lastSeen_;
1719 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1720 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1722 - (pkgCache::PkgIterator) iterator;
1725 - (NSString *) section;
1726 - (NSString *) simpleSection;
1728 - (NSString *) longSection;
1729 - (NSString *) shortSection;
1733 - (Address *) maintainer;
1735 - (NSString *) longDescription;
1736 - (NSString *) shortDescription;
1739 - (NSMutableDictionary *) metadata;
1741 - (BOOL) subscribed;
1744 - (NSString *) latest;
1745 - (NSString *) installed;
1748 - (BOOL) upgradableAndEssential:(BOOL)essential;
1751 - (BOOL) unfiltered;
1755 - (BOOL) halfConfigured;
1756 - (BOOL) halfInstalled;
1758 - (NSString *) mode;
1761 - (NSString *) name;
1763 - (NSString *) homepage;
1764 - (NSString *) depiction;
1765 - (Address *) author;
1767 - (NSString *) support;
1769 - (NSArray *) files;
1770 - (NSArray *) relationships;
1771 - (NSArray *) warnings;
1772 - (NSArray *) applications;
1774 - (Source *) source;
1775 - (NSString *) role;
1777 - (BOOL) matches:(NSString *)text;
1779 - (bool) hasSupportingRole;
1780 - (BOOL) hasTag:(NSString *)tag;
1781 - (NSString *) primaryPurpose;
1782 - (NSArray *) purposes;
1783 - (bool) isCommercial;
1785 - (CYString &) cyname;
1787 - (uint32_t) compareBySection:(NSArray *)sections;
1789 - (uint32_t) compareForChanges;
1794 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1795 - (bool) isInstalledAndVisible:(NSNumber *)number;
1796 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1797 - (bool) isVisibleInSource:(Source *)source;
1801 uint32_t PackageChangesRadix(Package *self, void *) {
1806 uint32_t timestamp : 30;
1807 uint32_t ignored : 1;
1808 uint32_t upgradable : 1;
1812 bool upgradable([self upgradableAndEssential:YES]);
1813 value.bits.upgradable = upgradable ? 1 : 0;
1816 value.bits.timestamp = 0;
1817 value.bits.ignored = [self ignored] ? 0 : 1;
1818 value.bits.upgradable = 1;
1820 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1821 value.bits.ignored = 0;
1822 value.bits.upgradable = 0;
1825 return _not(uint32_t) - value.key;
1828 _finline static void Stifle(uint8_t &value) {
1831 uint32_t PackagePrefixRadix(Package *self, void *context) {
1832 size_t offset(reinterpret_cast<size_t>(context));
1833 CYString &name([self cyname]);
1835 size_t size(name.size());
1838 char *text(name.data());
1841 if (!isdigit(text[0]))
1845 while (size != digits && isdigit(text[digits]))
1855 if (offset == 0 && zeros != 0) {
1856 memset(data, '0', zeros);
1857 memcpy(data + zeros, text, 4 - zeros);
1859 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1860 if (size <= offset - zeros)
1863 text += offset - zeros;
1864 size -= offset - zeros;
1867 memcpy(data, text, 4);
1869 memcpy(data, text, size);
1870 memset(data + size, 0, 4 - size);
1873 for (size_t i(0); i != 4; ++i)
1874 if (isalpha(data[i]))
1879 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1881 /* XXX: ntohl may be more honest */
1882 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1885 CYString &(*PackageName)(Package *self, SEL sel);
1887 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1888 _profile(PackageNameCompare)
1889 CYString &lhi(PackageName(lhs, @selector(cyname)));
1890 CYString &rhi(PackageName(rhs, @selector(cyname)));
1891 CFStringRef lhn(lhi), rhn(rhi);
1893 _profile(PackageNameCompare$NumbersLast)
1894 if (!lhi.empty() && !rhi.empty()) {
1895 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1896 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1897 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1898 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1899 return lha ? NSOrderedAscending : NSOrderedDescending;
1903 CFIndex length = CFStringGetLength(lhn);
1905 _profile(PackageNameCompare$Compare)
1906 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1911 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1912 return PackageNameCompare(*lhs, *rhs, context);
1915 struct PackageNameOrdering :
1916 std::binary_function<Package *, Package *, bool>
1918 _finline bool operator ()(Package *lhs, Package *rhs) const {
1919 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1923 @implementation Package
1925 - (NSString *) description {
1926 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1932 if (section$_ != nil)
1933 [section$_ release];
1937 if (installed_ != nil)
1938 [installed_ release];
1940 if (sponsor$_ != nil)
1941 [sponsor$_ release];
1942 if (author$_ != nil)
1949 if (relationships_ != nil)
1950 [relationships_ release];
1951 if (metadata_ != nil)
1952 [metadata_ release];
1957 + (NSString *) webScriptNameForSelector:(SEL)selector {
1958 if (selector == @selector(hasTag:))
1964 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1965 return [self webScriptNameForSelector:selector] == nil;
1968 + (NSArray *) _attributeKeys {
1969 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];
1972 - (NSArray *) attributeKeys {
1973 return [[self class] _attributeKeys];
1976 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1977 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1987 _profile(Package$parse)
1988 pkgRecords::Parser *parser;
1990 _profile(Package$parse$Lookup)
1991 parser = &[database_ records]->Lookup(file_);
1996 _profile(Package$parse$Find)
2002 {"depiction", &depiction_},
2003 {"homepage", &homepage_},
2004 {"website", &website},
2005 {"support", &support_},
2006 {"sponsor", &sponsor_},
2007 {"author", &author_},
2010 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2011 const char *start, *end;
2013 if (parser->Find(names[i].name_, start, end)) {
2014 CYString &value(*names[i].value_);
2015 _profile(Package$parse$Value)
2016 value.set(pool_, start, end - start);
2022 _profile(Package$parse$Tagline)
2023 const char *start, *end;
2024 if (parser->ShortDesc(start, end)) {
2025 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2028 while (stop != start && stop[-1] == '\r')
2030 tagline_.set(pool_, start, stop - start);
2034 _profile(Package$parse$Retain)
2035 if (!homepage_.empty())
2036 homepage_ = website;
2037 if (homepage_ == depiction_)
2043 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2044 if ((self = [super init]) != nil) {
2045 _profile(Package$initWithVersion)
2046 @synchronized (database) {
2047 era_ = [database era];
2051 iterator_ = version.ParentPkg();
2052 database_ = database;
2054 _profile(Package$initWithVersion$Latest)
2055 latest_ = (NSString *) StripVersion(version_.VerStr());
2058 pkgCache::VerIterator current;
2059 _profile(Package$initWithVersion$Versions)
2060 current = iterator_.CurrentVer();
2062 installed_ = (NSString *) StripVersion(current.VerStr());
2064 if (!version_.end())
2065 file_ = version_.FileList();
2067 pkgCache &cache([database_ cache]);
2068 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2072 _profile(Package$initWithVersion$Name)
2073 id_.set(pool_, iterator_.Name());
2074 name_.set(pool, iterator_.Display());
2078 _profile(Package$initWithVersion$Source)
2079 source_ = [database_ getSource:file_.File()];
2086 _profile(Package$initWithVersion$Tags)
2087 pkgCache::TagIterator tag(iterator_.TagList());
2089 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2091 const char *name(tag.Name());
2092 [tags_ addObject:(NSString *)CFCString(name)];
2093 if (role_ == nil && strncmp(name, "role::", 6) == 0)
2094 role_ = (NSString *) CFCString(name + 6);
2096 } while (!tag.end());
2100 bool changed(false);
2101 NSString *key([id_ lowercaseString]);
2103 _profile(Package$initWithVersion$Metadata)
2104 metadata_ = [Packages_ objectForKey:key];
2106 if (metadata_ == nil) {
2109 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2110 firstSeen_, @"FirstSeen",
2111 latest_, @"LastVersion",
2116 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2117 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2119 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2120 subscribed_ = [subscribed boolValue];
2122 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2124 if (firstSeen_ == nil) {
2125 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2126 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2130 if (version == nil) {
2131 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2133 } else if (![version isEqualToString:latest_]) {
2134 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2136 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2141 metadata_ = [metadata_ retain];
2144 [Packages_ setObject:metadata_ forKey:key];
2149 _profile(Package$initWithVersion$Section)
2150 section_.set(pool_, iterator_.Section());
2153 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2154 visible_ = [self hasSupportingRole] && [self unfiltered];
2155 } _end } return self;
2158 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2159 pkgCache::VerIterator version;
2161 _profile(Package$packageWithIterator$GetCandidateVer)
2162 version = [database policy]->GetCandidateVer(iterator);
2168 return [[[Package alloc]
2169 initWithVersion:version
2176 - (pkgCache::PkgIterator) iterator {
2180 - (NSString *) section {
2181 if (section$_ == nil) {
2182 if (section_.empty())
2185 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2186 NSString *name(section_);
2189 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2190 if (NSString *rename = [value objectForKey:@"Rename"]) {
2195 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2199 - (NSString *) simpleSection {
2200 if (NSString *section = [self section])
2201 return Simplify(section);
2206 - (NSString *) longSection {
2207 return LocalizeSection(section_);
2210 - (NSString *) shortSection {
2211 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2214 - (NSString *) uri {
2217 pkgIndexFile *index;
2218 pkgCache::PkgFileIterator file(file_.File());
2219 if (![database_ list].FindIndex(file, index))
2221 return [NSString stringWithUTF8String:iterator_->Path];
2222 //return [NSString stringWithUTF8String:file.Site()];
2223 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2227 - (Address *) maintainer {
2230 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2231 const std::string &maintainer(parser->Maintainer());
2232 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2236 return version_.end() ? 0 : version_->InstalledSize;
2239 - (NSString *) longDescription {
2242 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2243 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2245 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2246 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2247 if ([lines count] < 2)
2250 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2251 for (size_t i(1), e([lines count]); i != e; ++i) {
2252 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2253 [trimmed addObject:trim];
2256 return [trimmed componentsJoinedByString:@"\n"];
2259 - (NSString *) shortDescription {
2264 _profile(Package$index)
2265 CFStringRef name((CFStringRef) [self name]);
2266 if (CFStringGetLength(name) == 0)
2268 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2269 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2271 return toupper(character);
2275 - (NSMutableDictionary *) metadata {
2280 if (subscribed_ && lastSeen_ != nil)
2285 - (BOOL) subscribed {
2290 NSDictionary *metadata([self metadata]);
2291 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2292 return [ignored boolValue];
2297 - (NSString *) latest {
2301 - (NSString *) installed {
2306 return !version_.end();
2309 - (BOOL) upgradableAndEssential:(BOOL)essential {
2310 _profile(Package$upgradableAndEssential)
2311 pkgCache::VerIterator current(iterator_.CurrentVer());
2313 return essential && essential_ && visible_;
2315 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2319 - (BOOL) essential {
2324 return [database_ cache][iterator_].InstBroken();
2327 - (BOOL) unfiltered {
2328 NSString *section([self section]);
2329 return section == nil || isSectionVisible(section);
2337 unsigned char current(iterator_->CurrentState);
2338 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2341 - (BOOL) halfConfigured {
2342 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2345 - (BOOL) halfInstalled {
2346 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2350 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2351 return state.Mode != pkgDepCache::ModeKeep;
2354 - (NSString *) mode {
2355 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2357 switch (state.Mode) {
2358 case pkgDepCache::ModeDelete:
2359 if ((state.iFlags & pkgDepCache::Purge) != 0)
2363 case pkgDepCache::ModeKeep:
2364 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2365 return @"REINSTALL";
2366 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2370 case pkgDepCache::ModeInstall:
2371 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2372 return @"REINSTALL";
2373 else*/ switch (state.Status) {
2375 return @"DOWNGRADE";
2381 return @"NEW_INSTALL";
2394 - (NSString *) name {
2395 return name_.empty() ? id_ : name_;
2398 - (UIImage *) icon {
2399 NSString *section = [self simpleSection];
2403 if ([icon_ hasPrefix:@"file:///"])
2404 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2405 if (icon == nil) if (section != nil)
2406 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2407 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2408 if ([dicon hasPrefix:@"file:///"])
2409 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2411 icon = [UIImage applicationImageNamed:@"unknown.png"];
2415 - (NSString *) homepage {
2419 - (NSString *) depiction {
2423 - (Address *) sponsor {
2424 if (sponsor$_ == nil) {
2425 if (sponsor_.empty())
2427 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2431 - (Address *) author {
2432 if (author$_ == nil) {
2433 if (author_.empty())
2435 author$_ = [[Address addressWithString:author_] retain];
2439 - (NSString *) support {
2440 return !support_.empty() ? support_ : [[self source] supportForPackage:id_];
2443 - (NSArray *) files {
2444 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2445 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2448 fin.open([path UTF8String]);
2453 while (std::getline(fin, line))
2454 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2459 - (NSArray *) relationships {
2460 return relationships_;
2463 - (NSArray *) warnings {
2464 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2465 const char *name(iterator_.Name());
2467 size_t length(strlen(name));
2468 if (length < 2) invalid:
2469 [warnings addObject:CYLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2470 else for (size_t i(0); i != length; ++i)
2472 /* XXX: technically this is not allowed */
2473 (name[i] < 'A' || name[i] > 'Z') &&
2474 (name[i] < 'a' || name[i] > 'z') &&
2475 (name[i] < '0' || name[i] > '9') &&
2476 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2479 if (strcmp(name, "cydia") != 0) {
2481 bool _private = false;
2484 bool repository = [[self section] isEqualToString:@"Repositories"];
2486 if (NSArray *files = [self files])
2487 for (NSString *file in files)
2488 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2490 else if (!_private && [file isEqualToString:@"/private"])
2492 else if (!stash && [file isEqualToString:@"/var/stash"])
2495 /* XXX: this is not sensitive enough. only some folders are valid. */
2496 if (cydia && !repository)
2497 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2499 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/private"]];
2501 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2504 return [warnings count] == 0 ? nil : warnings;
2507 - (NSArray *) applications {
2508 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2510 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2512 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2513 if (NSArray *files = [self files])
2514 for (NSString *file in files)
2515 if (application_r(file)) {
2516 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2517 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2518 if ([id isEqualToString:me])
2521 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2523 display = application_r[1];
2525 NSString *bundle([file stringByDeletingLastPathComponent]);
2526 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2527 if (icon == nil || [icon length] == 0)
2529 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2531 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2532 [applications addObject:application];
2534 [application addObject:id];
2535 [application addObject:display];
2536 [application addObject:url];
2539 return [applications count] == 0 ? nil : applications;
2542 - (Source *) source {
2544 @synchronized (database_) {
2545 if ([database_ era] != era_ || file_.end())
2548 source_ = [database_ getSource:file_.File()];
2560 - (NSString *) role {
2564 - (BOOL) matches:(NSString *)text {
2570 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2571 if (range.location != NSNotFound)
2574 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2575 if (range.location != NSNotFound)
2578 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2579 if (range.location != NSNotFound)
2585 - (bool) hasSupportingRole {
2588 if ([role_ isEqualToString:@"enduser"])
2590 if ([Role_ isEqualToString:@"User"])
2592 if ([role_ isEqualToString:@"hacker"])
2594 if ([Role_ isEqualToString:@"Hacker"])
2596 if ([role_ isEqualToString:@"developer"])
2598 if ([Role_ isEqualToString:@"Developer"])
2603 - (BOOL) hasTag:(NSString *)tag {
2604 return tags_ == nil ? NO : [tags_ containsObject:tag];
2607 - (NSString *) primaryPurpose {
2608 for (NSString *tag in tags_)
2609 if ([tag hasPrefix:@"purpose::"])
2610 return [tag substringFromIndex:9];
2614 - (NSArray *) purposes {
2615 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2616 for (NSString *tag in tags_)
2617 if ([tag hasPrefix:@"purpose::"])
2618 [purposes addObject:[tag substringFromIndex:9]];
2619 return [purposes count] == 0 ? nil : purposes;
2622 - (bool) isCommercial {
2623 return [self hasTag:@"cydia::commercial"];
2626 - (CYString &) cyname {
2627 return name_.empty() ? id_ : name_;
2630 - (uint32_t) compareBySection:(NSArray *)sections {
2631 NSString *section([self section]);
2632 for (size_t i(0), e([sections count]); i != e; ++i) {
2633 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2637 return _not(uint32_t);
2640 - (uint32_t) compareForChanges {
2645 uint32_t timestamp : 30;
2646 uint32_t ignored : 1;
2647 uint32_t upgradable : 1;
2651 bool upgradable([self upgradableAndEssential:YES]);
2652 value.bits.upgradable = upgradable ? 1 : 0;
2655 value.bits.timestamp = 0;
2656 value.bits.ignored = [self ignored] ? 0 : 1;
2657 value.bits.upgradable = 1;
2659 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2660 value.bits.ignored = 0;
2661 value.bits.upgradable = 0;
2664 return _not(uint32_t) - value.key;
2668 pkgProblemResolver *resolver = [database_ resolver];
2669 resolver->Clear(iterator_);
2670 resolver->Protect(iterator_);
2674 pkgProblemResolver *resolver = [database_ resolver];
2675 resolver->Clear(iterator_);
2676 resolver->Protect(iterator_);
2677 pkgCacheFile &cache([database_ cache]);
2678 cache->MarkInstall(iterator_, false);
2679 pkgDepCache::StateCache &state((*cache)[iterator_]);
2680 if (!state.Install())
2681 cache->SetReInstall(iterator_, true);
2685 pkgProblemResolver *resolver = [database_ resolver];
2686 resolver->Clear(iterator_);
2687 resolver->Protect(iterator_);
2688 resolver->Remove(iterator_);
2689 [database_ cache]->MarkDelete(iterator_, true);
2692 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2693 _profile(Package$isUnfilteredAndSearchedForBy)
2696 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2697 value &= [self unfiltered];
2700 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2701 value &= [self matches:search];
2708 - (bool) isInstalledAndVisible:(NSNumber *)number {
2709 return (![number boolValue] || [self visible]) && [self installed] != nil;
2712 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2713 NSString *section = [self section];
2717 [self installed] == nil && (
2719 section == nil && [name length] == 0 ||
2720 [name isEqualToString:section]
2724 - (bool) isVisibleInSource:(Source *)source {
2725 return [self source] == source && [self visible];
2730 /* Section Class {{{ */
2731 @interface Section : NSObject {
2736 NSString *localized_;
2739 - (NSComparisonResult) compareByLocalized:(Section *)section;
2740 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2741 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2742 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2743 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2744 - (NSString *) name;
2751 - (void) addToCount;
2753 - (void) setCount:(size_t)count;
2754 - (NSString *) localized;
2758 @implementation Section
2762 if (localized_ != nil)
2763 [localized_ release];
2767 - (NSComparisonResult) compareByLocalized:(Section *)section {
2768 NSString *lhs(localized_);
2769 NSString *rhs([section localized]);
2771 /*if ([lhs length] != 0 && [rhs length] != 0) {
2772 unichar lhc = [lhs characterAtIndex:0];
2773 unichar rhc = [rhs characterAtIndex:0];
2775 if (isalpha(lhc) && !isalpha(rhc))
2776 return NSOrderedAscending;
2777 else if (!isalpha(lhc) && isalpha(rhc))
2778 return NSOrderedDescending;
2781 return [lhs compare:rhs options:LaxCompareOptions_];
2784 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2785 if ((self = [self initWithName:name localize:NO]) != nil) {
2786 if (localized != nil)
2787 localized_ = [localized retain];
2791 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2792 return [self initWithName:name row:0 localize:localize];
2795 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2796 if ((self = [super init]) != nil) {
2797 name_ = [name retain];
2801 localized_ = [LocalizeSection(name_) retain];
2805 /* XXX: localize the index thingees */
2806 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2807 if ((self = [super init]) != nil) {
2808 name_ = [(index == '#' ? @"123" : [NSString stringWithCharacters:&index length:1]) retain];
2814 - (NSString *) name {
2834 - (void) addToCount {
2838 - (void) setCount:(size_t)count {
2842 - (NSString *) localized {
2850 static NSArray *Finishes_;
2852 /* Database Implementation {{{ */
2853 @implementation Database
2855 + (Database *) sharedInstance {
2856 static Database *instance;
2857 if (instance == nil)
2858 instance = [[Database alloc] init];
2868 NSRecycleZone(zone_);
2869 // XXX: malloc_destroy_zone(zone_);
2870 apr_pool_destroy(pool_);
2874 - (void) _readCydia:(NSNumber *)fd { _pooled
2875 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2876 std::istream is(&ib);
2879 static Pcre finish_r("^finish:([^:]*)$");
2881 while (std::getline(is, line)) {
2882 const char *data(line.c_str());
2883 size_t size = line.size();
2884 lprintf("C:%s\n", data);
2886 if (finish_r(data, size)) {
2887 NSString *finish = finish_r[1];
2888 int index = [Finishes_ indexOfObject:finish];
2889 if (index != INT_MAX && index > Finish_)
2897 - (void) _readStatus:(NSNumber *)fd { _pooled
2898 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2899 std::istream is(&ib);
2902 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2903 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2905 while (std::getline(is, line)) {
2906 const char *data(line.c_str());
2907 size_t size = line.size();
2908 lprintf("S:%s\n", data);
2910 if (conffile_r(data, size)) {
2911 [delegate_ setConfigurationData:conffile_r[1]];
2912 } else if (strncmp(data, "status: ", 8) == 0) {
2913 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2914 [delegate_ setProgressTitle:string];
2915 } else if (pmstatus_r(data, size)) {
2916 std::string type([pmstatus_r[1] UTF8String]);
2917 NSString *id = pmstatus_r[2];
2919 float percent([pmstatus_r[3] floatValue]);
2920 [delegate_ setProgressPercent:(percent / 100)];
2922 NSString *string = pmstatus_r[4];
2924 if (type == "pmerror")
2925 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2926 withObject:[NSArray arrayWithObjects:string, id, nil]
2929 else if (type == "pmstatus") {
2930 [delegate_ setProgressTitle:string];
2931 } else if (type == "pmconffile")
2932 [delegate_ setConfigurationData:string];
2933 else _assert(false);
2934 } else _assert(false);
2940 - (void) _readOutput:(NSNumber *)fd { _pooled
2941 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2942 std::istream is(&ib);
2945 while (std::getline(is, line)) {
2946 lprintf("O:%s\n", line.c_str());
2947 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2957 - (Package *) packageWithName:(NSString *)name {
2958 if (static_cast<pkgDepCache *>(cache_) == NULL)
2960 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
2961 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
2964 - (Database *) init {
2965 if ((self = [super init]) != nil) {
2972 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
2973 apr_pool_create(&pool_, NULL);
2975 packages_ = [[NSMutableArray alloc] init];
2979 _assert(pipe(fds) != -1);
2982 _config->Set("APT::Keep-Fds::", cydiafd_);
2983 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
2986 detachNewThreadSelector:@selector(_readCydia:)
2988 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2991 _assert(pipe(fds) != -1);
2995 detachNewThreadSelector:@selector(_readStatus:)
2997 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3000 _assert(pipe(fds) != -1);
3001 _assert(dup2(fds[0], 0) != -1);
3002 _assert(close(fds[0]) != -1);
3004 input_ = fdopen(fds[1], "a");
3006 _assert(pipe(fds) != -1);
3007 _assert(dup2(fds[1], 1) != -1);
3008 _assert(close(fds[1]) != -1);
3011 detachNewThreadSelector:@selector(_readOutput:)
3013 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3018 - (pkgCacheFile &) cache {
3022 - (pkgDepCache::Policy *) policy {
3026 - (pkgRecords *) records {
3030 - (pkgProblemResolver *) resolver {
3034 - (pkgAcquire &) fetcher {
3038 - (pkgSourceList &) list {
3042 - (NSArray *) packages {
3046 - (NSArray *) sources {
3047 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3048 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3049 [sources addObject:i->second];
3053 - (NSArray *) issues {
3054 if (cache_->BrokenCount() == 0)
3057 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3059 for (Package *package in packages_) {
3060 if (![package broken])
3062 pkgCache::PkgIterator pkg([package iterator]);
3064 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3065 [entry addObject:[package name]];
3066 [issues addObject:entry];
3068 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3072 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3073 pkgCache::DepIterator start;
3074 pkgCache::DepIterator end;
3075 dep.GlobOr(start, end); // ++dep
3077 if (!cache_->IsImportantDep(end))
3079 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3082 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3083 [entry addObject:failure];
3084 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3086 Package *package([self packageWithName:[NSString stringWithUTF8String:start.TargetPkg().Name()]]);
3087 [failure addObject:[package name]];
3089 pkgCache::PkgIterator target(start.TargetPkg());
3090 if (target->ProvidesList != 0)
3091 [failure addObject:@"?"];
3093 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3095 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3096 else if (!cache_[target].CandidateVerIter(cache_).end())
3097 [failure addObject:@"-"];
3098 else if (target->ProvidesList == 0)
3099 [failure addObject:@"!"];
3101 [failure addObject:@"%"];
3105 if (start.TargetVer() != 0)
3106 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3117 - (void) reloadData { _pooled
3118 @synchronized (self) {
3122 [packages_ removeAllObjects];
3148 apr_pool_clear(pool_);
3149 NSRecycleZone(zone_);
3151 int chk(creat("/tmp/cydia.chk", 0644));
3156 if (!cache_.Open(progress_, true)) {
3158 if (!_error->PopMessage(error))
3161 lprintf("cache_.Open():[%s]\n", error.c_str());
3163 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3164 [delegate_ repairWithSelector:@selector(configure)];
3165 else if (error == "The package lists or status file could not be parsed or opened.")
3166 [delegate_ repairWithSelector:@selector(update)];
3167 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3168 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3169 // else if (error == "The list of sources could not be read.")
3170 else _assert(false);
3176 unlink("/tmp/cydia.chk");
3178 now_ = [[NSDate date] retain];
3180 policy_ = new pkgDepCache::Policy();
3181 records_ = new pkgRecords(cache_);
3182 resolver_ = new pkgProblemResolver(cache_);
3183 fetcher_ = new pkgAcquire(&status_);
3186 list_ = new pkgSourceList();
3187 _assert(list_->ReadMainList());
3189 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3190 _assert(pkgApplyStatus(cache_));
3192 if (cache_->BrokenCount() != 0) {
3193 _assert(pkgFixBroken(cache_));
3194 _assert(cache_->BrokenCount() == 0);
3195 _assert(pkgMinimizeUpgrade(cache_));
3200 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3201 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3202 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3203 // XXX: this could be more intelligent
3204 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3205 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3207 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3214 /*std::vector<Package *> packages;
3215 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3216 [packages_ release];
3221 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3222 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3223 //packages.push_back(package);
3224 [packages_ addObject:package];
3228 /*if (packages.empty())
3229 packages_ = [[NSArray alloc] init];
3231 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3234 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3235 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3236 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3244 /*if (!packages.empty())
3245 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3246 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3248 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3250 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3252 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3258 - (void) configure {
3259 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3260 system([dpkg UTF8String]);
3268 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3269 _assert(!_error->PendingError());
3272 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3275 public pkgArchiveCleaner
3278 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3283 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3285 while (_error->PopMessage(error))
3286 lprintf("ArchiveCleaner: %s\n", error.c_str());
3291 pkgRecords records(cache_);
3293 lock_ = new FileFd();
3294 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3295 _assert(!_error->PendingError());
3298 // XXX: explain this with an error message
3299 _assert(list.ReadMainList());
3301 manager_ = (_system->CreatePM(cache_));
3302 _assert(manager_->GetArchives(fetcher_, &list, &records));
3303 _assert(!_error->PendingError());
3307 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3309 _assert(list.ReadMainList());
3310 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3311 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3314 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3319 bool failed = false;
3320 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3321 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3324 std::string uri = (*item)->DescURI();
3325 std::string error = (*item)->ErrorText;
3327 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3330 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3331 withObject:[NSArray arrayWithObjects:
3332 [NSString stringWithUTF8String:error.c_str()],
3344 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3346 if (_error->PendingError()) {
3351 if (result == pkgPackageManager::Failed) {
3356 if (result != pkgPackageManager::Completed) {
3361 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3363 _assert(list.ReadMainList());
3364 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3365 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3368 if (![before isEqualToArray:after])
3373 _assert(pkgDistUpgrade(cache_));
3377 [self updateWithStatus:status_];
3380 - (void) updateWithStatus:(Status &)status {
3382 _assert(list.ReadMainList());
3385 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3386 _assert(!_error->PendingError());
3388 pkgAcquire fetcher(&status);
3389 _assert(list.GetIndexes(&fetcher));
3391 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3392 bool failed = false;
3393 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3394 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3395 (*item)->Finished();
3399 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3400 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3401 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3404 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3409 - (void) setDelegate:(id)delegate {
3410 delegate_ = delegate;
3411 status_.setDelegate(delegate);
3412 progress_.setDelegate(delegate);
3415 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3416 return sources_[file->ID];
3422 /* PopUp Windows {{{ */
3423 @interface PopUpView : UIView {
3424 _transient id delegate_;
3425 UITransitionView *transition_;
3430 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3434 @implementation PopUpView
3437 [transition_ setDelegate:nil];
3438 [transition_ release];
3444 [transition_ transition:UITransitionPushFromTop toView:nil];
3447 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3448 if (from != nil && to == nil)
3449 [self removeFromSuperview];
3452 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3453 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3454 delegate_ = delegate;
3456 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3457 [self addSubview:transition_];
3459 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3461 [view addSubview:self];
3463 [transition_ setDelegate:self];
3465 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3466 [transition_ transition:UITransitionNone toView:blank];
3467 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3475 /* Mail Composition {{{ */
3476 @interface MailToView : PopUpView {
3477 MailComposeController *controller_;
3480 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
3484 @implementation MailToView
3487 [controller_ release];
3491 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
3495 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
3496 NSLog(@"did:%@", delivery);
3497 // [UIApp setStatusBarShowsProgress:NO];
3498 if ([controller error]){
3499 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3500 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3501 [mailAlertSheet setBodyText:[controller error]];
3502 [mailAlertSheet popupAlertAnimated:YES];
3506 - (void) showError {
3507 NSLog(@"%@", [controller_ error]);
3508 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3509 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3510 [mailAlertSheet setBodyText:[controller_ error]];
3511 [mailAlertSheet popupAlertAnimated:YES];
3514 - (void) deliverMessage { _pooled
3518 if (![controller_ deliverMessage])
3519 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
3522 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
3523 if ([controller_ needsDelivery])
3524 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
3529 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
3530 if ((self = [super initWithView:view delegate:delegate]) != nil) {
3531 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
3532 [controller_ setDelegate:self];
3533 [controller_ initializeUI];
3534 [controller_ setupForURL:url];
3536 UIView *view([controller_ view]);
3537 [overlay_ addSubview:view];
3545 /* Confirmation View {{{ */
3546 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3547 if (!iterator.end())
3548 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3549 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3551 pkgCache::PkgIterator package(dep.TargetPkg());
3554 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3561 @protocol ConfirmationViewDelegate
3567 @interface ConfirmationView : BrowserView {
3568 _transient Database *database_;
3569 UIActionSheet *essential_;
3576 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3580 @implementation ConfirmationView
3587 if (essential_ != nil)
3588 [essential_ release];
3594 [book_ popFromSuperviewAnimated:YES];
3597 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3598 NSString *context([sheet context]);
3600 if ([context isEqualToString:@"remove"]) {
3608 [delegate_ confirm];
3615 } else if ([context isEqualToString:@"unable"]) {
3619 [super alertSheet:sheet buttonClicked:button];
3622 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3623 [super webView:sender didClearWindowObject:window forFrame:frame];
3624 [window setValue:changes_ forKey:@"changes"];
3625 [window setValue:issues_ forKey:@"issues"];
3626 [window setValue:sizes_ forKey:@"sizes"];
3629 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3630 if ((self = [super initWithBook:book]) != nil) {
3631 database_ = database;
3633 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3634 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3635 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3636 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3637 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3641 pkgDepCache::Policy *policy([database_ policy]);
3643 pkgCacheFile &cache([database_ cache]);
3644 NSArray *packages = [database_ packages];
3645 for (Package *package in packages) {
3646 pkgCache::PkgIterator iterator = [package iterator];
3647 pkgDepCache::StateCache &state(cache[iterator]);
3649 NSString *name([package name]);
3651 if (state.NewInstall())
3652 [installing addObject:name];
3653 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3654 [reinstalling addObject:name];
3655 else if (state.Upgrade())
3656 [upgrading addObject:name];
3657 else if (state.Downgrade())
3658 [downgrading addObject:name];
3659 else if (state.Delete()) {
3660 if ([package essential])
3662 [removing addObject:name];
3665 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3666 substrate_ |= DepSubstrate(iterator.CurrentVer());
3671 else if (Advanced_ || true) {
3672 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
3674 essential_ = [[UIActionSheet alloc]
3675 initWithTitle:CYLocalize("REMOVING_ESSENTIALS")
3676 buttons:[NSArray arrayWithObjects:
3677 [NSString stringWithFormat:parenthetical, CYLocalize("CANCEL_OPERATION"), CYLocalize("SAFE")],
3678 [NSString stringWithFormat:parenthetical, CYLocalize("FORCE_REMOVAL"), CYLocalize("UNSAFE")],
3680 defaultButtonIndex:0
3686 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3688 [essential_ setBodyText:CYLocalize("REMOVING_ESSENTIALS_EX")];
3690 essential_ = [[UIActionSheet alloc]
3691 initWithTitle:CYLocalize("UNABLE_TO_COMPLY")
3692 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3693 defaultButtonIndex:0
3698 [essential_ setBodyText:CYLocalize("UNABLE_TO_COMPLY_EX")];
3701 changes_ = [[NSArray alloc] initWithObjects:
3709 issues_ = [database_ issues];
3711 issues_ = [issues_ retain];
3713 sizes_ = [[NSArray alloc] initWithObjects:
3714 SizeString([database_ fetcher].FetchNeeded()),
3715 SizeString([database_ fetcher].PartialPresent()),
3716 SizeString([database_ cache]->UsrSize()),
3719 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3723 - (NSString *) backButtonTitle {
3724 return CYLocalize("CONFIRM");
3727 - (NSString *) leftButtonTitle {
3728 return [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("CANCEL"), CYLocalize("QUEUE")];
3731 - (id) rightButtonTitle {
3732 return issues_ != nil ? nil : [super rightButtonTitle];
3735 - (id) _rightButtonTitle {
3736 #if AlwaysReload || IgnoreInstall
3737 return [super _rightButtonTitle];
3739 return CYLocalize("CONFIRM");
3743 - (void) _leftButtonClicked {
3748 - (void) _rightButtonClicked {
3750 return [super _rightButtonClicked];
3752 if (essential_ != nil)
3753 [essential_ popupAlertAnimated:YES];
3757 [delegate_ confirm];
3765 /* Progress Data {{{ */
3766 @interface ProgressData : NSObject {
3772 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3779 @implementation ProgressData
3781 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3782 if ((self = [super init]) != nil) {
3783 selector_ = selector;
3803 /* Progress View {{{ */
3804 @interface ProgressView : UIView <
3805 ConfigurationDelegate,
3808 _transient Database *database_;
3810 UIView *background_;
3811 UITransitionView *transition_;
3813 UINavigationBar *navbar_;
3814 UIProgressBar *progress_;
3815 UITextView *output_;
3816 UITextLabel *status_;
3817 UIPushButton *close_;
3820 SHA1SumValue springlist_;
3821 SHA1SumValue notifyconf_;
3822 SHA1SumValue sandplate_;
3825 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
3827 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
3828 - (void) setContentView:(UIView *)view;
3831 - (void) _retachThread;
3832 - (void) _detachNewThreadData:(ProgressData *)data;
3833 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
3839 @protocol ProgressViewDelegate
3840 - (void) progressViewIsComplete:(ProgressView *)sender;
3843 @implementation ProgressView
3846 [transition_ setDelegate:nil];
3847 [navbar_ setDelegate:nil];
3850 if (background_ != nil)
3851 [background_ release];
3852 [transition_ release];
3855 [progress_ release];
3862 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3863 if (bootstrap_ && from == overlay_ && to == view_)
3867 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
3868 if ((self = [super initWithFrame:frame]) != nil) {
3869 database_ = database;
3870 delegate_ = delegate;
3872 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3873 [transition_ setDelegate:self];
3875 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3878 [overlay_ setBackgroundColor:[UIColor blackColor]];
3880 background_ = [[UIView alloc] initWithFrame:[self bounds]];
3881 [background_ setBackgroundColor:[UIColor blackColor]];
3882 [self addSubview:background_];
3885 [self addSubview:transition_];
3887 CGSize navsize = [UINavigationBar defaultSize];
3888 CGRect navrect = {{0, 0}, navsize};
3890 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
3891 [overlay_ addSubview:navbar_];
3893 [navbar_ setBarStyle:1];
3894 [navbar_ setDelegate:self];
3896 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
3897 [navbar_ pushNavigationItem:navitem];
3899 CGRect bounds = [overlay_ bounds];
3900 CGSize prgsize = [UIProgressBar defaultSize];
3903 (bounds.size.width - prgsize.width) / 2,
3904 bounds.size.height - prgsize.height - 20
3907 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3908 [progress_ setStyle:0];
3910 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3912 bounds.size.height - prgsize.height - 50,
3913 bounds.size.width - 20,
3917 [status_ setColor:[UIColor whiteColor]];
3918 [status_ setBackgroundColor:[UIColor clearColor]];
3920 [status_ setCentersHorizontally:YES];
3921 //[status_ setFont:font];
3924 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3926 navrect.size.height + 20,
3927 bounds.size.width - 20,
3928 bounds.size.height - navsize.height - 62 - navrect.size.height
3932 //[output_ setTextFont:@"Courier New"];
3933 [output_ setTextSize:12];
3935 [output_ setTextColor:[UIColor whiteColor]];
3936 [output_ setBackgroundColor:[UIColor clearColor]];
3938 [output_ setMarginTop:0];
3939 [output_ setAllowsRubberBanding:YES];
3940 [output_ setEditable:NO];
3942 [overlay_ addSubview:output_];
3944 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3946 bounds.size.height - prgsize.height - 50,
3947 bounds.size.width - 20,
3951 [close_ setAutosizesToFit:NO];
3952 [close_ setDrawsShadow:YES];
3953 [close_ setStretchBackground:YES];
3954 [close_ setEnabled:YES];
3956 UIFont *bold = [UIFont boldSystemFontOfSize:22];
3957 [close_ setTitleFont:bold];
3959 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
3960 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
3961 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
3965 - (void) setContentView:(UIView *)view {
3966 view_ = [view retain];
3969 - (void) resetView {
3970 [transition_ transition:6 toView:view_];
3973 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3974 NSString *context([sheet context]);
3976 if ([context isEqualToString:@"error"])
3978 else if ([context isEqualToString:@"conffile"]) {
3979 FILE *input = [database_ input];
3983 fprintf(input, "N\n");
3987 fprintf(input, "Y\n");
3998 - (void) closeButtonPushed {
4007 [delegate_ suspendWithAnimation:YES];
4011 system("launchctl stop com.apple.SpringBoard");
4015 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4024 - (void) _retachThread {
4025 UINavigationItem *item = [navbar_ topItem];
4026 [item setTitle:CYLocalize("COMPLETE")];
4028 [overlay_ addSubview:close_];
4029 [progress_ removeFromSuperview];
4030 [status_ removeFromSuperview];
4032 [delegate_ progressViewIsComplete:self];
4035 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4036 MMap mmap(file, MMap::ReadOnly);
4038 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4039 if (!(sandplate_ == sha1.Result()))
4044 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4045 MMap mmap(file, MMap::ReadOnly);
4047 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4048 if (!(notifyconf_ == sha1.Result()))
4053 FileFd file(SpringBoard_, FileFd::ReadOnly);
4054 MMap mmap(file, MMap::ReadOnly);
4056 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4057 if (!(springlist_ == sha1.Result()))
4062 case 0: [close_ setTitle:CYLocalize("RETURN_TO_CYDIA")]; break;
4063 case 1: [close_ setTitle:CYLocalize("CLOSE_CYDIA")]; break;
4064 case 2: [close_ setTitle:CYLocalize("RESTART_SPRINGBOARD")]; break;
4065 case 3: [close_ setTitle:CYLocalize("RELOAD_SPRINGBOARD")]; break;
4066 case 4: [close_ setTitle:CYLocalize("REBOOT_DEVICE")]; break;
4069 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4071 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
4072 [cache autorelease];
4074 NSFileManager *manager = [NSFileManager defaultManager];
4075 NSError *error = nil;
4077 id system = [cache objectForKey:@"System"];
4082 if (stat(Cache_, &info) == -1)
4085 [system removeAllObjects];
4087 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4088 for (NSString *app in apps)
4089 if ([app hasSuffix:@".app"]) {
4090 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4091 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4092 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4094 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4095 [info setObject:path forKey:@"Path"];
4096 [info setObject:@"System" forKey:@"ApplicationType"];
4097 [system addInfoDictionary:info];
4103 [cache writeToFile:@Cache_ atomically:YES];
4105 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
4107 if (chmod(Cache_, info.st_mode) == -1)
4111 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4114 notify_post("com.apple.mobile.application_installed");
4116 [delegate_ setStatusBarShowsProgress:NO];
4119 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4120 [[data target] performSelector:[data selector] withObject:[data object]];
4123 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4126 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4127 UINavigationItem *item = [navbar_ topItem];
4128 [item setTitle:title];
4130 [status_ setText:nil];
4131 [output_ setText:@""];
4132 [progress_ setProgress:0];
4134 [close_ removeFromSuperview];
4135 [overlay_ addSubview:progress_];
4136 [overlay_ addSubview:status_];
4138 [delegate_ setStatusBarShowsProgress:YES];
4142 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4143 MMap mmap(file, MMap::ReadOnly);
4145 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4146 sandplate_ = sha1.Result();
4150 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4151 MMap mmap(file, MMap::ReadOnly);
4153 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4154 notifyconf_ = sha1.Result();
4158 FileFd file(SpringBoard_, FileFd::ReadOnly);
4159 MMap mmap(file, MMap::ReadOnly);
4161 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4162 springlist_ = sha1.Result();
4165 [transition_ transition:6 toView:overlay_];
4168 detachNewThreadSelector:@selector(_detachNewThreadData:)
4170 withObject:[[ProgressData alloc]
4171 initWithSelector:selector
4178 - (void) repairWithSelector:(SEL)selector {
4180 detachNewThreadSelector:selector
4183 title:CYLocalize("REPAIRING")
4187 - (void) setConfigurationData:(NSString *)data {
4189 performSelectorOnMainThread:@selector(_setConfigurationData:)
4195 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4196 Package *package = id == nil ? nil : [database_ packageWithName:id];
4198 UIActionSheet *sheet = [[[UIActionSheet alloc]
4199 initWithTitle:(package == nil ? id : [package name])
4200 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
4201 defaultButtonIndex:0
4206 [sheet setBodyText:error];
4207 [sheet popupAlertAnimated:YES];
4210 - (void) setProgressTitle:(NSString *)title {
4212 performSelectorOnMainThread:@selector(_setProgressTitle:)
4218 - (void) setProgressPercent:(float)percent {
4220 performSelectorOnMainThread:@selector(_setProgressPercent:)
4221 withObject:[NSNumber numberWithFloat:percent]
4226 - (void) startProgress {
4229 - (void) addProgressOutput:(NSString *)output {
4231 performSelectorOnMainThread:@selector(_addProgressOutput:)
4237 - (bool) isCancelling:(size_t)received {
4241 - (void) _setConfigurationData:(NSString *)data {
4242 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4244 _assert(conffile_r(data));
4246 NSString *ofile = conffile_r[1];
4247 //NSString *nfile = conffile_r[2];
4249 UIActionSheet *sheet = [[[UIActionSheet alloc]
4250 initWithTitle:CYLocalize("CONFIGURATION_UPGRADE")
4251 buttons:[NSArray arrayWithObjects:
4252 CYLocalize("KEEP_OLD_COPY"),
4253 CYLocalize("ACCEPT_NEW_COPY"),
4254 // XXX: CYLocalize("SEE_WHAT_CHANGED"),
4256 defaultButtonIndex:0
4261 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", CYLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4262 [sheet popupAlertAnimated:YES];
4265 - (void) _setProgressTitle:(NSString *)title {
4266 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4267 for (size_t i(0), e([words count]); i != e; ++i) {
4268 NSString *word([words objectAtIndex:i]);
4269 if (Package *package = [database_ packageWithName:word])
4270 [words replaceObjectAtIndex:i withObject:[package name]];
4273 [status_ setText:[words componentsJoinedByString:@" "]];
4276 - (void) _setProgressPercent:(NSNumber *)percent {
4277 [progress_ setProgress:[percent floatValue]];
4280 - (void) _addProgressOutput:(NSString *)output {
4281 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4282 CGSize size = [output_ contentSize];
4283 CGRect rect = {{0, size.height}, {size.width, 0}};
4284 [output_ scrollRectToVisible:rect animated:YES];
4287 - (BOOL) isRunning {
4294 /* Package Cell {{{ */
4295 @interface PackageCell : UITableCell {
4298 NSString *description_;
4305 UITextLabel *status_;
4309 - (PackageCell *) init;
4310 - (void) setPackage:(Package *)package;
4312 + (int) heightForPackage:(Package *)package;
4316 @implementation PackageCell
4318 - (void) clearPackage {
4329 if (description_ != nil) {
4330 [description_ release];
4334 if (source_ != nil) {
4339 if (badge_ != nil) {
4349 [self clearPackage];
4356 - (PackageCell *) init {
4357 if ((self = [super init]) != nil) {
4359 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4360 [status_ setBackgroundColor:[UIColor clearColor]];
4361 [status_ setFont:small];
4366 - (void) setPackage:(Package *)package {
4367 [self clearPackage];
4370 Source *source = [package source];
4372 icon_ = [[package icon] retain];
4373 name_ = [[package name] retain];
4374 description_ = [[package shortDescription] retain];
4375 commercial_ = [package isCommercial];
4377 package_ = [package retain];
4379 NSString *label = nil;
4380 bool trusted = false;
4382 if (source != nil) {
4383 label = [source label];
4384 trusted = [source trusted];
4385 } else if ([[package id] isEqualToString:@"firmware"])
4386 label = CYLocalize("APPLE");
4388 label = [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("UNKNOWN"), CYLocalize("LOCAL")];
4390 NSString *from(label);
4392 NSString *section = [package simpleSection];
4393 if (section != nil && ![section isEqualToString:label]) {
4394 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4395 from = [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), from, section];
4398 from = [NSString stringWithFormat:CYLocalize("FROM"), from];
4399 source_ = [from retain];
4401 if (NSString *purpose = [package primaryPurpose])
4402 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4403 badge_ = [badge_ retain];
4406 if (NSString *mode = [package mode]) {
4407 [badge_ setImage:[UIImage applicationImageNamed:
4408 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4411 [status_ setText:[NSString stringWithFormat:CYLocalize("QUEUED_FOR"), CYLocalize(mode)]];
4412 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4413 } else if ([package half]) {
4414 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4415 [status_ setText:CYLocalize("PACKAGE_DAMAGED")];
4416 [status_ setColor:[UIColor redColor]];
4418 [badge_ setImage:nil];
4419 [status_ setText:nil];
4426 - (void) drawRect:(CGRect)rect {
4430 if (NSString *mode = [package_ mode]) {
4431 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4432 color = remove ? RemovingColor_ : InstallingColor_;
4434 color = [UIColor whiteColor];
4436 [self setBackgroundColor:color];
4440 [super drawRect:rect];
4443 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4445 CGContextRef context(UIGraphicsGetCurrentContext());
4446 [[self backgroundColor] set];
4448 back.size.height -= 1;
4449 CGContextFillRect(context, back);
4452 [super drawBackgroundInRect:rect withFade:fade];
4455 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4458 rect.size = [icon_ size];
4460 rect.size.width /= 2;
4461 rect.size.height /= 2;
4463 rect.origin.x = 25 - rect.size.width / 2;
4464 rect.origin.y = 25 - rect.size.height / 2;
4466 [icon_ drawInRect:rect];
4469 if (badge_ != nil) {
4470 CGSize size = [badge_ size];
4472 [badge_ drawAtPoint:CGPointMake(
4473 36 - size.width / 2,
4474 36 - size.height / 2
4482 UISetColor(commercial_ ? Purple_ : Black_);
4483 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4484 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4487 UISetColor(commercial_ ? Purplish_ : Gray_);
4488 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4490 [super drawContentInRect:rect selected:selected];
4493 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4495 [super setSelected:selected withFade:fade];
4498 + (int) heightForPackage:(Package *)package {
4504 /* Section Cell {{{ */
4505 @interface SectionCell : UISimpleTableCell {
4510 _UISwitchSlider *switch_;
4515 - (void) setSection:(Section *)section editing:(BOOL)editing;
4519 @implementation SectionCell
4521 - (void) clearSection {
4522 if (section_ != nil) {
4532 if (count_ != nil) {
4539 [self clearSection];
4546 if ((self = [super init]) != nil) {
4547 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4549 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4550 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4554 - (void) onSwitch:(id)sender {
4555 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4556 if (metadata == nil) {
4557 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4558 [Sections_ setObject:metadata forKey:section_];
4562 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4565 - (void) setSection:(Section *)section editing:(BOOL)editing {
4566 if (editing != editing_) {
4568 [switch_ removeFromSuperview];
4570 [self addSubview:switch_];
4574 [self clearSection];
4576 if (section == nil) {
4577 name_ = [CYLocalize("ALL_PACKAGES") retain];
4580 section_ = [section localized];
4581 if (section_ != nil)
4582 section_ = [section_ retain];
4583 name_ = [(section_ == nil ? CYLocalize("NO_SECTION") : section_) retain];
4584 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4587 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4591 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4592 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4599 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4601 CGSize size = [count_ sizeWithFont:Font14_];
4605 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4607 [super drawContentInRect:rect selected:selected];
4613 /* File Table {{{ */
4614 @interface FileTable : RVPage {
4615 _transient Database *database_;
4618 NSMutableArray *files_;
4622 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4623 - (void) setPackage:(Package *)package;
4627 @implementation FileTable
4630 if (package_ != nil)
4639 - (int) numberOfRowsInTable:(UITable *)table {
4640 return files_ == nil ? 0 : [files_ count];
4643 - (float) table:(UITable *)table heightForRow:(int)row {
4647 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4648 if (reusing == nil) {
4649 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4650 UIFont *font = [UIFont systemFontOfSize:16];
4651 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4653 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4657 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4661 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4662 if ((self = [super initWithBook:book]) != nil) {
4663 database_ = database;
4665 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4667 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4668 [self addSubview:list_];
4670 UITableColumn *column = [[[UITableColumn alloc]
4671 initWithTitle:CYLocalize("NAME")
4673 width:[self frame].size.width
4676 [list_ setDataSource:self];
4677 [list_ setSeparatorStyle:1];
4678 [list_ addTableColumn:column];
4679 [list_ setDelegate:self];
4680 [list_ setReusesTableCells:YES];
4684 - (void) setPackage:(Package *)package {
4685 if (package_ != nil) {
4686 [package_ autorelease];
4695 [files_ removeAllObjects];
4697 if (package != nil) {
4698 package_ = [package retain];
4699 name_ = [[package id] retain];
4701 if (NSArray *files = [package files])
4702 [files_ addObjectsFromArray:files];
4704 if ([files_ count] != 0) {
4705 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4706 [files_ removeObjectAtIndex:0];
4707 [files_ sortUsingSelector:@selector(compareByPath:)];
4709 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4710 [stack addObject:@"/"];
4712 for (int i(0), e([files_ count]); i != e; ++i) {
4713 NSString *file = [files_ objectAtIndex:i];
4714 while (![file hasPrefix:[stack lastObject]])
4715 [stack removeLastObject];
4716 NSString *directory = [stack lastObject];
4717 [stack addObject:[file stringByAppendingString:@"/"]];
4718 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4719 ([stack count] - 2) * 3, "",
4720 [file substringFromIndex:[directory length]]
4729 - (void) resetViewAnimated:(BOOL)animated {
4730 [list_ resetViewAnimated:animated];
4733 - (void) reloadData {
4734 [self setPackage:[database_ packageWithName:name_]];
4735 [self reloadButtons];
4738 - (NSString *) title {
4739 return CYLocalize("INSTALLED_FILES");
4742 - (NSString *) backButtonTitle {
4743 return CYLocalize("FILES");
4748 /* Package View {{{ */
4749 @interface PackageView : BrowserView {
4750 _transient Database *database_;
4754 NSMutableArray *buttons_;
4757 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4758 - (void) setPackage:(Package *)package;
4762 @implementation PackageView
4765 if (package_ != nil)
4774 if ([self retainCount] == 1)
4775 [delegate_ setPackageView:self];
4779 /* XXX: this is not safe at all... localization of /fail/ */
4780 - (void) _clickButtonWithName:(NSString *)name {
4781 if ([name isEqualToString:CYLocalize("CLEAR")])
4782 [delegate_ clearPackage:package_];
4783 else if ([name isEqualToString:CYLocalize("INSTALL")])
4784 [delegate_ installPackage:package_];
4785 else if ([name isEqualToString:CYLocalize("REINSTALL")])
4786 [delegate_ installPackage:package_];
4787 else if ([name isEqualToString:CYLocalize("REMOVE")])
4788 [delegate_ removePackage:package_];
4789 else if ([name isEqualToString:CYLocalize("UPGRADE")])
4790 [delegate_ installPackage:package_];
4791 else _assert(false);
4794 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4795 NSString *context([sheet context]);
4797 if ([context isEqualToString:@"modify"]) {
4798 int count = [buttons_ count];
4799 _assert(count != 0);
4800 _assert(button <= count + 1);
4802 if (count != button - 1)
4803 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
4807 [super alertSheet:sheet buttonClicked:button];
4810 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
4811 return [super webView:sender didFinishLoadForFrame:frame];
4814 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4815 [super webView:sender didClearWindowObject:window forFrame:frame];
4816 [window setValue:package_ forKey:@"package"];
4819 - (bool) _allowJavaScriptPanel {
4824 - (void) __rightButtonClicked {
4825 int count = [buttons_ count];
4826 _assert(count != 0);
4829 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
4831 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
4832 [buttons addObjectsFromArray:buttons_];
4833 [buttons addObject:CYLocalize("CANCEL")];
4835 [delegate_ slideUp:[[[UIActionSheet alloc]
4838 defaultButtonIndex:([buttons count] - 1)
4845 - (void) _rightButtonClicked {
4847 [super _rightButtonClicked];
4849 [self __rightButtonClicked];
4853 - (id) _rightButtonTitle {
4854 int count = [buttons_ count];
4855 return count == 0 ? nil : count != 1 ? CYLocalize("MODIFY") : [buttons_ objectAtIndex:0];
4858 - (NSString *) backButtonTitle {
4862 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4863 if ((self = [super initWithBook:book]) != nil) {
4864 database_ = database;
4865 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
4866 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
4870 - (void) setPackage:(Package *)package {
4871 if (package_ != nil) {
4872 [package_ autorelease];
4881 [buttons_ removeAllObjects];
4883 if (package != nil) {
4886 package_ = [package retain];
4887 name_ = [[package id] retain];
4888 commercial_ = [package isCommercial];
4890 if ([package_ mode] != nil)
4891 [buttons_ addObject:CYLocalize("CLEAR")];
4892 if ([package_ source] == nil);
4893 else if ([package_ upgradableAndEssential:NO])
4894 [buttons_ addObject:CYLocalize("UPGRADE")];
4895 else if ([package_ installed] == nil)
4896 [buttons_ addObject:CYLocalize("INSTALL")];
4898 [buttons_ addObject:CYLocalize("REINSTALL")];
4899 if ([package_ installed] != nil)
4900 [buttons_ addObject:CYLocalize("REMOVE")];
4902 if (special_ != NULL) {
4903 CGRect frame([webview_ frame]);
4904 frame.size.width = 320;
4905 frame.size.height = 0;
4906 [webview_ setFrame:frame];
4908 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
4911 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
4913 [self setButtonTitle:nil withStyle:nil toFunction:nil];
4915 [self setFinishHook:nil];
4916 [self setPopupHook:nil];
4919 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
4920 [super callFunction:special_];
4924 [self reloadButtons];
4927 - (bool) isLoading {
4928 return commercial_ ? [super isLoading] : false;
4931 - (void) reloadData {
4932 [self setPackage:[database_ packageWithName:name_]];
4937 /* Package Table {{{ */
4938 @interface PackageTable : RVPage {
4939 _transient Database *database_;
4941 NSMutableArray *packages_;
4942 NSMutableArray *sections_;
4943 UISectionList *list_;
4946 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
4948 - (void) setDelegate:(id)delegate;
4950 - (void) reloadData;
4951 - (void) resetCursor;
4953 - (UISectionList *) list;
4955 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
4959 @implementation PackageTable
4962 [list_ setDataSource:nil];
4965 [packages_ release];
4966 [sections_ release];
4971 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
4972 return [sections_ count];
4975 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
4976 return [[sections_ objectAtIndex:section] name];
4979 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
4980 return [[sections_ objectAtIndex:section] row];
4983 - (int) numberOfRowsInTable:(UITable *)table {
4984 return [packages_ count];
4987 - (float) table:(UITable *)table heightForRow:(int)row {
4988 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
4991 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4993 reusing = [[[PackageCell alloc] init] autorelease];
4994 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
4998 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5002 - (void) tableRowSelected:(NSNotification *)notification {
5003 int row = [[notification object] selectedRow];
5007 Package *package = [packages_ objectAtIndex:row];
5008 package = [database_ packageWithName:[package id]];
5009 PackageView *view([delegate_ packageView]);
5010 [view setPackage:package];
5011 [view setDelegate:delegate_];
5012 [book_ pushPage:view];
5015 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5016 if ((self = [super initWithBook:book]) != nil) {
5017 database_ = database;
5018 title_ = [title retain];
5020 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5021 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5023 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
5024 [list_ setDataSource:self];
5026 UITableColumn *column = [[[UITableColumn alloc]
5027 initWithTitle:CYLocalize("NAME")
5029 width:[self frame].size.width
5032 UITable *table = [list_ table];
5033 [table setSeparatorStyle:1];
5034 [table addTableColumn:column];
5035 [table setDelegate:self];
5036 [table setReusesTableCells:YES];
5038 [self addSubview:list_];
5040 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5041 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5045 - (void) setDelegate:(id)delegate {
5046 delegate_ = delegate;
5049 - (bool) hasPackage:(Package *)package {
5053 - (void) reloadData {
5054 NSArray *packages = [database_ packages];
5056 [packages_ removeAllObjects];
5057 [sections_ removeAllObjects];
5059 _profile(PackageTable$reloadData$Filter)
5060 for (Package *package in packages)
5061 if ([self hasPackage:package])
5062 [packages_ addObject:package];
5065 Section *section = nil;
5067 _profile(PackageTable$reloadData$Section)
5068 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5072 _profile(PackageTable$reloadData$Section$Package)
5073 package = [packages_ objectAtIndex:offset];
5074 index = [package index];
5077 if (section == nil || [section index] != index) {
5078 _profile(PackageTable$reloadData$Section$Allocate)
5079 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5082 _profile(PackageTable$reloadData$Section$Add)
5083 [sections_ addObject:section];
5087 [section addToCount];
5091 _profile(PackageTable$reloadData$List)
5096 - (NSString *) title {
5100 - (void) resetViewAnimated:(BOOL)animated {
5101 [list_ resetViewAnimated:animated];
5104 - (void) resetCursor {
5105 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
5108 - (UISectionList *) list {
5112 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5113 [list_ setShouldHideHeaderInShortLists:hide];
5118 /* Filtered Package Table {{{ */
5119 @interface FilteredPackageTable : PackageTable {
5125 - (void) setObject:(id)object;
5127 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5131 @implementation FilteredPackageTable
5139 - (void) setObject:(id)object {
5145 object_ = [object retain];
5148 - (bool) hasPackage:(Package *)package {
5149 _profile(FilteredPackageTable$hasPackage)
5150 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5154 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5155 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5157 object_ = object == nil ? nil : [object retain];
5159 /* XXX: this is an unsafe optimization of doomy hell */
5160 Method method = class_getInstanceMethod([Package class], filter);
5161 _assert(method != NULL);
5162 imp_ = method_getImplementation(method);
5163 _assert(imp_ != NULL);
5172 /* Add Source View {{{ */
5173 @interface AddSourceView : RVPage {
5174 _transient Database *database_;
5177 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5181 @implementation AddSourceView
5183 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5184 if ((self = [super initWithBook:book]) != nil) {
5185 database_ = database;
5191 /* Source Cell {{{ */
5192 @interface SourceCell : UITableCell {
5195 NSString *description_;
5201 - (SourceCell *) initWithSource:(Source *)source;
5205 @implementation SourceCell
5210 [description_ release];
5215 - (SourceCell *) initWithSource:(Source *)source {
5216 if ((self = [super init]) != nil) {
5218 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5220 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5221 icon_ = [icon_ retain];
5223 origin_ = [[source name] retain];
5224 label_ = [[source uri] retain];
5225 description_ = [[source description] retain];
5229 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5231 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5238 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5242 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5246 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5248 [super drawContentInRect:rect selected:selected];
5253 /* Source Table {{{ */
5254 @interface SourceTable : RVPage {
5255 _transient Database *database_;
5256 UISectionList *list_;
5257 NSMutableArray *sources_;
5258 UIActionSheet *alert_;
5262 UIProgressHUD *hud_;
5265 //NSURLConnection *installer_;
5266 NSURLConnection *trivial_bz2_;
5267 NSURLConnection *trivial_gz_;
5268 //NSURLConnection *automatic_;
5273 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5277 @implementation SourceTable
5279 - (void) _deallocConnection:(NSURLConnection *)connection {
5280 if (connection != nil) {
5281 [connection cancel];
5282 //[connection setDelegate:nil];
5283 [connection release];
5288 [[list_ table] setDelegate:nil];
5289 [list_ setDataSource:nil];
5298 //[self _deallocConnection:installer_];
5299 [self _deallocConnection:trivial_gz_];
5300 [self _deallocConnection:trivial_bz2_];
5301 //[self _deallocConnection:automatic_];
5308 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5309 return offset_ == 0 ? 1 : 2;
5312 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5313 switch (section + (offset_ == 0 ? 1 : 0)) {
5314 case 0: return CYLocalize("ENTERED_BY_USER");
5315 case 1: return CYLocalize("INSTALLED_BY_PACKAGE");
5323 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5324 switch (section + (offset_ == 0 ? 1 : 0)) {
5326 case 1: return offset_;
5334 - (int) numberOfRowsInTable:(UITable *)table {
5335 return [sources_ count];
5338 - (float) table:(UITable *)table heightForRow:(int)row {
5339 Source *source = [sources_ objectAtIndex:row];
5340 return [source description] == nil ? 56 : 73;
5343 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5344 Source *source = [sources_ objectAtIndex:row];
5345 // XXX: weird warning, stupid selectors ;P
5346 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5349 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5353 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5357 - (void) tableRowSelected:(NSNotification*)notification {
5358 UITable *table([list_ table]);
5359 int row([table selectedRow]);
5363 Source *source = [sources_ objectAtIndex:row];
5365 PackageTable *packages = [[[FilteredPackageTable alloc]
5368 title:[source label]
5369 filter:@selector(isVisibleInSource:)
5373 [packages setDelegate:delegate_];
5375 [book_ pushPage:packages];
5378 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5379 Source *source = [sources_ objectAtIndex:row];
5380 return [source record] != nil;
5383 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5384 [[list_ table] setDeleteConfirmationRow:row];
5387 - (void) table:(UITable *)table deleteRow:(int)row {
5388 Source *source = [sources_ objectAtIndex:row];
5389 [Sources_ removeObjectForKey:[source key]];
5390 [delegate_ syncData];
5394 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5397 @"./", @"Distribution",
5398 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5400 [delegate_ syncData];
5403 - (NSString *) getWarning {
5404 NSString *href(href_);
5405 NSRange colon([href rangeOfString:@"://"]);
5406 if (colon.location != NSNotFound)
5407 href = [href substringFromIndex:(colon.location + 3)];
5408 href = [href stringByAddingPercentEscapes];
5409 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5410 href = [href stringByCachingURLWithCurrentCDN];
5412 NSURL *url([NSURL URLWithString:href]);
5414 NSStringEncoding encoding;
5415 NSError *error(nil);
5417 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5418 return [warning length] == 0 ? nil : warning;
5422 - (void) _endConnection:(NSURLConnection *)connection {
5423 NSURLConnection **field = NULL;
5424 if (connection == trivial_bz2_)
5425 field = &trivial_bz2_;
5426 else if (connection == trivial_gz_)
5427 field = &trivial_gz_;
5428 _assert(field != NULL);
5429 [connection release];
5433 trivial_bz2_ == nil &&
5439 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5442 UIActionSheet *sheet = [[[UIActionSheet alloc]
5443 initWithTitle:CYLocalize("SOURCE_WARNING")
5444 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_ANYWAY"), CYLocalize("CANCEL"), nil]
5445 defaultButtonIndex:0
5450 [sheet setNumberOfRows:1];
5452 [sheet setBodyText:warning];
5453 [sheet popupAlertAnimated:YES];
5456 } else if (error_ != nil) {
5457 UIActionSheet *sheet = [[[UIActionSheet alloc]
5458 initWithTitle:CYLocalize("VERIFICATION_ERROR")
5459 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5460 defaultButtonIndex:0
5465 [sheet setBodyText:[error_ localizedDescription]];
5466 [sheet popupAlertAnimated:YES];
5468 UIActionSheet *sheet = [[[UIActionSheet alloc]
5469 initWithTitle:CYLocalize("NOT_REPOSITORY")
5470 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5471 defaultButtonIndex:0
5476 [sheet setBodyText:CYLocalize("NOT_REPOSITORY_EX")];
5477 [sheet popupAlertAnimated:YES];
5480 [delegate_ setStatusBarShowsProgress:NO];
5481 [delegate_ removeProgressHUD:hud_];
5491 if (error_ != nil) {
5498 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5499 switch ([response statusCode]) {
5505 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5506 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5508 error_ = [error retain];
5509 [self _endConnection:connection];
5512 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5513 [self _endConnection:connection];
5516 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5517 NSMutableURLRequest *request = [NSMutableURLRequest
5518 requestWithURL:[NSURL URLWithString:href]
5519 cachePolicy:NSURLRequestUseProtocolCachePolicy
5520 timeoutInterval:20.0
5523 [request setHTTPMethod:method];
5525 if (Machine_ != NULL)
5526 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5527 if (UniqueID_ != nil)
5528 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5531 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5533 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5536 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5537 NSString *context([sheet context]);
5539 if ([context isEqualToString:@"source"]) {
5542 NSString *href = [[sheet textField] text];
5544 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5546 if (![href hasSuffix:@"/"])
5547 href_ = [href stringByAppendingString:@"/"];
5550 href_ = [href_ retain];
5552 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5553 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5554 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5558 hud_ = [[delegate_ addProgressHUD] retain];
5559 [hud_ setText:CYLocalize("VERIFYING_URL")];
5570 } else if ([context isEqualToString:@"trivial"])
5572 else if ([context isEqualToString:@"urlerror"])
5574 else if ([context isEqualToString:@"warning"]) {
5594 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5595 if ((self = [super initWithBook:book]) != nil) {
5596 database_ = database;
5597 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5599 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5600 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5601 [list_ setShouldHideHeaderInShortLists:NO];
5603 [self addSubview:list_];
5604 [list_ setDataSource:self];
5606 UITableColumn *column = [[UITableColumn alloc]
5607 initWithTitle:CYLocalize("NAME")
5609 width:[self frame].size.width
5612 UITable *table = [list_ table];
5613 [table setSeparatorStyle:1];
5614 [table addTableColumn:column];
5615 [table setDelegate:self];
5619 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5620 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5624 - (void) reloadData {
5626 _assert(list.ReadMainList());
5628 [sources_ removeAllObjects];
5629 [sources_ addObjectsFromArray:[database_ sources]];
5631 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5634 int count = [sources_ count];
5635 for (offset_ = 0; offset_ != count; ++offset_) {
5636 Source *source = [sources_ objectAtIndex:offset_];
5637 if ([source record] == nil)
5644 - (void) resetViewAnimated:(BOOL)animated {
5645 [list_ resetViewAnimated:animated];
5648 - (void) _leftButtonClicked {
5649 /*[book_ pushPage:[[[AddSourceView alloc]
5654 UIActionSheet *sheet = [[[UIActionSheet alloc]
5655 initWithTitle:CYLocalize("ENTER_APT_URL")
5656 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_SOURCE"), CYLocalize("CANCEL"), nil]
5657 defaultButtonIndex:0
5662 [sheet setNumberOfRows:1];
5664 [sheet addTextFieldWithValue:@"http://" label:@""];
5666 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5667 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5668 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5669 [traits setKeyboardType:UIKeyboardTypeURL];
5670 // XXX: UIReturnKeyDone
5671 [traits setReturnKeyType:UIReturnKeyNext];
5673 [sheet popupAlertAnimated:YES];
5676 - (void) _rightButtonClicked {
5677 UITable *table = [list_ table];
5678 BOOL editing = [table isRowDeletionEnabled];
5679 [table enableRowDeletion:!editing animated:YES];
5680 [book_ reloadButtonsForPage:self];
5683 - (NSString *) title {
5684 return CYLocalize("SOURCES");
5687 - (NSString *) leftButtonTitle {
5688 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("ADD") : nil;
5691 - (id) rightButtonTitle {
5692 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("DONE") : CYLocalize("EDIT");
5695 - (UINavigationButtonStyle) rightButtonStyle {
5696 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5702 /* Installed View {{{ */
5703 @interface InstalledView : RVPage {
5704 _transient Database *database_;
5705 FilteredPackageTable *packages_;
5709 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5713 @implementation InstalledView
5716 [packages_ release];
5720 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5721 if ((self = [super initWithBook:book]) != nil) {
5722 database_ = database;
5724 packages_ = [[FilteredPackageTable alloc]
5728 filter:@selector(isInstalledAndVisible:)
5729 with:[NSNumber numberWithBool:YES]
5732 [self addSubview:packages_];
5734 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5735 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5739 - (void) resetViewAnimated:(BOOL)animated {
5740 [packages_ resetViewAnimated:animated];
5743 - (void) reloadData {
5744 [packages_ reloadData];
5747 - (void) _rightButtonClicked {
5748 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5749 [packages_ reloadData];
5751 [book_ reloadButtonsForPage:self];
5754 - (NSString *) title {
5755 return CYLocalize("INSTALLED");
5758 - (NSString *) backButtonTitle {
5759 return CYLocalize("PACKAGES");
5762 - (id) rightButtonTitle {
5763 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? CYLocalize("EXPERT") : CYLocalize("SIMPLE");
5766 - (UINavigationButtonStyle) rightButtonStyle {
5767 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5770 - (void) setDelegate:(id)delegate {
5771 [super setDelegate:delegate];
5772 [packages_ setDelegate:delegate];
5779 @interface HomeView : BrowserView {
5784 @implementation HomeView
5786 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5787 NSString *context([sheet context]);
5789 if ([context isEqualToString:@"about"])
5792 [super alertSheet:sheet buttonClicked:button];
5795 - (void) _leftButtonClicked {
5796 UIActionSheet *sheet = [[[UIActionSheet alloc]
5797 initWithTitle:CYLocalize("ABOUT_CYDIA")
5798 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
5799 defaultButtonIndex:0
5805 @"Copyright (C) 2008-2009\n"
5806 "Jay Freeman (saurik)\n"
5807 "saurik@saurik.com\n"
5808 "http://www.saurik.com/\n"
5811 "http://www.theokorigroup.com/\n"
5813 "College of Creative Studies,\n"
5814 "University of California,\n"
5816 "http://www.ccs.ucsb.edu/"
5819 [sheet popupAlertAnimated:YES];
5822 - (NSString *) leftButtonTitle {
5823 return CYLocalize("ABOUT");
5828 /* Manage View {{{ */
5829 @interface ManageView : BrowserView {
5834 @implementation ManageView
5836 - (NSString *) title {
5837 return CYLocalize("MANAGE");
5840 - (void) _leftButtonClicked {
5841 [delegate_ askForSettings];
5844 - (NSString *) leftButtonTitle {
5845 return CYLocalize("SETTINGS");
5849 - (id) _rightButtonTitle {
5850 return Queuing_ ? CYLocalize("QUEUE") : nil;
5853 - (UINavigationButtonStyle) rightButtonStyle {
5854 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5857 - (void) _rightButtonClicked {
5862 - (bool) isLoading {
5869 #include <BrowserView.m>
5871 /* Cydia Book {{{ */
5872 @interface CYBook : RVBook <
5875 _transient Database *database_;
5876 UINavigationBar *overlay_;
5877 UINavigationBar *underlay_;
5878 UIProgressIndicator *indicator_;
5879 UITextLabel *prompt_;
5880 UIProgressBar *progress_;
5881 UINavigationButton *cancel_;
5885 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
5891 @implementation CYBook
5895 [indicator_ release];
5897 [progress_ release];
5902 - (NSString *) getTitleForPage:(RVPage *)page {
5903 return [super getTitleForPage:page];
5911 [UIView beginAnimations:nil context:NULL];
5913 CGRect ovrframe = [overlay_ frame];
5914 ovrframe.origin.y = 0;
5915 [overlay_ setFrame:ovrframe];
5917 CGRect barframe = [navbar_ frame];
5918 barframe.origin.y += ovrframe.size.height;
5919 [navbar_ setFrame:barframe];
5921 CGRect trnframe = [transition_ frame];
5922 trnframe.origin.y += ovrframe.size.height;
5923 trnframe.size.height -= ovrframe.size.height;
5924 [transition_ setFrame:trnframe];
5926 [UIView endAnimations];
5928 [indicator_ startAnimation];
5929 [prompt_ setText:CYLocalize("UPDATING_DATABASE")];
5930 [progress_ setProgress:0];
5933 [overlay_ addSubview:cancel_];
5936 detachNewThreadSelector:@selector(_update)
5945 [indicator_ stopAnimation];
5947 [UIView beginAnimations:nil context:NULL];
5949 CGRect ovrframe = [overlay_ frame];
5950 ovrframe.origin.y = -ovrframe.size.height;
5951 [overlay_ setFrame:ovrframe];
5953 CGRect barframe = [navbar_ frame];
5954 barframe.origin.y -= ovrframe.size.height;
5955 [navbar_ setFrame:barframe];
5957 CGRect trnframe = [transition_ frame];
5958 trnframe.origin.y -= ovrframe.size.height;
5959 trnframe.size.height += ovrframe.size.height;
5960 [transition_ setFrame:trnframe];
5962 [UIView commitAnimations];
5964 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
5967 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
5968 if ((self = [super initWithFrame:frame]) != nil) {
5969 database_ = database;
5971 CGRect ovrrect = [navbar_ bounds];
5972 ovrrect.size.height = [UINavigationBar defaultSize].height;
5973 ovrrect.origin.y = -ovrrect.size.height;
5975 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5976 [self addSubview:overlay_];
5978 ovrrect.origin.y = frame.size.height;
5979 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5980 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
5981 [self addSubview:underlay_];
5983 [overlay_ setBarStyle:1];
5984 [underlay_ setBarStyle:1];
5986 int barstyle = [overlay_ _barStyle:NO];
5987 bool ugly = barstyle == 0;
5989 UIProgressIndicatorStyle style = ugly ?
5990 UIProgressIndicatorStyleMediumBrown :
5991 UIProgressIndicatorStyleMediumWhite;
5993 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
5994 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
5995 CGRect indrect = {{indoffset, indoffset}, indsize};
5997 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
5998 [indicator_ setStyle:style];
5999 [overlay_ addSubview:indicator_];
6001 CGSize prmsize = {215, indsize.height + 4};
6004 indoffset * 2 + indsize.width,
6008 unsigned(ovrrect.size.height - prmsize.height) / 2
6011 UIFont *font = [UIFont systemFontOfSize:15];
6013 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6015 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6016 [prompt_ setBackgroundColor:[UIColor clearColor]];
6017 [prompt_ setFont:font];
6019 [overlay_ addSubview:prompt_];
6021 CGSize prgsize = {75, 100};
6024 ovrrect.size.width - prgsize.width - 10,
6025 (ovrrect.size.height - prgsize.height) / 2
6028 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6029 [progress_ setStyle:0];
6030 [overlay_ addSubview:progress_];
6032 cancel_ = [[UINavigationButton alloc] initWithTitle:CYLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6033 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6035 CGRect frame = [cancel_ frame];
6036 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6037 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6038 [cancel_ setFrame:frame];
6040 [cancel_ setBarStyle:barstyle];
6044 - (void) _onCancel {
6046 [cancel_ removeFromSuperview];
6049 - (void) _update { _pooled
6051 status.setDelegate(self);
6053 [database_ updateWithStatus:status];
6056 performSelectorOnMainThread:@selector(_update_)
6062 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
6063 [prompt_ setText:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), error]];
6066 - (void) setProgressTitle:(NSString *)title {
6068 performSelectorOnMainThread:@selector(_setProgressTitle:)
6074 - (void) setProgressPercent:(float)percent {
6076 performSelectorOnMainThread:@selector(_setProgressPercent:)
6077 withObject:[NSNumber numberWithFloat:percent]
6082 - (void) startProgress {
6085 - (void) addProgressOutput:(NSString *)output {
6087 performSelectorOnMainThread:@selector(_addProgressOutput:)
6093 - (bool) isCancelling:(size_t)received {
6097 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6101 - (void) _setProgressTitle:(NSString *)title {
6102 [prompt_ setText:title];
6105 - (void) _setProgressPercent:(NSNumber *)percent {
6106 [progress_ setProgress:[percent floatValue]];
6109 - (void) _addProgressOutput:(NSString *)output {
6114 /* Cydia:// Protocol {{{ */
6115 @interface CydiaURLProtocol : NSURLProtocol {
6120 @implementation CydiaURLProtocol
6122 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6123 NSURL *url([request URL]);
6126 NSString *scheme([[url scheme] lowercaseString]);
6127 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6132 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6136 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6137 id<NSURLProtocolClient> client([self client]);
6139 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6141 NSData *data(UIImagePNGRepresentation(icon));
6143 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6144 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6145 [client URLProtocol:self didLoadData:data];
6146 [client URLProtocolDidFinishLoading:self];
6150 - (void) startLoading {
6151 id<NSURLProtocolClient> client([self client]);
6152 NSURLRequest *request([self request]);
6154 NSURL *url([request URL]);
6155 NSString *href([url absoluteString]);
6157 NSString *path([href substringFromIndex:8]);
6158 NSRange slash([path rangeOfString:@"/"]);
6161 if (slash.location == NSNotFound) {
6165 command = [path substringToIndex:slash.location];
6166 path = [path substringFromIndex:(slash.location + 1)];
6169 Database *database([Database sharedInstance]);
6171 if ([command isEqualToString:@"package-icon"]) {
6174 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6175 Package *package([database packageWithName:path]);
6178 UIImage *icon([package icon]);
6179 [self _returnPNGWithImage:icon forRequest:request];
6180 } else if ([command isEqualToString:@"source-icon"]) {
6183 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6184 NSString *source(Simplify(path));
6185 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6187 icon = [UIImage applicationImageNamed:@"unknown.png"];
6188 [self _returnPNGWithImage:icon forRequest:request];
6189 } else if ([command isEqualToString:@"uikit-image"]) {
6192 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6193 UIImage *icon(_UIImageWithName(path));
6194 [self _returnPNGWithImage:icon forRequest:request];
6195 } else if ([command isEqualToString:@"section-icon"]) {
6198 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6199 NSString *section(Simplify(path));
6200 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6202 icon = [UIImage applicationImageNamed:@"unknown.png"];
6203 [self _returnPNGWithImage:icon forRequest:request];
6205 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6209 - (void) stopLoading {
6215 /* Sections View {{{ */
6216 @interface SectionsView : RVPage {
6217 _transient Database *database_;
6218 NSMutableArray *sections_;
6219 NSMutableArray *filtered_;
6220 UITransitionView *transition_;
6226 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6227 - (void) reloadData;
6232 @implementation SectionsView
6235 [list_ setDataSource:nil];
6236 [list_ setDelegate:nil];
6238 [sections_ release];
6239 [filtered_ release];
6240 [transition_ release];
6242 [accessory_ release];
6246 - (int) numberOfRowsInTable:(UITable *)table {
6247 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6250 - (float) table:(UITable *)table heightForRow:(int)row {
6254 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6256 reusing = [[[SectionCell alloc] init] autorelease];
6257 [(SectionCell *)reusing setSection:(editing_ ?
6258 [sections_ objectAtIndex:row] :
6259 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6260 ) editing:editing_];
6264 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6268 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6272 - (void) tableRowSelected:(NSNotification *)notification {
6273 int row = [[notification object] selectedRow];
6284 title = CYLocalize("ALL_PACKAGES");
6286 section = [filtered_ objectAtIndex:(row - 1)];
6287 name = [section name];
6290 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6293 title = CYLocalize("NO_SECTION");
6297 PackageTable *table = [[[FilteredPackageTable alloc]
6301 filter:@selector(isVisiblyUninstalledInSection:)
6305 [table setDelegate:delegate_];
6307 [book_ pushPage:table];
6310 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6311 if ((self = [super initWithBook:book]) != nil) {
6312 database_ = database;
6314 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6315 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6317 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6318 [self addSubview:transition_];
6320 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6321 [transition_ transition:0 toView:list_];
6323 UITableColumn *column = [[[UITableColumn alloc]
6324 initWithTitle:CYLocalize("NAME")
6326 width:[self frame].size.width
6329 [list_ setDataSource:self];
6330 [list_ setSeparatorStyle:1];
6331 [list_ addTableColumn:column];
6332 [list_ setDelegate:self];
6333 [list_ setReusesTableCells:YES];
6337 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6338 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6342 - (void) reloadData {
6343 NSArray *packages = [database_ packages];
6345 [sections_ removeAllObjects];
6346 [filtered_ removeAllObjects];
6349 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6350 SectionMap sections;
6351 sections.resize(64);
6353 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6357 for (Package *package in packages) {
6358 NSString *name([package section]);
6359 NSString *key(name == nil ? @"" : name);
6364 _profile(SectionsView$reloadData$Section)
6365 section = §ions[key];
6366 if (*section == nil) {
6367 _profile(SectionsView$reloadData$Section$Allocate)
6368 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6373 [*section addToCount];
6375 _profile(SectionsView$reloadData$Filter)
6376 if (![package valid] || [package installed] != nil || ![package visible])
6380 [*section addToRow];
6384 _profile(SectionsView$reloadData$Section)
6385 section = [sections objectForKey:key];
6386 if (section == nil) {
6387 _profile(SectionsView$reloadData$Section$Allocate)
6388 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6389 [sections setObject:section forKey:key];
6394 [section addToCount];
6396 _profile(SectionsView$reloadData$Filter)
6397 if (![package valid] || [package installed] != nil || ![package visible])
6407 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6408 [sections_ addObject:i->second];
6410 [sections_ addObjectsFromArray:[sections allValues]];
6413 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6415 for (Section *section in sections_) {
6416 size_t count([section row]);
6420 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6421 [section setCount:count];
6422 [filtered_ addObject:section];
6429 - (void) resetView {
6431 [self _rightButtonClicked];
6434 - (void) resetViewAnimated:(BOOL)animated {
6435 [list_ resetViewAnimated:animated];
6438 - (void) _rightButtonClicked {
6439 if ((editing_ = !editing_))
6442 [delegate_ updateData];
6443 [book_ reloadTitleForPage:self];
6444 [book_ reloadButtonsForPage:self];
6447 - (NSString *) title {
6448 return editing_ ? CYLocalize("SECTION_VISIBILITY") : CYLocalize("INSTALL_BY_SECTION");
6451 - (NSString *) backButtonTitle {
6452 return CYLocalize("SECTIONS");
6455 - (id) rightButtonTitle {
6456 return [sections_ count] == 0 ? nil : editing_ ? CYLocalize("DONE") : CYLocalize("EDIT");
6459 - (UINavigationButtonStyle) rightButtonStyle {
6460 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6463 - (UIView *) accessoryView {
6469 /* Changes View {{{ */
6470 @interface ChangesView : RVPage {
6471 _transient Database *database_;
6472 NSMutableArray *packages_;
6473 NSMutableArray *sections_;
6474 UISectionList *list_;
6478 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6479 - (void) reloadData;
6483 @implementation ChangesView
6486 [[list_ table] setDelegate:nil];
6487 [list_ setDataSource:nil];
6489 [packages_ release];
6490 [sections_ release];
6495 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6496 return [sections_ count];
6499 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6500 return [[sections_ objectAtIndex:section] name];
6503 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6504 return [[sections_ objectAtIndex:section] row];
6507 - (int) numberOfRowsInTable:(UITable *)table {
6508 return [packages_ count];
6511 - (float) table:(UITable *)table heightForRow:(int)row {
6512 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6515 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6517 reusing = [[[PackageCell alloc] init] autorelease];
6518 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6522 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6526 - (void) tableRowSelected:(NSNotification *)notification {
6527 int row = [[notification object] selectedRow];
6530 Package *package = [packages_ objectAtIndex:row];
6531 PackageView *view([delegate_ packageView]);
6532 [view setDelegate:delegate_];
6533 [view setPackage:package];
6534 [book_ pushPage:view];
6537 - (void) _leftButtonClicked {
6538 [(CYBook *)book_ update];
6539 [self reloadButtons];
6542 - (void) _rightButtonClicked {
6543 [delegate_ distUpgrade];
6546 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6547 if ((self = [super initWithBook:book]) != nil) {
6548 database_ = database;
6550 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6551 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6553 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6554 [self addSubview:list_];
6556 [list_ setShouldHideHeaderInShortLists:NO];
6557 [list_ setDataSource:self];
6558 //[list_ setSectionListStyle:1];
6560 UITableColumn *column = [[[UITableColumn alloc]
6561 initWithTitle:CYLocalize("NAME")
6563 width:[self frame].size.width
6566 UITable *table = [list_ table];
6567 [table setSeparatorStyle:1];
6568 [table addTableColumn:column];
6569 [table setDelegate:self];
6570 [table setReusesTableCells:YES];
6574 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6575 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6579 - (void) reloadData {
6580 NSArray *packages = [database_ packages];
6582 [packages_ removeAllObjects];
6583 [sections_ removeAllObjects];
6586 for (Package *package in packages)
6588 [package installed] == nil && [package valid] && [package visible] ||
6589 [package upgradableAndEssential:YES]
6591 [packages_ addObject:package];
6594 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6597 Section *upgradable = [[[Section alloc] initWithName:CYLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6598 Section *ignored = [[[Section alloc] initWithName:CYLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6599 Section *section = nil;
6603 bool unseens = false;
6605 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6607 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6608 Package *package = [packages_ objectAtIndex:offset];
6610 BOOL uae = [package upgradableAndEssential:YES];
6616 _profile(ChangesView$reloadData$Remember)
6617 seen = [package seen];
6620 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6625 name = CYLocalize("UNKNOWN");
6627 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6631 _profile(ChangesView$reloadData$Allocate)
6632 name = [NSString stringWithFormat:CYLocalize("NEW_AT"), name];
6633 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6634 [sections_ addObject:section];
6638 [section addToCount];
6639 } else if ([package ignored])
6640 [ignored addToCount];
6643 [upgradable addToCount];
6648 CFRelease(formatter);
6651 Section *last = [sections_ lastObject];
6652 size_t count = [last count];
6653 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6654 [sections_ removeLastObject];
6657 if ([ignored count] != 0)
6658 [sections_ insertObject:ignored atIndex:0];
6660 [sections_ insertObject:upgradable atIndex:0];
6663 [self reloadButtons];
6666 - (void) resetViewAnimated:(BOOL)animated {
6667 [list_ resetViewAnimated:animated];
6670 - (NSString *) leftButtonTitle {
6671 return [(CYBook *)book_ updating] ? nil : CYLocalize("REFRESH");
6674 - (id) rightButtonTitle {
6675 return upgrades_ == 0 ? nil : [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6678 - (NSString *) title {
6679 return CYLocalize("CHANGES");
6684 /* Search View {{{ */
6685 @protocol SearchViewDelegate
6686 - (void) showKeyboard:(BOOL)show;
6689 @interface SearchView : RVPage {
6691 UISearchField *field_;
6692 UITransitionView *transition_;
6693 FilteredPackageTable *table_;
6694 UIPreferencesTable *advanced_;
6700 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6701 - (void) reloadData;
6705 @implementation SearchView
6708 [field_ setDelegate:nil];
6710 [accessory_ release];
6712 [transition_ release];
6714 [advanced_ release];
6719 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6723 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6725 case 0: return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("ADVANCED_SEARCH"), CYLocalize("COMING_SOON")];
6727 default: _assert(false);
6731 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6735 default: _assert(false);
6739 - (void) _showKeyboard:(BOOL)show {
6740 CGSize keysize = [UIKeyboard defaultSize];
6741 CGRect keydown = [book_ pageBounds];
6742 CGRect keyup = keydown;
6743 keyup.size.height -= keysize.height - ButtonBarHeight_;
6745 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6747 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6748 [animation setSignificantRectFields:8];
6751 [animation setStartFrame:keydown];
6752 [animation setEndFrame:keyup];
6754 [animation setStartFrame:keyup];
6755 [animation setEndFrame:keydown];
6758 UIAnimator *animator = [UIAnimator sharedAnimator];
6761 addAnimations:[NSArray arrayWithObjects:animation, nil]
6762 withDuration:(KeyboardTime_ - delay)
6767 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6769 [delegate_ showKeyboard:show];
6772 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6773 [self _showKeyboard:YES];
6776 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
6777 [self _showKeyboard:NO];
6780 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
6782 NSString *text([field_ text]);
6783 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6789 - (void) textFieldClearButtonPressed:(UITextField *)field {
6793 - (void) keyboardInputShouldDelete:(id)input {
6797 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
6798 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6802 [field_ resignFirstResponder];
6807 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6808 if ((self = [super initWithBook:book]) != nil) {
6809 CGRect pageBounds = [book_ pageBounds];
6811 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6812 [self addSubview:transition_];
6814 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6816 [advanced_ setReusesTableCells:YES];
6817 [advanced_ setDataSource:self];
6818 [advanced_ reloadData];
6820 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6821 CGColor dimmed(space_, 0, 0, 0, 0.5);
6822 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
6824 table_ = [[FilteredPackageTable alloc]
6828 filter:@selector(isUnfilteredAndSearchedForBy:)
6832 [table_ setShouldHideHeaderInShortLists:NO];
6833 [transition_ transition:0 toView:table_];
6842 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
6849 [self bounds].size.width - area.origin.x - 18;
6851 area.size.height = [UISearchField defaultHeight];
6853 field_ = [[UISearchField alloc] initWithFrame:area];
6855 UIFont *font = [UIFont systemFontOfSize:16];
6856 [field_ setFont:font];
6858 [field_ setPlaceholder:CYLocalize("SEARCH_EX")];
6859 [field_ setDelegate:self];
6861 [field_ setPaddingTop:5];
6863 UITextInputTraits *traits([field_ textInputTraits]);
6864 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6865 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6866 [traits setReturnKeyType:UIReturnKeySearch];
6868 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
6870 accessory_ = [[UIView alloc] initWithFrame:accrect];
6871 [accessory_ addSubview:field_];
6873 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
6874 [configure setShowPressFeedback:YES];
6875 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
6876 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
6877 [accessory_ addSubview:configure];*/
6879 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6880 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6886 LKAnimation *animation = [LKTransition animation];
6887 [animation setType:@"oglFlip"];
6888 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
6889 [animation setFillMode:@"extended"];
6890 [animation setTransitionFlags:3];
6891 [animation setDuration:10];
6892 [animation setSpeed:0.35];
6893 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
6894 [[transition_ _layer] addAnimation:animation forKey:0];
6895 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
6896 flipped_ = !flipped_;
6900 - (void) configurePushed {
6901 [field_ resignFirstResponder];
6905 - (void) resetViewAnimated:(BOOL)animated {
6908 [table_ resetViewAnimated:animated];
6911 - (void) _reloadData {
6914 - (void) reloadData {
6917 [table_ setObject:[field_ text]];
6918 _profile(SearchView$reloadData)
6919 [table_ reloadData];
6922 [table_ resetCursor];
6925 - (UIView *) accessoryView {
6929 - (NSString *) title {
6933 - (NSString *) backButtonTitle {
6934 return CYLocalize("SEARCH");
6937 - (void) setDelegate:(id)delegate {
6938 [table_ setDelegate:delegate];
6939 [super setDelegate:delegate];
6945 @interface SettingsView : RVPage {
6946 _transient Database *database_;
6949 UIPreferencesTable *table_;
6950 _UISwitchSlider *subscribedSwitch_;
6951 _UISwitchSlider *ignoredSwitch_;
6952 UIPreferencesControlTableCell *subscribedCell_;
6953 UIPreferencesControlTableCell *ignoredCell_;
6956 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6960 @implementation SettingsView
6963 [table_ setDataSource:nil];
6966 if (package_ != nil)
6969 [subscribedSwitch_ release];
6970 [ignoredSwitch_ release];
6971 [subscribedCell_ release];
6972 [ignoredCell_ release];
6976 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6977 if (package_ == nil)
6983 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6984 if (package_ == nil)
6991 default: _assert(false);
6997 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
6998 if (package_ == nil)
7005 default: _assert(false);
7011 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7012 if (package_ == nil)
7019 default: _assert(false);
7025 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7026 if (package_ == nil)
7029 _UISwitchSlider *slider([cell control]);
7030 BOOL value([slider value] != 0);
7031 NSMutableDictionary *metadata([package_ metadata]);
7034 if (NSNumber *number = [metadata objectForKey:key])
7035 before = [number boolValue];
7039 if (value != before) {
7040 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7042 [delegate_ updateData];
7046 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7047 [self onSomething:cell withKey:@"IsSubscribed"];
7050 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7051 [self onSomething:cell withKey:@"IsIgnored"];
7054 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7055 if (package_ == nil)
7059 case 0: switch (row) {
7061 return subscribedCell_;
7063 return ignoredCell_;
7064 default: _assert(false);
7067 case 1: switch (row) {
7069 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7070 [cell setShowSelection:NO];
7071 [cell setTitle:CYLocalize("SHOW_ALL_CHANGES_EX")];
7075 default: _assert(false);
7078 default: _assert(false);
7084 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7085 if ((self = [super initWithBook:book])) {
7086 database_ = database;
7087 name_ = [package retain];
7089 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7090 [self addSubview:table_];
7092 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7093 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
7095 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7096 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
7098 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7099 [subscribedCell_ setShowSelection:NO];
7100 [subscribedCell_ setTitle:CYLocalize("SHOW_ALL_CHANGES")];
7101 [subscribedCell_ setControl:subscribedSwitch_];
7103 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7104 [ignoredCell_ setShowSelection:NO];
7105 [ignoredCell_ setTitle:CYLocalize("IGNORE_UPGRADES")];
7106 [ignoredCell_ setControl:ignoredSwitch_];
7108 [table_ setDataSource:self];
7113 - (void) resetViewAnimated:(BOOL)animated {
7114 [table_ resetViewAnimated:animated];
7117 - (void) reloadData {
7118 if (package_ != nil)
7119 [package_ autorelease];
7120 package_ = [database_ packageWithName:name_];
7121 if (package_ != nil) {
7123 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7124 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7127 [table_ reloadData];
7130 - (NSString *) title {
7131 return CYLocalize("SETTINGS");
7136 /* Signature View {{{ */
7137 @interface SignatureView : BrowserView {
7138 _transient Database *database_;
7142 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7146 @implementation SignatureView
7153 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7155 [super webView:sender didClearWindowObject:window forFrame:frame];
7158 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7159 if ((self = [super initWithBook:book]) != nil) {
7160 database_ = database;
7161 package_ = [package retain];
7166 - (void) resetViewAnimated:(BOOL)animated {
7169 - (void) reloadData {
7170 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7176 @interface Cydia : UIApplication <
7177 ConfirmationViewDelegate,
7178 ProgressViewDelegate,
7187 UIToolbar *buttonbar_;
7191 NSMutableArray *essential_;
7192 NSMutableArray *broken_;
7194 Database *database_;
7195 ProgressView *progress_;
7199 UIKeyboard *keyboard_;
7200 UIProgressHUD *hud_;
7202 SectionsView *sections_;
7203 ChangesView *changes_;
7204 ManageView *manage_;
7205 SearchView *search_;
7207 NSMutableArray *details_;
7212 @implementation Cydia
7215 if ([broken_ count] != 0) {
7216 int count = [broken_ count];
7218 UIActionSheet *sheet = [[[UIActionSheet alloc]
7219 initWithTitle:(count == 1 ? CYLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:CYLocalize("HALFINSTALLED_PACKAGES"), count])
7220 buttons:[NSArray arrayWithObjects:
7221 CYLocalize("FORCIBLY_CLEAR"),
7222 CYLocalize("TEMPORARY_IGNORE"),
7224 defaultButtonIndex:0
7229 [sheet setBodyText:CYLocalize("HALFINSTALLED_PACKAGE_EX")];
7230 [sheet popupAlertAnimated:YES];
7231 } else if (!Ignored_ && [essential_ count] != 0) {
7232 int count = [essential_ count];
7234 UIActionSheet *sheet = [[[UIActionSheet alloc]
7235 initWithTitle:(count == 1 ? CYLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:CYLocalize("ESSENTIAL_UPGRADES"), count])
7236 buttons:[NSArray arrayWithObjects:
7237 CYLocalize("UPGRADE_ESSENTIAL"),
7238 CYLocalize("COMPLETE_UPGRADE"),
7239 CYLocalize("TEMPORARY_IGNORE"),
7241 defaultButtonIndex:0
7246 [sheet setBodyText:CYLocalize("ESSENTIAL_UPGRADE_EX")];
7247 [sheet popupAlertAnimated:YES];
7251 - (void) _reloadData {
7254 static bool loaded(false);
7255 UIProgressHUD *hud([self addProgressHUD]);
7256 [hud setText:(loaded ? CYLocalize("RELOADING_DATA") : CYLocalize("LOADING_DATA"))];
7259 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7262 [self removeProgressHUD:hud];
7266 [essential_ removeAllObjects];
7267 [broken_ removeAllObjects];
7269 NSArray *packages = [database_ packages];
7270 for (Package *package in packages) {
7272 [broken_ addObject:package];
7273 if ([package upgradableAndEssential:NO]) {
7274 if ([package essential])
7275 [essential_ addObject:package];
7281 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7282 [buttonbar_ setBadgeValue:badge forButton:3];
7283 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7284 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7285 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7286 [self setApplicationBadge:badge];
7288 [self setApplicationBadgeString:badge];
7290 [buttonbar_ setBadgeValue:nil forButton:3];
7291 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7292 [buttonbar_ setBadgeAnimated:NO forButton:3];
7293 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7294 [self removeApplicationBadge];
7295 else // XXX: maybe use setApplicationBadgeString also?
7296 [self setApplicationIconBadgeNumber:0];
7300 [buttonbar_ setBadgeValue:nil forButton:4];
7304 // XXX: what is this line of code for?
7305 if ([packages count] == 0);
7306 else if (Loaded_ || ManualRefresh) loaded:
7311 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7312 NSTimeInterval interval([update timeIntervalSinceNow]);
7313 if (interval <= 0 && interval > -600)
7321 - (void) _saveConfig {
7324 NSString *error(nil);
7325 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7327 NSError *error(nil);
7328 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7329 NSLog(@"failure to save metadata data: %@", error);
7332 NSLog(@"failure to serialize metadata: %@", error);
7340 - (void) updateData {
7343 /* XXX: this is just stupid */
7344 if (tag_ != 2 && sections_ != nil)
7345 [sections_ reloadData];
7346 if (tag_ != 3 && changes_ != nil)
7347 [changes_ reloadData];
7348 if (tag_ != 5 && search_ != nil)
7349 [search_ reloadData];
7359 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7360 _assert(file != NULL);
7362 NSArray *keys = [Sources_ allKeys];
7364 for (NSString *key in keys) {
7365 NSDictionary *source = [Sources_ objectForKey:key];
7367 fprintf(file, "%s %s %s\n",
7368 [[source objectForKey:@"Type"] UTF8String],
7369 [[source objectForKey:@"URI"] UTF8String],
7370 [[source objectForKey:@"Distribution"] UTF8String]
7379 detachNewThreadSelector:@selector(update_)
7382 title:CYLocalize("UPDATING_SOURCES")
7386 - (void) reloadData {
7387 @synchronized (self) {
7388 if (confirm_ == nil)
7394 pkgProblemResolver *resolver = [database_ resolver];
7396 resolver->InstallProtect();
7397 if (!resolver->Resolve(true))
7401 - (void) popUpBook:(RVBook *)book {
7402 [underlay_ popSubview:book];
7405 - (CGRect) popUpBounds {
7406 return [underlay_ bounds];
7410 [database_ prepare];
7412 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7413 [confirm_ setDelegate:self];
7415 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7416 [page setDelegate:self];
7418 [confirm_ setPage:page];
7419 [self popUpBook:confirm_];
7423 @synchronized (self) {
7428 - (void) clearPackage:(Package *)package {
7429 @synchronized (self) {
7436 - (void) installPackage:(Package *)package {
7437 @synchronized (self) {
7444 - (void) removePackage:(Package *)package {
7445 @synchronized (self) {
7452 - (void) distUpgrade {
7453 @synchronized (self) {
7454 [database_ upgrade];
7460 [self slideUp:[[[UIActionSheet alloc]
7462 buttons:[NSArray arrayWithObjects:CYLocalize("CONTINUE_QUEUING"), CYLocalize("CANCEL_CLEAR"), nil]
7463 defaultButtonIndex:1
7470 @synchronized (self) {
7473 if (confirm_ != nil) {
7481 [overlay_ removeFromSuperview];
7485 detachNewThreadSelector:@selector(perform)
7488 title:CYLocalize("RUNNING")
7492 - (void) bootstrap_ {
7494 [database_ upgrade];
7495 [database_ prepare];
7496 [database_ perform];
7499 /* XXX: replace and localize */
7500 - (void) bootstrap {
7502 detachNewThreadSelector:@selector(bootstrap_)
7505 title:@"Bootstrap Install"
7509 - (void) progressViewIsComplete:(ProgressView *)progress {
7510 if (confirm_ != nil) {
7511 [underlay_ addSubview:overlay_];
7512 [confirm_ popFromSuperviewAnimated:NO];
7518 - (void) setPage:(RVPage *)page {
7519 [page resetViewAnimated:NO];
7520 [page setDelegate:self];
7521 [book_ setPage:page];
7524 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7525 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7526 [browser loadURL:url];
7530 - (void) _setHomePage {
7531 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7534 - (SectionsView *) sectionsView {
7535 if (sections_ == nil)
7536 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7540 - (void) buttonBarItemTapped:(id)sender {
7541 unsigned tag = [sender tag];
7543 [book_ resetViewAnimated:YES];
7545 } else if (tag_ == 2 && tag != 2)
7546 [[self sectionsView] resetView];
7549 case 1: [self _setHomePage]; break;
7551 case 2: [self setPage:[self sectionsView]]; break;
7552 case 3: [self setPage:changes_]; break;
7553 case 4: [self setPage:manage_]; break;
7554 case 5: [self setPage:search_]; break;
7556 default: _assert(false);
7562 - (void) applicationWillSuspend {
7564 [super applicationWillSuspend];
7567 - (void) askForSettings {
7568 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
7570 UIActionSheet *role = [[[UIActionSheet alloc]
7571 initWithTitle:CYLocalize("WHO_ARE_YOU")
7572 buttons:[NSArray arrayWithObjects:
7573 [NSString stringWithFormat:parenthetical, CYLocalize("USER"), CYLocalize("USER_EX")],
7574 [NSString stringWithFormat:parenthetical, CYLocalize("HACKER"), CYLocalize("HACKER_EX")],
7575 [NSString stringWithFormat:parenthetical, CYLocalize("DEVELOPER"), CYLocalize("DEVELOPER_EX")],
7577 defaultButtonIndex:-1
7582 [role setBodyText:CYLocalize("ROLE_EX")];
7583 [role popupAlertAnimated:YES];
7586 - (void) setPackageView:(PackageView *)view {
7588 [view setPackage:nil];
7589 if ([details_ count] < 3)
7590 [details_ addObject:view];
7594 - (PackageView *) _packageView {
7595 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7598 - (PackageView *) packageView {
7600 size_t count([details_ count]);
7603 view = [self _packageView];
7605 [details_ addObject:[self _packageView]];
7607 view = [[[details_ lastObject] retain] autorelease];
7608 [details_ removeLastObject];
7618 [self setStatusBarShowsProgress:NO];
7619 [self removeProgressHUD:hud_];
7624 pid_t pid = ExecFork();
7626 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7627 perror("launchctl stop");
7634 [self askForSettings];
7639 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7641 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7642 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7643 0, 0, screenrect.size.width, screenrect.size.height - 48
7644 ) database:database_];
7646 [book_ setDelegate:self];
7648 [overlay_ addSubview:book_];
7650 NSArray *buttonitems = [NSArray arrayWithObjects:
7651 [NSDictionary dictionaryWithObjectsAndKeys:
7652 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7653 @"home-up.png", kUIButtonBarButtonInfo,
7654 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7655 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7656 self, kUIButtonBarButtonTarget,
7657 @"Cydia", kUIButtonBarButtonTitle,
7658 @"0", kUIButtonBarButtonType,
7661 [NSDictionary dictionaryWithObjectsAndKeys:
7662 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7663 @"install-up.png", kUIButtonBarButtonInfo,
7664 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7665 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7666 self, kUIButtonBarButtonTarget,
7667 CYLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7668 @"0", kUIButtonBarButtonType,
7671 [NSDictionary dictionaryWithObjectsAndKeys:
7672 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7673 @"changes-up.png", kUIButtonBarButtonInfo,
7674 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7675 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7676 self, kUIButtonBarButtonTarget,
7677 CYLocalize("CHANGES"), kUIButtonBarButtonTitle,
7678 @"0", kUIButtonBarButtonType,
7681 [NSDictionary dictionaryWithObjectsAndKeys:
7682 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7683 @"manage-up.png", kUIButtonBarButtonInfo,
7684 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7685 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7686 self, kUIButtonBarButtonTarget,
7687 CYLocalize("MANAGE"), kUIButtonBarButtonTitle,
7688 @"0", kUIButtonBarButtonType,
7691 [NSDictionary dictionaryWithObjectsAndKeys:
7692 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7693 @"search-up.png", kUIButtonBarButtonInfo,
7694 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7695 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7696 self, kUIButtonBarButtonTarget,
7697 CYLocalize("SEARCH"), kUIButtonBarButtonTitle,
7698 @"0", kUIButtonBarButtonType,
7702 buttonbar_ = [[UIToolbar alloc]
7704 withFrame:CGRectMake(
7705 0, screenrect.size.height - ButtonBarHeight_,
7706 screenrect.size.width, ButtonBarHeight_
7708 withItemList:buttonitems
7711 [buttonbar_ setDelegate:self];
7712 [buttonbar_ setBarStyle:1];
7713 [buttonbar_ setButtonBarTrackingMode:2];
7715 int buttons[5] = {1, 2, 3, 4, 5};
7716 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7717 [buttonbar_ showButtonGroup:0 withDuration:0];
7719 for (int i = 0; i != 5; ++i)
7720 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7721 i * 64 + 2, 1, 60, ButtonBarHeight_
7724 [buttonbar_ showSelectionForButton:1];
7725 [overlay_ addSubview:buttonbar_];
7727 [UIKeyboard initImplementationNow];
7728 CGSize keysize = [UIKeyboard defaultSize];
7729 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7730 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7731 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
7732 [overlay_ addSubview:keyboard_];
7735 [underlay_ addSubview:overlay_];
7739 [self sectionsView];
7740 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7741 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7743 manage_ = (ManageView *) [[self
7744 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7745 withClass:[ManageView class]
7748 details_ = [[NSMutableArray alloc] initWithCapacity:4];
7749 [details_ addObject:[self _packageView]];
7750 [details_ addObject:[self _packageView]];
7757 [self _setHomePage];
7760 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7761 NSString *context([sheet context]);
7763 if ([context isEqualToString:@"missing"])
7765 else if ([context isEqualToString:@"cancel"]) {
7783 @synchronized (self) {
7788 [buttonbar_ setBadgeValue:CYLocalize("Q_D") forButton:4];
7792 if (confirm_ != nil) {
7797 } else if ([context isEqualToString:@"fixhalf"]) {
7800 @synchronized (self) {
7801 for (Package *broken in broken_) {
7804 NSString *id = [broken id];
7805 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7806 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7807 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7808 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7817 [broken_ removeAllObjects];
7826 } else if ([context isEqualToString:@"role"]) {
7828 case 1: Role_ = @"User"; break;
7829 case 2: Role_ = @"Hacker"; break;
7830 case 3: Role_ = @"Developer"; break;
7837 bool reset = Settings_ != nil;
7839 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7843 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7853 } else if ([context isEqualToString:@"upgrade"]) {
7856 @synchronized (self) {
7857 for (Package *essential in essential_)
7858 [essential install];
7881 - (void) reorganize { _pooled
7882 system("/usr/libexec/cydia/free.sh");
7883 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
7886 - (void) applicationSuspend:(__GSEvent *)event {
7887 if (hud_ == nil && ![progress_ isRunning])
7888 [super applicationSuspend:event];
7891 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7893 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7896 - (void) _setSuspended:(BOOL)value {
7898 [super _setSuspended:value];
7901 - (UIProgressHUD *) addProgressHUD {
7902 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
7903 [window_ setUserInteractionEnabled:NO];
7905 [progress_ addSubview:hud];
7909 - (void) removeProgressHUD:(UIProgressHUD *)hud {
7911 [hud removeFromSuperview];
7912 [window_ setUserInteractionEnabled:YES];
7915 - (void) openMailToURL:(NSURL *)url {
7916 // XXX: this makes me sad
7918 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
7920 [UIApp openURL:url];// asPanel:YES];
7924 - (void) clearFirstResponder {
7925 if (id responder = [window_ firstResponder])
7926 [responder resignFirstResponder];
7929 - (RVPage *) pageForPackage:(NSString *)name {
7930 if (Package *package = [database_ packageWithName:name]) {
7931 PackageView *view([self packageView]);
7932 [view setPackage:package];
7935 UIActionSheet *sheet = [[[UIActionSheet alloc]
7936 initWithTitle:CYLocalize("CANNOT_LOCATE_PACKAGE")
7937 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
7938 defaultButtonIndex:0
7943 [sheet setBodyText:[NSString stringWithFormat:CYLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
7945 [sheet popupAlertAnimated:YES];
7950 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
7954 NSString *scheme([[url scheme] lowercaseString]);
7955 if (![scheme isEqualToString:@"cydia"])
7957 NSString *path([url absoluteString]);
7958 if ([path length] < 8)
7960 path = [path substringFromIndex:8];
7961 if (![path hasPrefix:@"/"])
7962 path = [@"/" stringByAppendingString:path];
7964 if ([path isEqualToString:@"/add-source"])
7965 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
7966 else if ([path isEqualToString:@"/storage"])
7967 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[BrowserView class]];
7968 else if ([path isEqualToString:@"/sources"])
7969 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
7970 else if ([path isEqualToString:@"/packages"])
7971 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
7972 else if ([path hasPrefix:@"/url/"])
7973 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[BrowserView class]];
7974 else if ([path hasPrefix:@"/launch/"])
7975 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
7976 else if ([path hasPrefix:@"/package-settings/"])
7977 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
7978 else if ([path hasPrefix:@"/package-signature/"])
7979 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
7980 else if ([path hasPrefix:@"/package/"])
7981 return [self pageForPackage:[path substringFromIndex:9]];
7982 else if ([path hasPrefix:@"/files/"]) {
7983 NSString *name = [path substringFromIndex:7];
7985 if (Package *package = [database_ packageWithName:name]) {
7986 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
7987 [files setPackage:package];
7995 - (void) applicationOpenURL:(NSURL *)url {
7996 [super applicationOpenURL:url];
7998 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
7999 [self setPage:page];
8000 [buttonbar_ showSelectionForButton:tag];
8005 - (void) applicationDidFinishLaunching:(id)unused {
8007 Font12_ = [[UIFont systemFontOfSize:12] retain];
8008 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8009 Font14_ = [[UIFont systemFontOfSize:14] retain];
8010 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8011 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8015 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8016 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8018 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8020 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8021 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
8023 [window_ orderFront:self];
8024 [window_ makeKey:self];
8025 [window_ setHidden:NO];
8027 database_ = [Database sharedInstance];
8028 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8029 [database_ setDelegate:progress_];
8030 [window_ setContentView:progress_];
8032 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8033 [progress_ setContentView:underlay_];
8035 [progress_ resetView];
8038 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8039 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8040 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8041 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8042 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8043 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
8044 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
8046 [self setIdleTimerDisabled:YES];
8048 hud_ = [[self addProgressHUD] retain];
8049 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8051 [self setStatusBarShowsProgress:YES];
8054 detachNewThreadSelector:@selector(reorganize)
8062 - (void) showKeyboard:(BOOL)show {
8063 CGSize keysize = [UIKeyboard defaultSize];
8064 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8065 CGRect keyup = keydown;
8066 keyup.origin.y -= keysize.height;
8068 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
8069 [animation setSignificantRectFields:2];
8072 [animation setStartFrame:keydown];
8073 [animation setEndFrame:keyup];
8074 [keyboard_ activate];
8076 [animation setStartFrame:keyup];
8077 [animation setEndFrame:keydown];
8078 [keyboard_ deactivate];
8081 [[UIAnimator sharedAnimator]
8082 addAnimations:[NSArray arrayWithObjects:animation, nil]
8083 withDuration:KeyboardTime_
8088 - (void) slideUp:(UIActionSheet *)alert {
8090 [alert presentSheetFromButtonBar:buttonbar_];
8092 [alert presentSheetInView:overlay_];
8097 void AddPreferences(NSString *plist) { _pooled
8098 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
8099 _assert(settings != NULL);
8100 NSMutableArray *items = [settings objectForKey:@"items"];
8104 for (NSMutableDictionary *item in items) {
8105 NSString *label = [item objectForKey:@"label"];
8106 if (label != nil && [label isEqualToString:@"Cydia"]) {
8113 for (size_t i(0); i != [items count]; ++i) {
8114 NSDictionary *item([items objectAtIndex:i]);
8115 NSString *label = [item objectForKey:@"label"];
8116 if (label != nil && [label isEqualToString:@"General"]) {
8117 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
8118 @"CydiaSettings", @"bundle",
8119 @"PSLinkCell", @"cell",
8120 [NSNumber numberWithBool:YES], @"hasIcon",
8121 [NSNumber numberWithBool:YES], @"isController",
8123 nil] atIndex:(i + 1)];
8129 _assert([settings writeToFile:plist atomically:YES] == YES);
8134 id Alloc_(id self, SEL selector) {
8135 id object = alloc_(self, selector);
8136 lprintf("[%s]A-%p\n", self->isa->name, object);
8141 id Dealloc_(id self, SEL selector) {
8142 id object = dealloc_(self, selector);
8143 lprintf("[%s]D-%p\n", self->isa->name, object);
8147 Class $WebDefaultUIKitDelegate;
8149 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
8151 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
8152 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8153 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8154 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
8157 int main(int argc, char *argv[]) { _pooled
8160 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8162 /* Library Hacks {{{ */
8163 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8165 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8166 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8167 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8168 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8169 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8172 /* Set Locale {{{ */
8173 Locale_ = CFLocaleCopyCurrent();
8174 Languages_ = [NSLocale preferredLanguages];
8175 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8176 //NSLog(@"%@", [Languages_ description]);
8178 if (Languages_ == nil || [Languages_ count] == 0)
8181 lang = [[Languages_ objectAtIndex:0] UTF8String];
8182 setenv("LANG", lang, true);
8183 //std::setlocale(LC_ALL, lang);
8184 NSLog(@"Setting Language: %s", lang);
8187 // XXX: apr_app_initialize?
8190 /* Parse Arguments {{{ */
8191 bool substrate(false);
8197 for (int argi(1); argi != argc; ++argi)
8198 if (strcmp(argv[argi], "--") == 0) {
8200 argv[argi] = argv[0];
8206 for (int argi(1); argi != arge; ++argi)
8207 if (strcmp(args[argi], "--bootstrap") == 0)
8209 else if (strcmp(args[argi], "--substrate") == 0)
8212 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8217 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
8218 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
8219 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
8220 Sounds_Keyboard_ = [keyboard boolValue];
8223 App_ = [[NSBundle mainBundle] bundlePath];
8224 Home_ = NSHomeDirectory();
8229 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8230 alloc_ = alloc->method_imp;
8231 alloc->method_imp = (IMP) &Alloc_;*/
8233 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8234 dealloc_ = dealloc->method_imp;
8235 dealloc->method_imp = (IMP) &Dealloc_;*/
8240 size = sizeof(maxproc);
8241 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8242 perror("sysctlbyname(\"kern.maxproc\", ?)");
8243 else if (maxproc < 64) {
8245 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8246 perror("sysctlbyname(\"kern.maxproc\", #)");
8249 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8250 char *machine = new char[size];
8251 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8252 perror("sysctlbyname(\"hw.machine\", ?)");
8256 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8258 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8259 Build_ = [system objectForKey:@"ProductBuildVersion"];
8260 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8261 Product_ = [info objectForKey:@"SafariProductVersion"];
8262 Safari_ = [info objectForKey:@"CFBundleVersion"];
8265 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8266 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
8268 /* Load Database {{{ */
8270 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8272 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8275 if (Metadata_ == NULL)
8276 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8278 Settings_ = [Metadata_ objectForKey:@"Settings"];
8280 Packages_ = [Metadata_ objectForKey:@"Packages"];
8281 Sections_ = [Metadata_ objectForKey:@"Sections"];
8282 Sources_ = [Metadata_ objectForKey:@"Sources"];
8285 if (Settings_ != nil)
8286 Role_ = [Settings_ objectForKey:@"Role"];
8288 if (Packages_ == nil) {
8289 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8290 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8293 if (Sections_ == nil) {
8294 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8295 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8298 if (Sources_ == nil) {
8299 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8300 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8305 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8308 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8309 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8310 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8311 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8313 if (access("/User", F_OK) != 0) {
8315 system("/usr/libexec/cydia/firmware.sh");
8319 _assert([[NSFileManager defaultManager]
8320 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8321 withIntermediateDirectories:YES
8326 if (access("/tmp/cydia.chk", F_OK) == 0) {
8327 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8328 _assert(errno == ENOENT);
8329 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8330 _assert(errno == ENOENT);
8333 _assert(pkgInitConfig(*_config));
8334 _assert(pkgInitSystem(*_config, _system));
8337 _config->Set("APT::Acquire::Translation", lang);
8338 _config->Set("Acquire::http::Timeout", 15);
8339 _config->Set("Acquire::http::MaxParallel", 4);
8341 /* Color Choices {{{ */
8342 space_ = CGColorSpaceCreateDeviceRGB();
8344 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8345 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8346 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8347 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8348 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8349 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8350 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8351 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8352 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8353 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8354 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8355 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8356 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8357 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8358 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8361 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8362 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8365 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8367 /* UIKit Configuration {{{ */
8368 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8369 if ($GSFontSetUseLegacyFontMetrics != NULL)
8370 $GSFontSetUseLegacyFontMetrics(YES);
8372 UIKeyboardDisableAutomaticAppearance();
8376 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8378 CGColorSpaceRelease(space_);