1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008 Jay Freeman (saurik)
6 * Redistribution and use in source and binary
7 * forms, with or without modification, are permitted
8 * provided that the following conditions are met:
10 * 1. Redistributions of source code must retain the
11 * above copyright notice, this list of conditions
12 * and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the
14 * above copyright notice, this list of conditions
15 * and the following disclaimer in the documentation
16 * and/or other materials provided with the
18 * 3. The name of the author may not be used to endorse
19 * or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
23 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
24 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
28 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
30 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
33 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
35 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 // XXX: wtf/FastMalloc.h... wtf?
39 #define USE_SYSTEM_MALLOC 1
41 /* #include Directives {{{ */
42 #import "UICaboodle.h"
44 #include <objc/message.h>
45 #include <objc/objc.h>
46 #include <objc/runtime.h>
48 #include <CoreGraphics/CoreGraphics.h>
49 #include <GraphicsServices/GraphicsServices.h>
50 #include <Foundation/Foundation.h>
53 #define DEPLOYMENT_TARGET_MACOSX 1
54 #define CF_BUILDING_CF 1
55 #include <CoreFoundation/CFInternal.h>
58 #include <CoreFoundation/CFPriv.h>
59 #include <CoreFoundation/CFUniChar.h>
61 #import <QuartzCore/CALayer.h>
62 #import <UIKit/UIKit.h>
64 #include <WebCore/WebCoreThread.h>
65 #import <WebKit/WebDefaultUIKitDelegate.h>
72 #include <ext/stdio_filebuf.h>
74 #include <apt-pkg/acquire.h>
75 #include <apt-pkg/acquire-item.h>
76 #include <apt-pkg/algorithms.h>
77 #include <apt-pkg/cachefile.h>
78 #include <apt-pkg/clean.h>
79 #include <apt-pkg/configuration.h>
80 #include <apt-pkg/debindexfile.h>
81 #include <apt-pkg/debmetaindex.h>
82 #include <apt-pkg/error.h>
83 #include <apt-pkg/init.h>
84 #include <apt-pkg/mmap.h>
85 #include <apt-pkg/pkgrecords.h>
86 #include <apt-pkg/sha1.h>
87 #include <apt-pkg/sourcelist.h>
88 #include <apt-pkg/sptr.h>
89 #include <apt-pkg/strutl.h>
91 #include <apr-1/apr_pools.h>
93 #include <sys/types.h>
95 #include <sys/sysctl.h>
96 #include <sys/param.h>
97 #include <sys/mount.h>
103 #include <mach-o/nlist.h>
113 #include <ext/hash_map>
115 #import "BrowserView.h"
116 #import "ResetView.h"
118 #import "substrate.h"
121 //#define _finline __attribute__((force_inline))
122 #define _finline inline
127 #define _limit(count) do { \
128 static size_t _count(0); \
129 if (++_count == count) \
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
199 /* Objective-C Handle<> {{{ */
200 template <typename Type_>
202 typedef _H<Type_> This_;
207 _finline void Retain_() {
212 _finline void Clear_() {
218 _finline _H(Type_ *value = NULL, bool mended = false) :
229 _finline This_ &operator =(Type_ *value) {
230 if (value_ != value) {
239 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
241 void NSLogPoint(const char *fix, const CGPoint &point) {
242 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
245 void NSLogRect(const char *fix, const CGRect &rect) {
246 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
249 @interface NSObject (Cydia)
250 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
251 - (id) yieldToSelector:(SEL)selector;
254 @implementation NSObject (Cydia)
259 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
260 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
261 id object([[context objectAtIndex:1] nonretainedObjectValue]);
262 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
264 /* XXX: deal with exceptions */
265 id value([self performSelector:selector withObject:object]);
267 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
268 [context removeAllObjects];
269 if ([signature methodReturnLength] != 0 && value != nil)
270 [context addObject:value];
275 performSelectorOnMainThread:@selector(doNothing)
281 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
282 /*return [self performSelector:selector withObject:object];*/
284 volatile bool stopped(false);
286 NSMutableArray *context([NSMutableArray arrayWithObjects:
287 [NSValue valueWithPointer:selector],
288 [NSValue valueWithNonretainedObject:object],
289 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
292 NSThread *thread([[[NSThread alloc]
294 selector:@selector(_yieldToContext:)
300 NSRunLoop *loop([NSRunLoop currentRunLoop]);
301 NSDate *future([NSDate distantFuture]);
303 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
305 return [context count] == 0 ? nil : [context objectAtIndex:0];
308 - (id) yieldToSelector:(SEL)selector {
309 return [self yieldToSelector:selector withObject:nil];
314 /* NSForcedOrderingSearch doesn't work on the iPhone */
315 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
316 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
317 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
319 /* iPhoneOS 2.0 Compatibility {{{ */
321 @interface UITextView (iPhoneOS)
322 - (void) setTextSize:(float)size;
325 @implementation UITextView (iPhoneOS)
327 - (void) setTextSize:(float)size {
328 [self setFont:[[self font] fontWithSize:size]];
335 extern NSString * const kCAFilterNearest;
337 /* Information Dictionaries {{{ */
338 @interface NSMutableArray (Cydia)
339 - (void) addInfoDictionary:(NSDictionary *)info;
342 @implementation NSMutableArray (Cydia)
344 - (void) addInfoDictionary:(NSDictionary *)info {
345 [self addObject:info];
350 @interface NSMutableDictionary (Cydia)
351 - (void) addInfoDictionary:(NSDictionary *)info;
354 @implementation NSMutableDictionary (Cydia)
356 - (void) addInfoDictionary:(NSDictionary *)info {
357 NSString *bundle = [info objectForKey:@"CFBundleIdentifier"];
358 [self setObject:info forKey:bundle];
363 /* Pop Transitions {{{ */
364 @interface PopTransitionView : UITransitionView {
369 @implementation PopTransitionView
371 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
372 if (from != nil && to == nil)
373 [self removeFromSuperview];
378 @implementation UIView (PopUpView)
380 - (void) popFromSuperviewAnimated:(BOOL)animated {
381 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
384 - (void) popSubview:(UIView *)view {
385 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
386 [transition setDelegate:transition];
387 [self addSubview:transition];
389 UIView *blank = [[[UIView alloc] initWithFrame:[transition bounds]] autorelease];
390 [transition transition:UITransitionNone toView:blank];
391 [transition transition:UITransitionPushFromBottom toView:view];
397 #define lprintf(args...) fprintf(stderr, args)
400 #define ForSaurik (0 && !ForRelease)
401 #define LogBrowser (0 && !ForRelease)
402 #define TrackResize (0 && !ForRelease)
403 #define ManualRefresh (1 && !ForRelease)
404 #define ShowInternals (0 && !ForRelease)
405 #define IgnoreInstall (0 && !ForRelease)
406 #define RecycleWebViews 0
407 #define AlwaysReload (1 && !ForRelease)
411 #define _trace(args...)
413 #define _profile(name) {
416 #define PrintTimes() do {} while (false)
420 typedef uint32_t (*SKRadixFunction)(id, void *);
422 @interface NSMutableArray (Radix)
423 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
424 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
432 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
433 struct RadixItem_ *lhs(swap), *rhs(swap + count);
435 static const size_t width = 32;
436 static const size_t bits = 11;
437 static const size_t slots = 1 << bits;
438 static const size_t passes = (width + (bits - 1)) / bits;
440 size_t *hist(new size_t[slots]);
442 for (size_t pass(0); pass != passes; ++pass) {
443 memset(hist, 0, sizeof(size_t) * slots);
445 for (size_t i(0); i != count; ++i) {
446 uint32_t key(lhs[i].key);
448 key &= _not(uint32_t) >> width - bits;
453 for (size_t i(0); i != slots; ++i) {
454 size_t local(offset);
459 for (size_t i(0); i != count; ++i) {
460 uint32_t key(lhs[i].key);
462 key &= _not(uint32_t) >> width - bits;
463 rhs[hist[key]++] = lhs[i];
466 RadixItem_ *tmp(lhs);
473 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
474 for (size_t i(0); i != count; ++i)
475 [values addObject:[self objectAtIndex:lhs[i].index]];
476 [self setArray:values];
481 @implementation NSMutableArray (Radix)
483 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
484 size_t count([self count]);
489 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
490 [invocation setSelector:selector];
491 [invocation setArgument:&object atIndex:2];
493 /* XXX: this is an unsafe optimization of doomy hell */
494 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
495 _assert(method != NULL);
496 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
497 _assert(imp != NULL);
500 struct RadixItem_ *swap(new RadixItem_[count * 2]);
502 for (size_t i(0); i != count; ++i) {
503 RadixItem_ &item(swap[i]);
506 id object([self objectAtIndex:i]);
509 [invocation setTarget:object];
511 [invocation getReturnValue:&item.key];
513 item.key = imp(object, selector, object);
517 RadixSort_(self, count, swap);
520 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
521 size_t count([self count]);
522 struct RadixItem_ *swap(new RadixItem_[count * 2]);
524 for (size_t i(0); i != count; ++i) {
525 RadixItem_ &item(swap[i]);
528 id object([self objectAtIndex:i]);
529 item.key = function(object, argument);
532 RadixSort_(self, count, swap);
537 /* Insertion Sort {{{ */
539 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
540 const char *ptr = (const char *)list;
542 CFIndex half = count / 2;
543 const char *probe = ptr + elementSize * half;
544 CFComparisonResult cr = comparator(element, probe, context);
545 if (0 == cr) return (probe - (const char *)list) / elementSize;
546 ptr = (cr < 0) ? ptr : probe + elementSize;
547 count = (cr < 0) ? half : (half + (count & 1) - 1);
549 return (ptr - (const char *)list) / elementSize;
552 CFIndex CFBSearch_(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 #define HistogramInsertionSort 1
567 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
568 if (range.length == 0)
570 const void **values(new const void *[range.length]);
571 CFArrayGetValues(array, range, values);
573 #if HistogramInsertionSort
574 uint32_t total(0), *offsets(new uint32_t[range.length]);
577 for (CFIndex index(1); index != range.length; ++index) {
578 const void *value(values[index]);
579 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
580 CFIndex correct(index);
581 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
584 if (correct != index) {
585 size_t offset(index - correct);
586 #if HistogramInsertionSort
590 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
592 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
593 values[correct] = value;
597 CFArrayReplaceValues(array, range, values, range.length);
600 #if HistogramInsertionSort
601 for (CFIndex index(0); index != range.length; ++index)
602 if (offsets[index] != 0)
603 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
604 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
611 /* Apple Bug Fixes {{{ */
612 @implementation UIWebDocumentView (Cydia)
614 - (void) _setScrollerOffset:(CGPoint)offset {
615 UIScroller *scroller([self _scroller]);
617 CGSize size([scroller contentSize]);
618 CGSize bounds([scroller bounds].size);
621 max.x = size.width - bounds.width;
622 max.y = size.height - bounds.height;
630 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
631 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
633 [scroller setOffset:offset];
640 kUIControlEventMouseDown = 1 << 0,
641 kUIControlEventMouseMovedInside = 1 << 2, // mouse moved inside control target
642 kUIControlEventMouseMovedOutside = 1 << 3, // mouse moved outside control target
643 kUIControlEventMouseUpInside = 1 << 6, // mouse up inside control target
644 kUIControlEventMouseUpOutside = 1 << 7, // mouse up outside control target
645 kUIControlAllEvents = (kUIControlEventMouseDown | kUIControlEventMouseMovedInside | kUIControlEventMouseMovedOutside | kUIControlEventMouseUpInside | kUIControlEventMouseUpOutside)
646 } UIControlEventMasks;
648 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
649 size_t length([self length] - state->state);
652 else if (length > count)
654 for (size_t i(0); i != length; ++i)
655 objects[i] = [self item:state->state++];
656 state->itemsPtr = objects;
657 state->mutationsPtr = (unsigned long *) self;
661 @interface NSString (UIKit)
662 - (NSString *) stringByAddingPercentEscapes;
663 - (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
666 @interface NSString (Cydia)
667 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
668 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
669 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
670 - (NSComparisonResult) compareByPath:(NSString *)other;
671 - (NSString *) stringByCachingURLWithCurrentCDN;
672 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
675 @implementation NSString (Cydia)
677 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
678 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
681 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
682 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
683 memcpy(data, bytes, length);
684 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
687 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
688 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
691 - (NSComparisonResult) compareByPath:(NSString *)other {
692 NSString *prefix = [self commonPrefixWithString:other options:0];
693 size_t length = [prefix length];
695 NSRange lrange = NSMakeRange(length, [self length] - length);
696 NSRange rrange = NSMakeRange(length, [other length] - length);
698 lrange = [self rangeOfString:@"/" options:0 range:lrange];
699 rrange = [other rangeOfString:@"/" options:0 range:rrange];
701 NSComparisonResult value;
703 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
704 value = NSOrderedSame;
705 else if (lrange.location == NSNotFound)
706 value = NSOrderedAscending;
707 else if (rrange.location == NSNotFound)
708 value = NSOrderedDescending;
710 value = NSOrderedSame;
712 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
713 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
714 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
715 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
717 NSComparisonResult result = [lpath compare:rpath];
718 return result == NSOrderedSame ? value : result;
721 - (NSString *) stringByCachingURLWithCurrentCDN {
723 stringByReplacingOccurrencesOfString:@"://"
724 withString:@"://ne.edgecastcdn.net/8003A4/"
726 /* XXX: this is somewhat inaccurate */
727 range:NSMakeRange(0, 10)
731 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
732 return [(id)CFURLCreateStringByAddingPercentEscapes(
737 kCFStringEncodingUTF8
743 static inline NSString *CYLocalizeEx(NSString *key, NSString *value = nil) {
744 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:nil];
747 #define CYLocalize(key) CYLocalizeEx(@ key)
755 _finline void clear_() {
761 _finline bool empty() const {
765 _finline size_t size() const {
769 _finline char *data() const {
773 _finline void clear() {
778 _finline CYString() :
785 _finline ~CYString() {
789 void operator =(const CYString &rhs) {
793 if (rhs.cache_ == nil)
796 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
799 void set(apr_pool_t *pool, const char *data, size_t size) {
805 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
806 memcpy(temp, data, size);
813 _finline void set(apr_pool_t *pool, const char *data) {
814 set(pool, data, data == NULL ? 0 : strlen(data));
817 _finline void set(apr_pool_t *pool, const std::string &rhs) {
818 set(pool, rhs.data(), rhs.size());
821 bool operator ==(const CYString &rhs) const {
822 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
825 operator CFStringRef() {
826 if (cache_ == NULL) {
829 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
833 _finline operator id() {
834 return (NSString *) static_cast<CFStringRef>(*this);
839 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
842 struct NSStringMapHash :
843 std::unary_function<NSString *, size_t>
845 _finline size_t operator ()(NSString *value) const {
846 return CFStringHashNSString((CFStringRef) value);
850 struct NSStringMapLess :
851 std::binary_function<NSString *, NSString *, bool>
853 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
854 return [lhs compare:rhs] == NSOrderedAscending;
858 struct NSStringMapEqual :
859 std::binary_function<NSString *, NSString *, bool>
861 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
862 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
863 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
864 //[lhs isEqualToString:rhs];
868 /* Perl-Compatible RegEx {{{ */
878 Pcre(const char *regex) :
883 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
886 lprintf("%d:%s\n", offset, error);
890 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
891 matches_ = new int[(capture_ + 1) * 3];
899 NSString *operator [](size_t match) {
900 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
903 bool operator ()(NSString *data) {
904 // XXX: length is for characters, not for bytes
905 return operator ()([data UTF8String], [data length]);
908 bool operator ()(const char *data, size_t size) {
910 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
914 /* Mime Addresses {{{ */
915 @interface Address : NSObject {
921 - (NSString *) address;
923 - (void) setAddress:(NSString *)address;
925 + (Address *) addressWithString:(NSString *)string;
926 - (Address *) initWithString:(NSString *)string;
929 @implementation Address
938 - (NSString *) name {
942 - (NSString *) address {
946 - (void) setAddress:(NSString *)address {
948 [address_ autorelease];
952 address_ = [address retain];
955 + (Address *) addressWithString:(NSString *)string {
956 return [[[Address alloc] initWithString:string] autorelease];
959 + (NSArray *) _attributeKeys {
960 return [NSArray arrayWithObjects:@"address", @"name", nil];
963 - (NSArray *) attributeKeys {
964 return [[self class] _attributeKeys];
967 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
968 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
971 - (Address *) initWithString:(NSString *)string {
972 if ((self = [super init]) != nil) {
973 const char *data = [string UTF8String];
974 size_t size = [string length];
976 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
978 if (address_r(data, size)) {
979 name_ = [address_r[1] retain];
980 address_ = [address_r[2] retain];
982 name_ = [string retain];
990 /* CoreGraphics Primitives {{{ */
1001 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
1004 Set(space, red, green, blue, alpha);
1009 CGColorRelease(color_);
1016 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1018 float color[] = {red, green, blue, alpha};
1019 color_ = CGColorCreate(space, color);
1022 operator CGColorRef() {
1028 extern "C" void UISetColor(CGColorRef color);
1030 /* Random Global Variables {{{ */
1031 static const int PulseInterval_ = 50000;
1032 static const int ButtonBarHeight_ = 48;
1033 static const float KeyboardTime_ = 0.3f;
1035 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1036 #define SandboxTemplate_ "/usr/share/sandbox/SandboxTemplate.sb"
1037 #define NotifyConfig_ "/etc/notify.conf"
1039 static bool Queuing_;
1041 static CGColor Blue_;
1042 static CGColor Blueish_;
1043 static CGColor Black_;
1044 static CGColor Off_;
1045 static CGColor White_;
1046 static CGColor Gray_;
1047 static CGColor Green_;
1048 static CGColor Purple_;
1049 static CGColor Purplish_;
1051 static UIColor *InstallingColor_;
1052 static UIColor *RemovingColor_;
1054 static NSString *App_;
1055 static NSString *Home_;
1056 static BOOL Sounds_Keyboard_;
1058 static BOOL Advanced_;
1059 static BOOL Loaded_;
1060 static BOOL Ignored_;
1062 static UIFont *Font12_;
1063 static UIFont *Font12Bold_;
1064 static UIFont *Font14_;
1065 static UIFont *Font18Bold_;
1066 static UIFont *Font22Bold_;
1068 static const char *Machine_ = NULL;
1069 static const NSString *UniqueID_ = nil;
1070 static const NSString *Build_ = nil;
1071 static const NSString *Product_ = nil;
1072 static const NSString *Safari_ = nil;
1074 CFLocaleRef Locale_;
1075 NSArray *Languages_;
1076 CGColorSpaceRef space_;
1081 static NSDictionary *SectionMap_;
1082 static NSMutableDictionary *Metadata_;
1083 static _transient NSMutableDictionary *Settings_;
1084 static _transient NSString *Role_;
1085 static _transient NSMutableDictionary *Packages_;
1086 static _transient NSMutableDictionary *Sections_;
1087 static _transient NSMutableDictionary *Sources_;
1088 static bool Changed_;
1089 static NSDate *now_;
1092 static NSMutableArray *Documents_;
1095 NSString *GetLastUpdate() {
1096 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1099 return CYLocalize("NEVER_OR_UNKNOWN");
1101 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1102 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1104 CFRelease(formatter);
1106 return [(NSString *) formatted autorelease];
1109 /* Display Helpers {{{ */
1110 inline float Interpolate(float begin, float end, float fraction) {
1111 return (end - begin) * fraction + begin;
1114 /* XXX: localize this! */
1115 NSString *SizeString(double size) {
1116 bool negative = size < 0;
1121 while (size > 1024) {
1126 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1128 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1131 NSString *StripVersion(const char *version) {
1132 const char *colon(strchr(version, ':'));
1134 version = colon + 1;
1135 return [NSString stringWithUTF8String:version];
1138 NSString *StripVersion(NSString *version) {
1139 NSRange colon = [version rangeOfString:@":"];
1140 if (colon.location != NSNotFound)
1141 version = [version substringFromIndex:(colon.location + 1)];
1145 NSString *LocalizeSection(NSString *section) {
1146 static Pcre title_r("^(.*?) \\((.*)\\)$");
1147 if (title_r(section)) {
1148 NSString *parent(title_r[1]);
1149 NSString *child(title_r[2]);
1151 return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"),
1152 LocalizeSection(parent),
1153 LocalizeSection(child)
1157 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1160 NSString *Simplify(NSString *title) {
1161 const char *data = [title UTF8String];
1162 size_t size = [title length];
1164 static Pcre square_r("^\\[(.*)\\]$");
1165 if (square_r(data, size))
1166 return Simplify(square_r[1]);
1168 static Pcre paren_r("^\\((.*)\\)$");
1169 if (paren_r(data, size))
1170 return Simplify(paren_r[1]);
1172 static Pcre title_r("^(.*?) \\((.*)\\)$");
1173 if (title_r(data, size))
1174 return Simplify(title_r[1]);
1180 bool isSectionVisible(NSString *section) {
1181 NSDictionary *metadata([Sections_ objectForKey:section]);
1182 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1183 return hidden == nil || ![hidden boolValue];
1186 /* Delegate Prototypes {{{ */
1190 @interface NSObject (ProgressDelegate)
1193 @implementation NSObject(ProgressDelegate)
1195 - (void) _setProgressError:(NSArray *)args {
1196 [self performSelector:@selector(setProgressError:forPackage:)
1197 withObject:[args objectAtIndex:0]
1198 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1204 @protocol ProgressDelegate
1205 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1206 - (void) setProgressTitle:(NSString *)title;
1207 - (void) setProgressPercent:(float)percent;
1208 - (void) startProgress;
1209 - (void) addProgressOutput:(NSString *)output;
1210 - (bool) isCancelling:(size_t)received;
1213 @protocol ConfigurationDelegate
1214 - (void) repairWithSelector:(SEL)selector;
1215 - (void) setConfigurationData:(NSString *)data;
1220 @protocol CydiaDelegate
1221 - (void) setPackageView:(PackageView *)view;
1222 - (void) clearPackage:(Package *)package;
1223 - (void) installPackage:(Package *)package;
1224 - (void) removePackage:(Package *)package;
1225 - (void) slideUp:(UIActionSheet *)alert;
1226 - (void) distUpgrade;
1227 - (void) updateData;
1229 - (void) askForSettings;
1230 - (UIProgressHUD *) addProgressHUD;
1231 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1232 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag;
1233 - (RVPage *) pageForPackage:(NSString *)name;
1234 - (void) openMailToURL:(NSURL *)url;
1235 - (void) clearFirstResponder;
1236 - (PackageView *) packageView;
1240 /* Status Delegation {{{ */
1242 public pkgAcquireStatus
1245 _transient NSObject<ProgressDelegate> *delegate_;
1253 void setDelegate(id delegate) {
1254 delegate_ = delegate;
1257 virtual bool MediaChange(std::string media, std::string drive) {
1261 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1264 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1265 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1266 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
1269 virtual void Done(pkgAcquire::ItemDesc &item) {
1272 virtual void Fail(pkgAcquire::ItemDesc &item) {
1274 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1275 item.Owner->Status == pkgAcquire::Item::StatDone
1279 std::string &error(item.Owner->ErrorText);
1283 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1284 NSArray *fields([description componentsSeparatedByString:@" "]);
1285 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1287 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1288 withObject:[NSArray arrayWithObjects:
1289 [NSString stringWithUTF8String:error.c_str()],
1296 virtual bool Pulse(pkgAcquire *Owner) {
1297 bool value = pkgAcquireStatus::Pulse(Owner);
1300 double(CurrentBytes + CurrentItems) /
1301 double(TotalBytes + TotalItems)
1304 [delegate_ setProgressPercent:percent];
1305 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1308 virtual void Start() {
1309 [delegate_ startProgress];
1312 virtual void Stop() {
1316 /* Progress Delegation {{{ */
1321 _transient id<ProgressDelegate> delegate_;
1324 virtual void Update() {
1325 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1326 [delegate_ setProgressPercent:(Percent / 100)];*/
1335 void setDelegate(id delegate) {
1336 delegate_ = delegate;
1339 virtual void Done() {
1340 //[delegate_ setProgressPercent:1];
1345 /* Database Interface {{{ */
1346 @interface Database : NSObject {
1352 pkgCacheFile cache_;
1353 pkgDepCache::Policy *policy_;
1354 pkgRecords *records_;
1355 pkgProblemResolver *resolver_;
1356 pkgAcquire *fetcher_;
1358 SPtr<pkgPackageManager> manager_;
1359 pkgSourceList *list_;
1361 NSMutableDictionary *sources_;
1362 NSMutableArray *packages_;
1364 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1373 + (Database *) sharedInstance;
1376 - (void) _readCydia:(NSNumber *)fd;
1377 - (void) _readStatus:(NSNumber *)fd;
1378 - (void) _readOutput:(NSNumber *)fd;
1382 - (Package *) packageWithName:(NSString *)name;
1384 - (pkgCacheFile &) cache;
1385 - (pkgDepCache::Policy *) policy;
1386 - (pkgRecords *) records;
1387 - (pkgProblemResolver *) resolver;
1388 - (pkgAcquire &) fetcher;
1389 - (pkgSourceList &) list;
1390 - (NSArray *) packages;
1391 - (NSArray *) sources;
1392 - (void) reloadData;
1400 - (void) updateWithStatus:(Status &)status;
1402 - (void) setDelegate:(id)delegate;
1403 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1407 /* Source Class {{{ */
1408 @interface Source : NSObject {
1409 NSString *description_;
1415 NSString *distribution_;
1419 NSString *defaultIcon_;
1421 NSDictionary *record_;
1425 - (Source *) initWithMetaIndex:(metaIndex *)index;
1427 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1429 - (NSString *) supportForPackage:(NSString *)package;
1431 - (NSDictionary *) record;
1435 - (NSString *) distribution;
1436 - (NSString *) type;
1438 - (NSString *) host;
1440 - (NSString *) name;
1441 - (NSString *) description;
1442 - (NSString *) label;
1443 - (NSString *) origin;
1444 - (NSString *) version;
1446 - (NSString *) defaultIcon;
1450 @implementation Source
1452 #define _clear(field) \
1459 _clear(distribution_)
1462 _clear(description_)
1467 _clear(defaultIcon_)
1476 + (NSArray *) _attributeKeys {
1477 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1480 - (NSArray *) attributeKeys {
1481 return [[self class] _attributeKeys];
1484 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1485 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1488 - (void) setMetaIndex:(metaIndex *)index {
1491 trusted_ = index->IsTrusted();
1493 uri_ = [[NSString stringWithUTF8String:index->GetURI().c_str()] retain];
1494 distribution_ = [[NSString stringWithUTF8String:index->GetDist().c_str()] retain];
1495 type_ = [[NSString stringWithUTF8String:index->GetType()] retain];
1497 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1498 if (dindex != NULL) {
1499 std::ifstream release(dindex->MetaIndexFile("Release").c_str());
1501 while (std::getline(release, line)) {
1502 std::string::size_type colon(line.find(':'));
1503 if (colon == std::string::npos)
1506 std::string name(line.substr(0, colon));
1507 std::string value(line.substr(colon + 1));
1508 while (!value.empty() && value[0] == ' ')
1509 value = value.substr(1);
1511 if (name == "Default-Icon")
1512 defaultIcon_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1513 else if (name == "Description")
1514 description_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1515 else if (name == "Label")
1516 label_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1517 else if (name == "Origin")
1518 origin_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1519 else if (name == "Support")
1520 support_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1521 else if (name == "Version")
1522 version_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1526 record_ = [Sources_ objectForKey:[self key]];
1528 record_ = [record_ retain];
1531 - (Source *) initWithMetaIndex:(metaIndex *)index {
1532 if ((self = [super init]) != nil) {
1533 [self setMetaIndex:index];
1537 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1538 NSDictionary *lhr = [self record];
1539 NSDictionary *rhr = [source record];
1542 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1544 NSString *lhs = [self name];
1545 NSString *rhs = [source name];
1547 if ([lhs length] != 0 && [rhs length] != 0) {
1548 unichar lhc = [lhs characterAtIndex:0];
1549 unichar rhc = [rhs characterAtIndex:0];
1551 if (isalpha(lhc) && !isalpha(rhc))
1552 return NSOrderedAscending;
1553 else if (!isalpha(lhc) && isalpha(rhc))
1554 return NSOrderedDescending;
1557 return [lhs compare:rhs options:LaxCompareOptions_];
1560 - (NSString *) supportForPackage:(NSString *)package {
1561 return support_ == nil ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1564 - (NSDictionary *) record {
1572 - (NSString *) uri {
1576 - (NSString *) distribution {
1577 return distribution_;
1580 - (NSString *) type {
1584 - (NSString *) key {
1585 return [NSString stringWithFormat:@"%@:%@:%@", type_, uri_, distribution_];
1588 - (NSString *) host {
1589 return [[[NSURL URLWithString:[self uri]] host] lowercaseString];
1592 - (NSString *) name {
1593 return origin_ == nil ? [self host] : origin_;
1596 - (NSString *) description {
1597 return description_;
1600 - (NSString *) label {
1601 return label_ == nil ? [self host] : label_;
1604 - (NSString *) origin {
1608 - (NSString *) version {
1612 - (NSString *) defaultIcon {
1613 return defaultIcon_;
1618 /* Relationship Class {{{ */
1619 @interface Relationship : NSObject {
1624 - (NSString *) type;
1626 - (NSString *) name;
1630 @implementation Relationship
1638 - (NSString *) type {
1646 - (NSString *) name {
1653 /* Package Class {{{ */
1654 @interface Package : NSObject {
1657 pkgCache::VerIterator version_;
1658 pkgCache::PkgIterator iterator_;
1659 _transient Database *database_;
1660 pkgCache::VerFileIterator file_;
1666 NSString *section$_;
1671 NSString *installed_;
1677 CYString depiction_;
1690 NSArray *relationships_;
1692 NSMutableDictionary *metadata_;
1693 _transient NSDate *firstSeen_;
1694 _transient NSDate *lastSeen_;
1698 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1699 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1701 - (pkgCache::PkgIterator) iterator;
1703 - (NSString *) section;
1704 - (NSString *) simpleSection;
1706 - (NSString *) longSection;
1707 - (NSString *) shortSection;
1711 - (Address *) maintainer;
1713 - (NSString *) longDescription;
1714 - (NSString *) shortDescription;
1717 - (NSMutableDictionary *) metadata;
1719 - (BOOL) subscribed;
1722 - (NSString *) latest;
1723 - (NSString *) installed;
1726 - (BOOL) upgradableAndEssential:(BOOL)essential;
1729 - (BOOL) unfiltered;
1733 - (BOOL) halfConfigured;
1734 - (BOOL) halfInstalled;
1736 - (NSString *) mode;
1739 - (NSString *) name;
1741 - (NSString *) homepage;
1742 - (NSString *) depiction;
1743 - (Address *) author;
1745 - (NSString *) support;
1747 - (NSArray *) files;
1748 - (NSArray *) relationships;
1749 - (NSArray *) warnings;
1750 - (NSArray *) applications;
1752 - (Source *) source;
1753 - (NSString *) role;
1755 - (BOOL) matches:(NSString *)text;
1757 - (bool) hasSupportingRole;
1758 - (BOOL) hasTag:(NSString *)tag;
1759 - (NSString *) primaryPurpose;
1760 - (NSArray *) purposes;
1761 - (bool) isCommercial;
1763 - (CYString &) cyname;
1765 - (uint32_t) compareBySection:(NSArray *)sections;
1767 - (uint32_t) compareForChanges;
1772 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1773 - (bool) isInstalledAndVisible:(NSNumber *)number;
1774 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1775 - (bool) isVisibleInSource:(Source *)source;
1779 uint32_t PackageChangesRadix(Package *self, void *) {
1784 uint32_t timestamp : 30;
1785 uint32_t ignored : 1;
1786 uint32_t upgradable : 1;
1790 bool upgradable([self upgradableAndEssential:YES]);
1791 value.bits.upgradable = upgradable ? 1 : 0;
1794 value.bits.timestamp = 0;
1795 value.bits.ignored = [self ignored] ? 0 : 1;
1796 value.bits.upgradable = 1;
1798 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1799 value.bits.ignored = 0;
1800 value.bits.upgradable = 0;
1803 return _not(uint32_t) - value.key;
1806 _finline static void Stifle(uint8_t &value) {
1809 uint32_t PackagePrefixRadix(Package *self, void *context) {
1810 size_t offset(reinterpret_cast<size_t>(context));
1811 CYString &name([self cyname]);
1813 size_t size(name.size());
1816 char *text(name.data());
1819 if (!isdigit(text[0]))
1823 while (size != digits && isdigit(text[digits]))
1833 if (offset == 0 && zeros != 0) {
1834 memset(data, '0', zeros);
1835 memcpy(data + zeros, text, 4 - zeros);
1837 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1838 if (size <= offset - zeros)
1841 text += offset - zeros;
1842 size -= offset - zeros;
1845 memcpy(data, text, 4);
1847 memcpy(data, text, size);
1848 memset(data + size, 0, 4 - size);
1851 for (size_t i(0); i != 4; ++i)
1852 if (isalpha(data[i]))
1857 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1859 /* XXX: ntohl may be more honest */
1860 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1863 CYString &(*PackageName)(Package *self, SEL sel);
1865 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1866 _profile(PackageNameCompare)
1867 CYString &lhi(PackageName(lhs, @selector(cyname)));
1868 CYString &rhi(PackageName(rhs, @selector(cyname)));
1869 CFStringRef lhn(lhi), rhn(rhi);
1871 _profile(PackageNameCompare$NumbersLast)
1872 if (!lhi.empty() && !rhi.empty()) {
1873 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1874 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1875 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1876 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1877 return lha ? NSOrderedAscending : NSOrderedDescending;
1881 CFIndex length = CFStringGetLength(lhn);
1883 _profile(PackageNameCompare$Compare)
1884 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1889 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1890 return PackageNameCompare(*lhs, *rhs, context);
1893 struct PackageNameOrdering :
1894 std::binary_function<Package *, Package *, bool>
1896 _finline bool operator ()(Package *lhs, Package *rhs) const {
1897 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1901 @implementation Package
1903 - (NSString *) description {
1904 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1910 if (section$_ != nil)
1911 [section$_ release];
1915 if (installed_ != nil)
1916 [installed_ release];
1918 if (sponsor$_ != nil)
1919 [sponsor$_ release];
1920 if (author$_ != nil)
1927 if (relationships_ != nil)
1928 [relationships_ release];
1929 if (metadata_ != nil)
1930 [metadata_ release];
1935 + (NSString *) webScriptNameForSelector:(SEL)selector {
1936 if (selector == @selector(hasTag:))
1942 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1943 return [self webScriptNameForSelector:selector] == nil;
1946 + (NSArray *) _attributeKeys {
1947 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];
1950 - (NSArray *) attributeKeys {
1951 return [[self class] _attributeKeys];
1954 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1955 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1958 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
1959 if ((self = [super init]) != nil) {
1960 _profile(Package$initWithVersion)
1961 @synchronized (database) {
1962 era_ = [database era];
1965 iterator_ = version.ParentPkg();
1966 database_ = database;
1968 _profile(Package$initWithVersion$Latest)
1969 latest_ = [StripVersion(version_.VerStr()) retain];
1972 pkgCache::VerIterator current(iterator_.CurrentVer());
1974 installed_ = [StripVersion(current.VerStr()) retain];
1976 if (!version_.end())
1977 file_ = version_.FileList();
1979 pkgCache &cache([database_ cache]);
1980 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
1983 _profile(Package$initWithVersion$Name)
1984 id_.set(pool, iterator_.Name());
1988 source_ = [database_ getSource:file_.File()];
1993 _profile(Package$initWithVersion$Parse)
1994 pkgRecords::Parser *parser;
1996 _profile(Package$initWithVersion$Parse$Lookup)
1997 parser = &[database_ records]->Lookup(file_);
2003 _profile(Package$initWithVersion$Parse$Find)
2010 {"depiction", &depiction_},
2011 {"homepage", &homepage_},
2012 {"website", &website},
2013 {"support", &support_},
2014 {"sponsor", &sponsor_},
2015 {"author", &author_},
2019 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2020 const char *start, *end;
2022 if (parser->Find(names[i].name_, start, end)) {
2023 CYString &value(*names[i].value_);
2024 _profile(Package$initWithVersion$Parse$Value)
2025 value.set(pool, start, end - start);
2031 _profile(Package$initWithVersion$Parse$Tagline)
2032 tagline_.set(pool, parser->ShortDesc());
2035 _profile(Package$initWithVersion$Parse$Retain)
2036 if (!homepage_.empty())
2037 homepage_ = website;
2038 if (homepage_ == depiction_)
2041 tags_ = [[tag componentsSeparatedByString:@", "] retain];
2045 _profile(Package$initWithVersion$Tags)
2047 for (NSString *tag in tags_)
2048 if ([tag hasPrefix:@"role::"]) {
2049 role_ = [[tag substringFromIndex:6] retain];
2054 bool changed(false);
2055 NSString *key([id_ lowercaseString]);
2057 _profile(Package$initWithVersion$Metadata)
2058 metadata_ = [Packages_ objectForKey:key];
2060 if (metadata_ == nil) {
2061 firstSeen_ = [now_ retain];
2063 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2064 firstSeen_, @"FirstSeen",
2065 latest_, @"LastVersion",
2070 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2071 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2073 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2074 subscribed_ = [subscribed boolValue];
2076 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2078 if (firstSeen_ == nil) {
2079 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2080 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2084 if (version == nil) {
2085 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2087 } else if (![version isEqualToString:latest_]) {
2088 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2090 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2095 metadata_ = [metadata_ retain];
2098 [Packages_ setObject:metadata_ forKey:key];
2103 _profile(Package$initWithVersion$Section)
2104 section_.set(pool, iterator_.Section());
2107 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2108 visible_ = [self hasSupportingRole] && [self unfiltered];
2109 } _end } return self;
2112 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2113 pkgCache::VerIterator version;
2115 _profile(Package$packageWithIterator$GetCandidateVer)
2116 version = [database policy]->GetCandidateVer(iterator);
2122 return [[[Package alloc]
2123 initWithVersion:version
2130 - (pkgCache::PkgIterator) iterator {
2134 - (NSString *) section {
2135 if (section$_ == nil) {
2136 if (section_.empty())
2139 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2140 NSString *name(section_);
2143 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2144 if (NSString *rename = [value objectForKey:@"Rename"]) {
2149 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2153 - (NSString *) simpleSection {
2154 if (NSString *section = [self section])
2155 return Simplify(section);
2160 - (NSString *) longSection {
2161 return LocalizeSection(section_);
2164 - (NSString *) shortSection {
2165 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2168 - (NSString *) uri {
2171 pkgIndexFile *index;
2172 pkgCache::PkgFileIterator file(file_.File());
2173 if (![database_ list].FindIndex(file, index))
2175 return [NSString stringWithUTF8String:iterator_->Path];
2176 //return [NSString stringWithUTF8String:file.Site()];
2177 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2181 - (Address *) maintainer {
2184 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2185 const std::string &maintainer(parser->Maintainer());
2186 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2190 return version_.end() ? 0 : version_->InstalledSize;
2193 - (NSString *) longDescription {
2196 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2197 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2199 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2200 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2201 if ([lines count] < 2)
2204 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2205 for (size_t i(1), e([lines count]); i != e; ++i) {
2206 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2207 [trimmed addObject:trim];
2210 return [trimmed componentsJoinedByString:@"\n"];
2213 - (NSString *) shortDescription {
2218 _profile(Package$index)
2219 CFStringRef name((CFStringRef) [self name]);
2220 if (CFStringGetLength(name) == 0)
2222 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2223 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2225 return toupper(character);
2229 - (NSMutableDictionary *) metadata {
2234 if (subscribed_ && lastSeen_ != nil)
2239 - (BOOL) subscribed {
2244 NSDictionary *metadata([self metadata]);
2245 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2246 return [ignored boolValue];
2251 - (NSString *) latest {
2255 - (NSString *) installed {
2260 return !version_.end();
2263 - (BOOL) upgradableAndEssential:(BOOL)essential {
2264 _profile(Package$upgradableAndEssential)
2265 pkgCache::VerIterator current(iterator_.CurrentVer());
2267 return essential && essential_ && visible_;
2269 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2273 - (BOOL) essential {
2278 return [database_ cache][iterator_].InstBroken();
2281 - (BOOL) unfiltered {
2282 NSString *section([self section]);
2283 return section == nil || isSectionVisible(section);
2291 unsigned char current(iterator_->CurrentState);
2292 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2295 - (BOOL) halfConfigured {
2296 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2299 - (BOOL) halfInstalled {
2300 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2304 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2305 return state.Mode != pkgDepCache::ModeKeep;
2308 - (NSString *) mode {
2309 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2311 switch (state.Mode) {
2312 case pkgDepCache::ModeDelete:
2313 if ((state.iFlags & pkgDepCache::Purge) != 0)
2317 case pkgDepCache::ModeKeep:
2318 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2319 return @"REINSTALL";
2320 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2324 case pkgDepCache::ModeInstall:
2325 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2326 return @"REINSTALL";
2327 else*/ switch (state.Status) {
2329 return @"DOWNGRADE";
2335 return @"NEW_INSTALL";
2348 - (NSString *) name {
2349 return name_.empty() ? id_ : name_;
2352 - (UIImage *) icon {
2353 NSString *section = [self simpleSection];
2357 if ([icon_ hasPrefix:@"file:///"])
2358 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2359 if (icon == nil) if (section != nil)
2360 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2361 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2362 if ([dicon hasPrefix:@"file:///"])
2363 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2365 icon = [UIImage applicationImageNamed:@"unknown.png"];
2369 - (NSString *) homepage {
2373 - (NSString *) depiction {
2377 - (Address *) sponsor {
2378 if (sponsor$_ == nil) {
2379 if (sponsor_.empty())
2381 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2385 - (Address *) author {
2386 if (author$_ == nil) {
2387 if (author_.empty())
2389 author$_ = [[Address addressWithString:author_] retain];
2393 - (NSString *) support {
2394 return !support_.empty() ? support_ : [[self source] supportForPackage:id_];
2397 - (NSArray *) files {
2398 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2399 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2402 fin.open([path UTF8String]);
2407 while (std::getline(fin, line))
2408 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2413 - (NSArray *) relationships {
2414 return relationships_;
2417 - (NSArray *) warnings {
2418 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2419 const char *name(iterator_.Name());
2421 size_t length(strlen(name));
2422 if (length < 2) invalid:
2423 [warnings addObject:CYLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2424 else for (size_t i(0); i != length; ++i)
2426 /* XXX: technically this is not allowed */
2427 (name[i] < 'A' || name[i] > 'Z') &&
2428 (name[i] < 'a' || name[i] > 'z') &&
2429 (name[i] < '0' || name[i] > '9') &&
2430 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2433 if (strcmp(name, "cydia") != 0) {
2435 bool _private = false;
2438 bool repository = [[self section] isEqualToString:@"Repositories"];
2440 if (NSArray *files = [self files])
2441 for (NSString *file in files)
2442 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2444 else if (!_private && [file isEqualToString:@"/private"])
2446 else if (!stash && [file isEqualToString:@"/var/stash"])
2449 /* XXX: this is not sensitive enough. only some folders are valid. */
2450 if (cydia && !repository)
2451 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2453 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/private"]];
2455 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2458 return [warnings count] == 0 ? nil : warnings;
2461 - (NSArray *) applications {
2462 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2464 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2466 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2467 if (NSArray *files = [self files])
2468 for (NSString *file in files)
2469 if (application_r(file)) {
2470 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2471 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2472 if ([id isEqualToString:me])
2475 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2477 display = application_r[1];
2479 NSString *bundle([file stringByDeletingLastPathComponent]);
2480 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2481 if (icon == nil || [icon length] == 0)
2483 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2485 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2486 [applications addObject:application];
2488 [application addObject:id];
2489 [application addObject:display];
2490 [application addObject:url];
2493 return [applications count] == 0 ? nil : applications;
2496 - (Source *) source {
2498 @synchronized (database_) {
2499 if ([database_ era] != era_ || file_.end())
2502 source_ = [database_ getSource:file_.File()];
2514 - (NSString *) role {
2518 - (BOOL) matches:(NSString *)text {
2524 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2525 if (range.location != NSNotFound)
2528 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2529 if (range.location != NSNotFound)
2532 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2533 if (range.location != NSNotFound)
2539 - (bool) hasSupportingRole {
2542 if ([role_ isEqualToString:@"enduser"])
2544 if ([Role_ isEqualToString:@"User"])
2546 if ([role_ isEqualToString:@"hacker"])
2548 if ([Role_ isEqualToString:@"Hacker"])
2550 if ([role_ isEqualToString:@"developer"])
2552 if ([Role_ isEqualToString:@"Developer"])
2557 - (BOOL) hasTag:(NSString *)tag {
2558 return tags_ == nil ? NO : [tags_ containsObject:tag];
2561 - (NSString *) primaryPurpose {
2562 for (NSString *tag in tags_)
2563 if ([tag hasPrefix:@"purpose::"])
2564 return [tag substringFromIndex:9];
2568 - (NSArray *) purposes {
2569 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2570 for (NSString *tag in tags_)
2571 if ([tag hasPrefix:@"purpose::"])
2572 [purposes addObject:[tag substringFromIndex:9]];
2573 return [purposes count] == 0 ? nil : purposes;
2576 - (bool) isCommercial {
2577 return [self hasTag:@"cydia::commercial"];
2580 - (CYString &) cyname {
2581 return name_.empty() ? id_ : name_;
2584 - (uint32_t) compareBySection:(NSArray *)sections {
2585 NSString *section([self section]);
2586 for (size_t i(0), e([sections count]); i != e; ++i) {
2587 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2591 return _not(uint32_t);
2594 - (uint32_t) compareForChanges {
2599 uint32_t timestamp : 30;
2600 uint32_t ignored : 1;
2601 uint32_t upgradable : 1;
2605 bool upgradable([self upgradableAndEssential:YES]);
2606 value.bits.upgradable = upgradable ? 1 : 0;
2609 value.bits.timestamp = 0;
2610 value.bits.ignored = [self ignored] ? 0 : 1;
2611 value.bits.upgradable = 1;
2613 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2614 value.bits.ignored = 0;
2615 value.bits.upgradable = 0;
2618 return _not(uint32_t) - value.key;
2622 pkgProblemResolver *resolver = [database_ resolver];
2623 resolver->Clear(iterator_);
2624 resolver->Protect(iterator_);
2628 pkgProblemResolver *resolver = [database_ resolver];
2629 resolver->Clear(iterator_);
2630 resolver->Protect(iterator_);
2631 pkgCacheFile &cache([database_ cache]);
2632 cache->MarkInstall(iterator_, false);
2633 pkgDepCache::StateCache &state((*cache)[iterator_]);
2634 if (!state.Install())
2635 cache->SetReInstall(iterator_, true);
2639 pkgProblemResolver *resolver = [database_ resolver];
2640 resolver->Clear(iterator_);
2641 resolver->Protect(iterator_);
2642 resolver->Remove(iterator_);
2643 [database_ cache]->MarkDelete(iterator_, true);
2646 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2647 _profile(Package$isUnfilteredAndSearchedForBy)
2650 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2651 value &= [self unfiltered];
2654 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2655 value &= [self matches:search];
2662 - (bool) isInstalledAndVisible:(NSNumber *)number {
2663 return (![number boolValue] || [self visible]) && [self installed] != nil;
2666 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2667 NSString *section = [self section];
2671 [self installed] == nil && (
2673 section == nil && [name length] == 0 ||
2674 [name isEqualToString:section]
2678 - (bool) isVisibleInSource:(Source *)source {
2679 return [self source] == source && [self visible];
2684 /* Section Class {{{ */
2685 @interface Section : NSObject {
2690 NSString *localized_;
2693 - (NSComparisonResult) compareByLocalized:(Section *)section;
2694 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2695 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2696 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2697 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2698 - (NSString *) name;
2705 - (void) addToCount;
2707 - (void) setCount:(size_t)count;
2708 - (NSString *) localized;
2712 @implementation Section
2716 if (localized_ != nil)
2717 [localized_ release];
2721 - (NSComparisonResult) compareByLocalized:(Section *)section {
2722 NSString *lhs(localized_);
2723 NSString *rhs([section localized]);
2725 /*if ([lhs length] != 0 && [rhs length] != 0) {
2726 unichar lhc = [lhs characterAtIndex:0];
2727 unichar rhc = [rhs characterAtIndex:0];
2729 if (isalpha(lhc) && !isalpha(rhc))
2730 return NSOrderedAscending;
2731 else if (!isalpha(lhc) && isalpha(rhc))
2732 return NSOrderedDescending;
2735 return [lhs compare:rhs options:LaxCompareOptions_];
2738 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2739 if ((self = [self initWithName:name localize:NO]) != nil) {
2740 if (localized != nil)
2741 localized_ = [localized retain];
2745 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2746 return [self initWithName:name row:0 localize:localize];
2749 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2750 if ((self = [super init]) != nil) {
2751 name_ = [name retain];
2755 localized_ = [LocalizeSection(name_) retain];
2759 /* XXX: localize the index thingees */
2760 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2761 if ((self = [super init]) != nil) {
2762 name_ = [(index == '#' ? @"123" : [NSString stringWithCharacters:&index length:1]) retain];
2768 - (NSString *) name {
2788 - (void) addToCount {
2792 - (void) setCount:(size_t)count {
2796 - (NSString *) localized {
2804 static NSArray *Finishes_;
2806 /* Database Implementation {{{ */
2807 @implementation Database
2809 + (Database *) sharedInstance {
2810 static Database *instance;
2811 if (instance == nil)
2812 instance = [[Database alloc] init];
2822 NSRecycleZone(zone_);
2823 // XXX: malloc_destroy_zone(zone_);
2824 apr_pool_destroy(pool_);
2828 - (void) _readCydia:(NSNumber *)fd { _pooled
2829 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2830 std::istream is(&ib);
2833 static Pcre finish_r("^finish:([^:]*)$");
2835 while (std::getline(is, line)) {
2836 const char *data(line.c_str());
2837 size_t size = line.size();
2838 lprintf("C:%s\n", data);
2840 if (finish_r(data, size)) {
2841 NSString *finish = finish_r[1];
2842 int index = [Finishes_ indexOfObject:finish];
2843 if (index != INT_MAX && index > Finish_)
2851 - (void) _readStatus:(NSNumber *)fd { _pooled
2852 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2853 std::istream is(&ib);
2856 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2857 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2859 while (std::getline(is, line)) {
2860 const char *data(line.c_str());
2861 size_t size = line.size();
2862 lprintf("S:%s\n", data);
2864 if (conffile_r(data, size)) {
2865 [delegate_ setConfigurationData:conffile_r[1]];
2866 } else if (strncmp(data, "status: ", 8) == 0) {
2867 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2868 [delegate_ setProgressTitle:string];
2869 } else if (pmstatus_r(data, size)) {
2870 std::string type([pmstatus_r[1] UTF8String]);
2871 NSString *id = pmstatus_r[2];
2873 float percent([pmstatus_r[3] floatValue]);
2874 [delegate_ setProgressPercent:(percent / 100)];
2876 NSString *string = pmstatus_r[4];
2878 if (type == "pmerror")
2879 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2880 withObject:[NSArray arrayWithObjects:string, id, nil]
2883 else if (type == "pmstatus") {
2884 [delegate_ setProgressTitle:string];
2885 } else if (type == "pmconffile")
2886 [delegate_ setConfigurationData:string];
2887 else _assert(false);
2888 } else _assert(false);
2894 - (void) _readOutput:(NSNumber *)fd { _pooled
2895 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2896 std::istream is(&ib);
2899 while (std::getline(is, line)) {
2900 lprintf("O:%s\n", line.c_str());
2901 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2911 - (Package *) packageWithName:(NSString *)name {
2912 if (static_cast<pkgDepCache *>(cache_) == NULL)
2914 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
2915 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
2918 - (Database *) init {
2919 if ((self = [super init]) != nil) {
2926 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
2927 apr_pool_create(&pool_, NULL);
2929 sources_ = [[NSMutableDictionary dictionaryWithCapacity:16] retain];
2930 packages_ = [[NSMutableArray alloc] init];
2934 _assert(pipe(fds) != -1);
2937 _config->Set("APT::Keep-Fds::", cydiafd_);
2938 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
2941 detachNewThreadSelector:@selector(_readCydia:)
2943 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2946 _assert(pipe(fds) != -1);
2950 detachNewThreadSelector:@selector(_readStatus:)
2952 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2955 _assert(pipe(fds) != -1);
2956 _assert(dup2(fds[0], 0) != -1);
2957 _assert(close(fds[0]) != -1);
2959 input_ = fdopen(fds[1], "a");
2961 _assert(pipe(fds) != -1);
2962 _assert(dup2(fds[1], 1) != -1);
2963 _assert(close(fds[1]) != -1);
2966 detachNewThreadSelector:@selector(_readOutput:)
2968 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2973 - (pkgCacheFile &) cache {
2977 - (pkgDepCache::Policy *) policy {
2981 - (pkgRecords *) records {
2985 - (pkgProblemResolver *) resolver {
2989 - (pkgAcquire &) fetcher {
2993 - (pkgSourceList &) list {
2997 - (NSArray *) packages {
3001 - (NSArray *) sources {
3002 return [sources_ allValues];
3005 - (NSArray *) issues {
3006 if (cache_->BrokenCount() == 0)
3009 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3011 for (Package *package in packages_) {
3012 if (![package broken])
3014 pkgCache::PkgIterator pkg([package iterator]);
3016 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3017 [entry addObject:[package name]];
3018 [issues addObject:entry];
3020 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3024 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3025 pkgCache::DepIterator start;
3026 pkgCache::DepIterator end;
3027 dep.GlobOr(start, end); // ++dep
3029 if (!cache_->IsImportantDep(end))
3031 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3034 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3035 [entry addObject:failure];
3036 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3038 Package *package([self packageWithName:[NSString stringWithUTF8String:start.TargetPkg().Name()]]);
3039 [failure addObject:[package name]];
3041 pkgCache::PkgIterator target(start.TargetPkg());
3042 if (target->ProvidesList != 0)
3043 [failure addObject:@"?"];
3045 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3047 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3048 else if (!cache_[target].CandidateVerIter(cache_).end())
3049 [failure addObject:@"-"];
3050 else if (target->ProvidesList == 0)
3051 [failure addObject:@"!"];
3053 [failure addObject:@"%"];
3057 if (start.TargetVer() != 0)
3058 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3069 - (void) reloadData { _pooled
3070 @synchronized (self) {
3092 apr_pool_clear(pool_);
3093 NSRecycleZone(zone_);
3095 int chk(creat("/tmp/cydia.chk", 0644));
3100 if (!cache_.Open(progress_, true)) {
3102 if (!_error->PopMessage(error))
3105 lprintf("cache_.Open():[%s]\n", error.c_str());
3107 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3108 [delegate_ repairWithSelector:@selector(configure)];
3109 else if (error == "The package lists or status file could not be parsed or opened.")
3110 [delegate_ repairWithSelector:@selector(update)];
3111 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3112 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3113 // else if (error == "The list of sources could not be read.")
3114 else _assert(false);
3120 unlink("/tmp/cydia.chk");
3122 now_ = [[NSDate date] retain];
3124 policy_ = new pkgDepCache::Policy();
3125 records_ = new pkgRecords(cache_);
3126 resolver_ = new pkgProblemResolver(cache_);
3127 fetcher_ = new pkgAcquire(&status_);
3130 list_ = new pkgSourceList();
3131 _assert(list_->ReadMainList());
3133 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3134 _assert(pkgApplyStatus(cache_));
3136 if (cache_->BrokenCount() != 0) {
3137 _assert(pkgFixBroken(cache_));
3138 _assert(cache_->BrokenCount() == 0);
3139 _assert(pkgMinimizeUpgrade(cache_));
3144 std::string lists(_config->FindDir("Dir::State::lists"));
3146 [sources_ removeAllObjects];
3147 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3148 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3149 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3150 if (debPackagesIndex *packages = dynamic_cast<debPackagesIndex *>(*index))
3152 setObject:[[[Source alloc] initWithMetaIndex:*source] autorelease]
3153 forKey:[NSString stringWithFormat:@"%s%s",
3155 URItoFileName(packages->IndexURI("Packages")).c_str()
3163 /*std::vector<Package *> packages;
3164 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3165 [packages_ release];
3168 [packages_ removeAllObjects];
3172 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3173 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3174 //packages.push_back(package);
3175 [packages_ addObject:package];
3179 /*if (packages.empty())
3180 packages_ = [[NSArray alloc] init];
3182 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3185 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3186 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3187 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3195 /*if (!packages.empty())
3196 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3197 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3199 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3201 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3203 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3209 - (void) configure {
3210 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3211 system([dpkg UTF8String]);
3219 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3220 _assert(!_error->PendingError());
3223 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3226 public pkgArchiveCleaner
3229 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3234 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3236 while (_error->PopMessage(error))
3237 lprintf("ArchiveCleaner: %s\n", error.c_str());
3242 pkgRecords records(cache_);
3244 lock_ = new FileFd();
3245 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3246 _assert(!_error->PendingError());
3249 // XXX: explain this with an error message
3250 _assert(list.ReadMainList());
3252 manager_ = (_system->CreatePM(cache_));
3253 _assert(manager_->GetArchives(fetcher_, &list, &records));
3254 _assert(!_error->PendingError());
3258 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3260 _assert(list.ReadMainList());
3261 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3262 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3265 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3270 bool failed = false;
3271 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3272 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3275 std::string uri = (*item)->DescURI();
3276 std::string error = (*item)->ErrorText;
3278 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3281 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3282 withObject:[NSArray arrayWithObjects:
3283 [NSString stringWithUTF8String:error.c_str()],
3295 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3297 if (_error->PendingError()) {
3302 if (result == pkgPackageManager::Failed) {
3307 if (result != pkgPackageManager::Completed) {
3312 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3314 _assert(list.ReadMainList());
3315 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3316 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3319 if (![before isEqualToArray:after])
3324 _assert(pkgDistUpgrade(cache_));
3328 [self updateWithStatus:status_];
3331 - (void) updateWithStatus:(Status &)status {
3333 _assert(list.ReadMainList());
3336 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3337 _assert(!_error->PendingError());
3339 pkgAcquire fetcher(&status);
3340 _assert(list.GetIndexes(&fetcher));
3342 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3343 bool failed = false;
3344 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3345 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3346 (*item)->Finished();
3350 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3351 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3352 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3355 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3360 - (void) setDelegate:(id)delegate {
3361 delegate_ = delegate;
3362 status_.setDelegate(delegate);
3363 progress_.setDelegate(delegate);
3366 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3367 if (const char *name = file.FileName())
3368 if (Source *source = [sources_ objectForKey:[NSString stringWithUTF8String:name]])
3376 /* PopUp Windows {{{ */
3377 @interface PopUpView : UIView {
3378 _transient id delegate_;
3379 UITransitionView *transition_;
3384 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3388 @implementation PopUpView
3391 [transition_ setDelegate:nil];
3392 [transition_ release];
3398 [transition_ transition:UITransitionPushFromTop toView:nil];
3401 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3402 if (from != nil && to == nil)
3403 [self removeFromSuperview];
3406 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3407 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3408 delegate_ = delegate;
3410 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3411 [self addSubview:transition_];
3413 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3415 [view addSubview:self];
3417 [transition_ setDelegate:self];
3419 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3420 [transition_ transition:UITransitionNone toView:blank];
3421 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3429 /* Mail Composition {{{ */
3430 @interface MailToView : PopUpView {
3431 MailComposeController *controller_;
3434 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
3438 @implementation MailToView
3441 [controller_ release];
3445 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
3449 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
3450 NSLog(@"did:%@", delivery);
3451 // [UIApp setStatusBarShowsProgress:NO];
3452 if ([controller error]){
3453 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3454 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3455 [mailAlertSheet setBodyText:[controller error]];
3456 [mailAlertSheet popupAlertAnimated:YES];
3460 - (void) showError {
3461 NSLog(@"%@", [controller_ error]);
3462 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3463 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3464 [mailAlertSheet setBodyText:[controller_ error]];
3465 [mailAlertSheet popupAlertAnimated:YES];
3468 - (void) deliverMessage { _pooled
3472 if (![controller_ deliverMessage])
3473 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
3476 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
3477 if ([controller_ needsDelivery])
3478 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
3483 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
3484 if ((self = [super initWithView:view delegate:delegate]) != nil) {
3485 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
3486 [controller_ setDelegate:self];
3487 [controller_ initializeUI];
3488 [controller_ setupForURL:url];
3490 UIView *view([controller_ view]);
3491 [overlay_ addSubview:view];
3499 /* Confirmation View {{{ */
3500 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3501 if (!iterator.end())
3502 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3503 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3505 pkgCache::PkgIterator package(dep.TargetPkg());
3508 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3515 @protocol ConfirmationViewDelegate
3521 @interface ConfirmationView : BrowserView {
3522 _transient Database *database_;
3523 UIActionSheet *essential_;
3530 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3534 @implementation ConfirmationView
3541 if (essential_ != nil)
3542 [essential_ release];
3548 [book_ popFromSuperviewAnimated:YES];
3551 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3552 NSString *context([sheet context]);
3554 if ([context isEqualToString:@"remove"]) {
3562 [delegate_ confirm];
3569 } else if ([context isEqualToString:@"unable"]) {
3573 [super alertSheet:sheet buttonClicked:button];
3576 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3577 [super webView:sender didClearWindowObject:window forFrame:frame];
3578 [window setValue:changes_ forKey:@"changes"];
3579 [window setValue:issues_ forKey:@"issues"];
3580 [window setValue:sizes_ forKey:@"sizes"];
3583 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3584 if ((self = [super initWithBook:book]) != nil) {
3585 database_ = database;
3587 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3588 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3589 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3590 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3591 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3595 pkgDepCache::Policy *policy([database_ policy]);
3597 pkgCacheFile &cache([database_ cache]);
3598 NSArray *packages = [database_ packages];
3599 for (Package *package in packages) {
3600 pkgCache::PkgIterator iterator = [package iterator];
3601 pkgDepCache::StateCache &state(cache[iterator]);
3603 NSString *name([package name]);
3605 if (state.NewInstall())
3606 [installing addObject:name];
3607 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3608 [reinstalling addObject:name];
3609 else if (state.Upgrade())
3610 [upgrading addObject:name];
3611 else if (state.Downgrade())
3612 [downgrading addObject:name];
3613 else if (state.Delete()) {
3614 if ([package essential])
3616 [removing addObject:name];
3619 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3620 substrate_ |= DepSubstrate(iterator.CurrentVer());
3625 else if (Advanced_ || true) {
3626 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
3628 essential_ = [[UIActionSheet alloc]
3629 initWithTitle:CYLocalize("REMOVING_ESSENTIALS")
3630 buttons:[NSArray arrayWithObjects:
3631 [NSString stringWithFormat:parenthetical, CYLocalize("CANCEL_OPERATION"), CYLocalize("SAFE")],
3632 [NSString stringWithFormat:parenthetical, CYLocalize("FORCE_REMOVAL"), CYLocalize("UNSAFE")],
3634 defaultButtonIndex:0
3640 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3642 [essential_ setBodyText:CYLocalize("REMOVING_ESSENTIALS_EX")];
3644 essential_ = [[UIActionSheet alloc]
3645 initWithTitle:CYLocalize("UNABLE_TO_COMPLY")
3646 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3647 defaultButtonIndex:0
3652 [essential_ setBodyText:CYLocalize("UNABLE_TO_COMPLY_EX")];
3655 changes_ = [[NSArray alloc] initWithObjects:
3663 issues_ = [database_ issues];
3665 issues_ = [issues_ retain];
3667 sizes_ = [[NSArray alloc] initWithObjects:
3668 SizeString([database_ fetcher].FetchNeeded()),
3669 SizeString([database_ fetcher].PartialPresent()),
3670 SizeString([database_ cache]->UsrSize()),
3673 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3677 - (NSString *) backButtonTitle {
3678 return CYLocalize("CONFIRM");
3681 - (NSString *) leftButtonTitle {
3682 return [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("CANCEL"), CYLocalize("QUEUE")];
3685 - (id) rightButtonTitle {
3686 return issues_ != nil ? nil : [super rightButtonTitle];
3689 - (id) _rightButtonTitle {
3690 #if AlwaysReload || IgnoreInstall
3691 return [super _rightButtonTitle];
3693 return CYLocalize("CONFIRM");
3697 - (void) _leftButtonClicked {
3702 - (void) _rightButtonClicked {
3704 return [super _rightButtonClicked];
3706 if (essential_ != nil)
3707 [essential_ popupAlertAnimated:YES];
3711 [delegate_ confirm];
3719 /* Progress Data {{{ */
3720 @interface ProgressData : NSObject {
3726 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3733 @implementation ProgressData
3735 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3736 if ((self = [super init]) != nil) {
3737 selector_ = selector;
3757 /* Progress View {{{ */
3758 @interface ProgressView : UIView <
3759 ConfigurationDelegate,
3762 _transient Database *database_;
3764 UIView *background_;
3765 UITransitionView *transition_;
3767 UINavigationBar *navbar_;
3768 UIProgressBar *progress_;
3769 UITextView *output_;
3770 UITextLabel *status_;
3771 UIPushButton *close_;
3774 SHA1SumValue springlist_;
3775 SHA1SumValue notifyconf_;
3776 SHA1SumValue sandplate_;
3779 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
3781 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
3782 - (void) setContentView:(UIView *)view;
3785 - (void) _retachThread;
3786 - (void) _detachNewThreadData:(ProgressData *)data;
3787 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
3793 @protocol ProgressViewDelegate
3794 - (void) progressViewIsComplete:(ProgressView *)sender;
3797 @implementation ProgressView
3800 [transition_ setDelegate:nil];
3801 [navbar_ setDelegate:nil];
3804 if (background_ != nil)
3805 [background_ release];
3806 [transition_ release];
3809 [progress_ release];
3816 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3817 if (bootstrap_ && from == overlay_ && to == view_)
3821 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
3822 if ((self = [super initWithFrame:frame]) != nil) {
3823 database_ = database;
3824 delegate_ = delegate;
3826 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3827 [transition_ setDelegate:self];
3829 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3832 [overlay_ setBackgroundColor:[UIColor blackColor]];
3834 background_ = [[UIView alloc] initWithFrame:[self bounds]];
3835 [background_ setBackgroundColor:[UIColor blackColor]];
3836 [self addSubview:background_];
3839 [self addSubview:transition_];
3841 CGSize navsize = [UINavigationBar defaultSize];
3842 CGRect navrect = {{0, 0}, navsize};
3844 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
3845 [overlay_ addSubview:navbar_];
3847 [navbar_ setBarStyle:1];
3848 [navbar_ setDelegate:self];
3850 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
3851 [navbar_ pushNavigationItem:navitem];
3853 CGRect bounds = [overlay_ bounds];
3854 CGSize prgsize = [UIProgressBar defaultSize];
3857 (bounds.size.width - prgsize.width) / 2,
3858 bounds.size.height - prgsize.height - 20
3861 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3862 [progress_ setStyle:0];
3864 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3866 bounds.size.height - prgsize.height - 50,
3867 bounds.size.width - 20,
3871 [status_ setColor:[UIColor whiteColor]];
3872 [status_ setBackgroundColor:[UIColor clearColor]];
3874 [status_ setCentersHorizontally:YES];
3875 //[status_ setFont:font];
3878 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3880 navrect.size.height + 20,
3881 bounds.size.width - 20,
3882 bounds.size.height - navsize.height - 62 - navrect.size.height
3886 //[output_ setTextFont:@"Courier New"];
3887 [output_ setTextSize:12];
3889 [output_ setTextColor:[UIColor whiteColor]];
3890 [output_ setBackgroundColor:[UIColor clearColor]];
3892 [output_ setMarginTop:0];
3893 [output_ setAllowsRubberBanding:YES];
3894 [output_ setEditable:NO];
3896 [overlay_ addSubview:output_];
3898 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3900 bounds.size.height - prgsize.height - 50,
3901 bounds.size.width - 20,
3905 [close_ setAutosizesToFit:NO];
3906 [close_ setDrawsShadow:YES];
3907 [close_ setStretchBackground:YES];
3908 [close_ setEnabled:YES];
3910 UIFont *bold = [UIFont boldSystemFontOfSize:22];
3911 [close_ setTitleFont:bold];
3913 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
3914 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
3915 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
3919 - (void) setContentView:(UIView *)view {
3920 view_ = [view retain];
3923 - (void) resetView {
3924 [transition_ transition:6 toView:view_];
3927 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3928 NSString *context([sheet context]);
3930 if ([context isEqualToString:@"error"])
3932 else if ([context isEqualToString:@"conffile"]) {
3933 FILE *input = [database_ input];
3937 fprintf(input, "N\n");
3941 fprintf(input, "Y\n");
3952 - (void) closeButtonPushed {
3961 [delegate_ suspendWithAnimation:YES];
3965 system("launchctl stop com.apple.SpringBoard");
3969 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
3978 - (void) _retachThread {
3979 UINavigationItem *item = [navbar_ topItem];
3980 [item setTitle:CYLocalize("COMPLETE")];
3982 [overlay_ addSubview:close_];
3983 [progress_ removeFromSuperview];
3984 [status_ removeFromSuperview];
3986 [delegate_ progressViewIsComplete:self];
3989 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
3990 MMap mmap(file, MMap::ReadOnly);
3992 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3993 if (!(sandplate_ == sha1.Result()))
3998 FileFd file(NotifyConfig_, FileFd::ReadOnly);
3999 MMap mmap(file, MMap::ReadOnly);
4001 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4002 if (!(notifyconf_ == sha1.Result()))
4007 FileFd file(SpringBoard_, FileFd::ReadOnly);
4008 MMap mmap(file, MMap::ReadOnly);
4010 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4011 if (!(springlist_ == sha1.Result()))
4016 case 0: [close_ setTitle:CYLocalize("RETURN_TO_CYDIA")]; break;
4017 case 1: [close_ setTitle:CYLocalize("CLOSE_CYDIA")]; break;
4018 case 2: [close_ setTitle:CYLocalize("RESTART_SPRINGBOARD")]; break;
4019 case 3: [close_ setTitle:CYLocalize("RELOAD_SPRINGBOARD")]; break;
4020 case 4: [close_ setTitle:CYLocalize("REBOOT_DEVICE")]; break;
4023 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4025 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
4026 [cache autorelease];
4028 NSFileManager *manager = [NSFileManager defaultManager];
4029 NSError *error = nil;
4031 id system = [cache objectForKey:@"System"];
4036 if (stat(Cache_, &info) == -1)
4039 [system removeAllObjects];
4041 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4042 for (NSString *app in apps)
4043 if ([app hasSuffix:@".app"]) {
4044 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4045 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4046 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4048 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4049 [info setObject:path forKey:@"Path"];
4050 [info setObject:@"System" forKey:@"ApplicationType"];
4051 [system addInfoDictionary:info];
4057 [cache writeToFile:@Cache_ atomically:YES];
4059 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
4061 if (chmod(Cache_, info.st_mode) == -1)
4065 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4068 notify_post("com.apple.mobile.application_installed");
4070 [delegate_ setStatusBarShowsProgress:NO];
4073 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4074 [[data target] performSelector:[data selector] withObject:[data object]];
4077 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4080 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4081 UINavigationItem *item = [navbar_ topItem];
4082 [item setTitle:title];
4084 [status_ setText:nil];
4085 [output_ setText:@""];
4086 [progress_ setProgress:0];
4088 [close_ removeFromSuperview];
4089 [overlay_ addSubview:progress_];
4090 [overlay_ addSubview:status_];
4092 [delegate_ setStatusBarShowsProgress:YES];
4096 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4097 MMap mmap(file, MMap::ReadOnly);
4099 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4100 sandplate_ = sha1.Result();
4104 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4105 MMap mmap(file, MMap::ReadOnly);
4107 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4108 notifyconf_ = sha1.Result();
4112 FileFd file(SpringBoard_, FileFd::ReadOnly);
4113 MMap mmap(file, MMap::ReadOnly);
4115 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4116 springlist_ = sha1.Result();
4119 [transition_ transition:6 toView:overlay_];
4122 detachNewThreadSelector:@selector(_detachNewThreadData:)
4124 withObject:[[ProgressData alloc]
4125 initWithSelector:selector
4132 - (void) repairWithSelector:(SEL)selector {
4134 detachNewThreadSelector:selector
4137 title:CYLocalize("REPAIRING")
4141 - (void) setConfigurationData:(NSString *)data {
4143 performSelectorOnMainThread:@selector(_setConfigurationData:)
4149 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4150 Package *package = id == nil ? nil : [database_ packageWithName:id];
4152 UIActionSheet *sheet = [[[UIActionSheet alloc]
4153 initWithTitle:(package == nil ? id : [package name])
4154 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
4155 defaultButtonIndex:0
4160 [sheet setBodyText:error];
4161 [sheet popupAlertAnimated:YES];
4164 - (void) setProgressTitle:(NSString *)title {
4166 performSelectorOnMainThread:@selector(_setProgressTitle:)
4172 - (void) setProgressPercent:(float)percent {
4174 performSelectorOnMainThread:@selector(_setProgressPercent:)
4175 withObject:[NSNumber numberWithFloat:percent]
4180 - (void) startProgress {
4183 - (void) addProgressOutput:(NSString *)output {
4185 performSelectorOnMainThread:@selector(_addProgressOutput:)
4191 - (bool) isCancelling:(size_t)received {
4195 - (void) _setConfigurationData:(NSString *)data {
4196 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4198 _assert(conffile_r(data));
4200 NSString *ofile = conffile_r[1];
4201 //NSString *nfile = conffile_r[2];
4203 UIActionSheet *sheet = [[[UIActionSheet alloc]
4204 initWithTitle:CYLocalize("CONFIGURATION_UPGRADE")
4205 buttons:[NSArray arrayWithObjects:
4206 CYLocalize("KEEP_OLD_COPY"),
4207 CYLocalize("ACCEPT_NEW_COPY"),
4208 // XXX: CYLocalize("SEE_WHAT_CHANGED"),
4210 defaultButtonIndex:0
4215 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", CYLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4216 [sheet popupAlertAnimated:YES];
4219 - (void) _setProgressTitle:(NSString *)title {
4220 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4221 for (size_t i(0), e([words count]); i != e; ++i) {
4222 NSString *word([words objectAtIndex:i]);
4223 if (Package *package = [database_ packageWithName:word])
4224 [words replaceObjectAtIndex:i withObject:[package name]];
4227 [status_ setText:[words componentsJoinedByString:@" "]];
4230 - (void) _setProgressPercent:(NSNumber *)percent {
4231 [progress_ setProgress:[percent floatValue]];
4234 - (void) _addProgressOutput:(NSString *)output {
4235 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4236 CGSize size = [output_ contentSize];
4237 CGRect rect = {{0, size.height}, {size.width, 0}};
4238 [output_ scrollRectToVisible:rect animated:YES];
4241 - (BOOL) isRunning {
4248 /* Package Cell {{{ */
4249 @interface PackageCell : UITableCell {
4252 NSString *description_;
4259 UITextLabel *status_;
4263 - (PackageCell *) init;
4264 - (void) setPackage:(Package *)package;
4266 + (int) heightForPackage:(Package *)package;
4270 @implementation PackageCell
4272 - (void) clearPackage {
4283 if (description_ != nil) {
4284 [description_ release];
4288 if (source_ != nil) {
4293 if (badge_ != nil) {
4303 [self clearPackage];
4310 - (PackageCell *) init {
4311 if ((self = [super init]) != nil) {
4313 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4314 [status_ setBackgroundColor:[UIColor clearColor]];
4315 [status_ setFont:small];
4320 - (void) setPackage:(Package *)package {
4321 [self clearPackage];
4323 Source *source = [package source];
4325 icon_ = [[package icon] retain];
4326 name_ = [[package name] retain];
4327 description_ = [[package shortDescription] retain];
4328 commercial_ = [package isCommercial];
4330 package_ = [package retain];
4332 NSString *label = nil;
4333 bool trusted = false;
4335 if (source != nil) {
4336 label = [source label];
4337 trusted = [source trusted];
4338 } else if ([[package id] isEqualToString:@"firmware"])
4339 label = CYLocalize("APPLE");
4341 label = [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("UNKNOWN"), CYLocalize("LOCAL")];
4343 NSString *from(label);
4345 NSString *section = [package simpleSection];
4346 if (section != nil && ![section isEqualToString:label]) {
4347 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4348 from = [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), from, section];
4351 from = [NSString stringWithFormat:CYLocalize("FROM"), from];
4352 source_ = [from retain];
4354 if (NSString *purpose = [package primaryPurpose])
4355 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4356 badge_ = [badge_ retain];
4359 if (NSString *mode = [package mode]) {
4360 [badge_ setImage:[UIImage applicationImageNamed:
4361 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4364 [status_ setText:[NSString stringWithFormat:CYLocalize("QUEUED_FOR"), CYLocalize(mode)]];
4365 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4366 } else if ([package half]) {
4367 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4368 [status_ setText:CYLocalize("PACKAGE_DAMAGED")];
4369 [status_ setColor:[UIColor redColor]];
4371 [badge_ setImage:nil];
4372 [status_ setText:nil];
4379 - (void) drawRect:(CGRect)rect {
4383 if (NSString *mode = [package_ mode]) {
4384 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4385 color = remove ? RemovingColor_ : InstallingColor_;
4387 color = [UIColor whiteColor];
4389 [self setBackgroundColor:color];
4393 [super drawRect:rect];
4396 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4398 CGContextRef context(UIGraphicsGetCurrentContext());
4399 [[self backgroundColor] set];
4401 back.size.height -= 1;
4402 CGContextFillRect(context, back);
4405 [super drawBackgroundInRect:rect withFade:fade];
4408 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4411 rect.size = [icon_ size];
4413 rect.size.width /= 2;
4414 rect.size.height /= 2;
4416 rect.origin.x = 25 - rect.size.width / 2;
4417 rect.origin.y = 25 - rect.size.height / 2;
4419 [icon_ drawInRect:rect];
4422 if (badge_ != nil) {
4423 CGSize size = [badge_ size];
4425 [badge_ drawAtPoint:CGPointMake(
4426 36 - size.width / 2,
4427 36 - size.height / 2
4435 UISetColor(commercial_ ? Purple_ : Black_);
4436 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4437 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4440 UISetColor(commercial_ ? Purplish_ : Gray_);
4441 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4443 [super drawContentInRect:rect selected:selected];
4446 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4448 [super setSelected:selected withFade:fade];
4451 + (int) heightForPackage:(Package *)package {
4452 NSString *tagline([package shortDescription]);
4453 int height = tagline == nil || [tagline length] == 0 ? -17 : 0;
4455 if ([package hasMode] || [package half])
4464 /* Section Cell {{{ */
4465 @interface SectionCell : UISimpleTableCell {
4470 _UISwitchSlider *switch_;
4475 - (void) setSection:(Section *)section editing:(BOOL)editing;
4479 @implementation SectionCell
4481 - (void) clearSection {
4482 if (section_ != nil) {
4492 if (count_ != nil) {
4499 [self clearSection];
4506 if ((self = [super init]) != nil) {
4507 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4509 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4510 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4514 - (void) onSwitch:(id)sender {
4515 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4516 if (metadata == nil) {
4517 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4518 [Sections_ setObject:metadata forKey:section_];
4522 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4525 - (void) setSection:(Section *)section editing:(BOOL)editing {
4526 if (editing != editing_) {
4528 [switch_ removeFromSuperview];
4530 [self addSubview:switch_];
4534 [self clearSection];
4536 if (section == nil) {
4537 name_ = [CYLocalize("ALL_PACKAGES") retain];
4540 section_ = [section localized];
4541 if (section_ != nil)
4542 section_ = [section_ retain];
4543 name_ = [(section_ == nil ? CYLocalize("NO_SECTION") : section_) retain];
4544 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4547 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4551 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4552 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4559 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4561 CGSize size = [count_ sizeWithFont:Font14_];
4565 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4567 [super drawContentInRect:rect selected:selected];
4573 /* File Table {{{ */
4574 @interface FileTable : RVPage {
4575 _transient Database *database_;
4578 NSMutableArray *files_;
4582 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4583 - (void) setPackage:(Package *)package;
4587 @implementation FileTable
4590 if (package_ != nil)
4599 - (int) numberOfRowsInTable:(UITable *)table {
4600 return files_ == nil ? 0 : [files_ count];
4603 - (float) table:(UITable *)table heightForRow:(int)row {
4607 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4608 if (reusing == nil) {
4609 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4610 UIFont *font = [UIFont systemFontOfSize:16];
4611 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4613 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4617 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4621 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4622 if ((self = [super initWithBook:book]) != nil) {
4623 database_ = database;
4625 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4627 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4628 [self addSubview:list_];
4630 UITableColumn *column = [[[UITableColumn alloc]
4631 initWithTitle:CYLocalize("NAME")
4633 width:[self frame].size.width
4636 [list_ setDataSource:self];
4637 [list_ setSeparatorStyle:1];
4638 [list_ addTableColumn:column];
4639 [list_ setDelegate:self];
4640 [list_ setReusesTableCells:YES];
4644 - (void) setPackage:(Package *)package {
4645 if (package_ != nil) {
4646 [package_ autorelease];
4655 [files_ removeAllObjects];
4657 if (package != nil) {
4658 package_ = [package retain];
4659 name_ = [[package id] retain];
4661 if (NSArray *files = [package files])
4662 [files_ addObjectsFromArray:files];
4664 if ([files_ count] != 0) {
4665 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4666 [files_ removeObjectAtIndex:0];
4667 [files_ sortUsingSelector:@selector(compareByPath:)];
4669 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4670 [stack addObject:@"/"];
4672 for (int i(0), e([files_ count]); i != e; ++i) {
4673 NSString *file = [files_ objectAtIndex:i];
4674 while (![file hasPrefix:[stack lastObject]])
4675 [stack removeLastObject];
4676 NSString *directory = [stack lastObject];
4677 [stack addObject:[file stringByAppendingString:@"/"]];
4678 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4679 ([stack count] - 2) * 3, "",
4680 [file substringFromIndex:[directory length]]
4689 - (void) resetViewAnimated:(BOOL)animated {
4690 [list_ resetViewAnimated:animated];
4693 - (void) reloadData {
4694 [self setPackage:[database_ packageWithName:name_]];
4695 [self reloadButtons];
4698 - (NSString *) title {
4699 return CYLocalize("INSTALLED_FILES");
4702 - (NSString *) backButtonTitle {
4703 return CYLocalize("FILES");
4708 /* Package View {{{ */
4709 @interface PackageView : BrowserView {
4710 _transient Database *database_;
4714 NSMutableArray *buttons_;
4717 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4718 - (void) setPackage:(Package *)package;
4722 @implementation PackageView
4725 if (package_ != nil)
4734 if ([self retainCount] == 1)
4735 [delegate_ setPackageView:self];
4739 /* XXX: this is not safe at all... localization of /fail/ */
4740 - (void) _clickButtonWithName:(NSString *)name {
4741 if ([name isEqualToString:CYLocalize("CLEAR")])
4742 [delegate_ clearPackage:package_];
4743 else if ([name isEqualToString:CYLocalize("INSTALL")])
4744 [delegate_ installPackage:package_];
4745 else if ([name isEqualToString:CYLocalize("REINSTALL")])
4746 [delegate_ installPackage:package_];
4747 else if ([name isEqualToString:CYLocalize("REMOVE")])
4748 [delegate_ removePackage:package_];
4749 else if ([name isEqualToString:CYLocalize("UPGRADE")])
4750 [delegate_ installPackage:package_];
4751 else _assert(false);
4754 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4755 NSString *context([sheet context]);
4757 if ([context isEqualToString:@"modify"]) {
4758 int count = [buttons_ count];
4759 _assert(count != 0);
4760 _assert(button <= count + 1);
4762 if (count != button - 1)
4763 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
4767 [super alertSheet:sheet buttonClicked:button];
4770 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
4771 return [super webView:sender didFinishLoadForFrame:frame];
4774 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4775 [super webView:sender didClearWindowObject:window forFrame:frame];
4776 [window setValue:package_ forKey:@"package"];
4779 - (bool) _allowJavaScriptPanel {
4784 - (void) __rightButtonClicked {
4785 int count = [buttons_ count];
4786 _assert(count != 0);
4789 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
4791 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
4792 [buttons addObjectsFromArray:buttons_];
4793 [buttons addObject:CYLocalize("CANCEL")];
4795 [delegate_ slideUp:[[[UIActionSheet alloc]
4798 defaultButtonIndex:([buttons count] - 1)
4805 - (void) _rightButtonClicked {
4807 [super _rightButtonClicked];
4809 [self __rightButtonClicked];
4813 - (id) _rightButtonTitle {
4814 int count = [buttons_ count];
4815 return count == 0 ? nil : count != 1 ? CYLocalize("MODIFY") : [buttons_ objectAtIndex:0];
4818 - (NSString *) backButtonTitle {
4822 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4823 if ((self = [super initWithBook:book]) != nil) {
4824 database_ = database;
4825 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
4826 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
4830 - (void) setPackage:(Package *)package {
4831 if (package_ != nil) {
4832 [package_ autorelease];
4841 [buttons_ removeAllObjects];
4843 if (package != nil) {
4844 package_ = [package retain];
4845 name_ = [[package id] retain];
4846 commercial_ = [package isCommercial];
4848 if ([package_ mode] != nil)
4849 [buttons_ addObject:CYLocalize("CLEAR")];
4850 if ([package_ source] == nil);
4851 else if ([package_ upgradableAndEssential:NO])
4852 [buttons_ addObject:CYLocalize("UPGRADE")];
4853 else if ([package_ installed] == nil)
4854 [buttons_ addObject:CYLocalize("INSTALL")];
4856 [buttons_ addObject:CYLocalize("REINSTALL")];
4857 if ([package_ installed] != nil)
4858 [buttons_ addObject:CYLocalize("REMOVE")];
4860 if (special_ != NULL) {
4861 CGRect frame([webview_ frame]);
4862 frame.size.width = 320;
4863 frame.size.height = 0;
4864 [webview_ setFrame:frame];
4866 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
4869 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
4871 [self setButtonTitle:nil withStyle:nil toFunction:nil];
4873 [self setFinishHook:nil];
4874 [self setPopupHook:nil];
4877 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
4878 [super callFunction:special_];
4882 [self reloadButtons];
4885 - (bool) isLoading {
4886 return commercial_ ? [super isLoading] : false;
4889 - (void) reloadData {
4890 [self setPackage:[database_ packageWithName:name_]];
4895 /* Package Table {{{ */
4896 @interface PackageTable : RVPage {
4897 _transient Database *database_;
4899 NSMutableArray *packages_;
4900 NSMutableArray *sections_;
4901 UISectionList *list_;
4904 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
4906 - (void) setDelegate:(id)delegate;
4908 - (void) reloadData;
4909 - (void) resetCursor;
4911 - (UISectionList *) list;
4913 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
4917 @implementation PackageTable
4920 [list_ setDataSource:nil];
4923 [packages_ release];
4924 [sections_ release];
4929 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
4930 return [sections_ count];
4933 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
4934 return [[sections_ objectAtIndex:section] name];
4937 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
4938 return [[sections_ objectAtIndex:section] row];
4941 - (int) numberOfRowsInTable:(UITable *)table {
4942 return [packages_ count];
4945 - (float) table:(UITable *)table heightForRow:(int)row {
4946 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
4949 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4951 reusing = [[[PackageCell alloc] init] autorelease];
4952 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
4956 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
4960 - (void) tableRowSelected:(NSNotification *)notification {
4961 int row = [[notification object] selectedRow];
4965 Package *package = [packages_ objectAtIndex:row];
4966 package = [database_ packageWithName:[package id]];
4967 PackageView *view([delegate_ packageView]);
4968 [view setPackage:package];
4969 [view setDelegate:delegate_];
4970 [book_ pushPage:view];
4973 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
4974 if ((self = [super initWithBook:book]) != nil) {
4975 database_ = database;
4976 title_ = [title retain];
4978 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
4979 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
4981 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
4982 [list_ setDataSource:self];
4984 UITableColumn *column = [[[UITableColumn alloc]
4985 initWithTitle:CYLocalize("NAME")
4987 width:[self frame].size.width
4990 UITable *table = [list_ table];
4991 [table setSeparatorStyle:1];
4992 [table addTableColumn:column];
4993 [table setDelegate:self];
4994 [table setReusesTableCells:YES];
4996 [self addSubview:list_];
4998 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
4999 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5003 - (void) setDelegate:(id)delegate {
5004 delegate_ = delegate;
5007 - (bool) hasPackage:(Package *)package {
5011 - (void) reloadData {
5012 NSArray *packages = [database_ packages];
5014 [packages_ removeAllObjects];
5015 [sections_ removeAllObjects];
5017 _profile(PackageTable$reloadData$Filter)
5018 for (Package *package in packages)
5019 if ([self hasPackage:package])
5020 [packages_ addObject:package];
5023 Section *section = nil;
5025 _profile(PackageTable$reloadData$Section)
5026 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5030 _profile(PackageTable$reloadData$Section$Package)
5031 package = [packages_ objectAtIndex:offset];
5032 index = [package index];
5035 if (section == nil || [section index] != index) {
5036 _profile(PackageTable$reloadData$Section$Allocate)
5037 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5040 _profile(PackageTable$reloadData$Section$Add)
5041 [sections_ addObject:section];
5045 [section addToCount];
5049 _profile(PackageTable$reloadData$List)
5054 - (NSString *) title {
5058 - (void) resetViewAnimated:(BOOL)animated {
5059 [list_ resetViewAnimated:animated];
5062 - (void) resetCursor {
5063 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
5066 - (UISectionList *) list {
5070 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5071 [list_ setShouldHideHeaderInShortLists:hide];
5076 /* Filtered Package Table {{{ */
5077 @interface FilteredPackageTable : PackageTable {
5083 - (void) setObject:(id)object;
5085 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5089 @implementation FilteredPackageTable
5097 - (void) setObject:(id)object {
5103 object_ = [object retain];
5106 - (bool) hasPackage:(Package *)package {
5107 _profile(FilteredPackageTable$hasPackage)
5108 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5112 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5113 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5115 object_ = object == nil ? nil : [object retain];
5117 /* XXX: this is an unsafe optimization of doomy hell */
5118 Method method = class_getInstanceMethod([Package class], filter);
5119 _assert(method != NULL);
5120 imp_ = method_getImplementation(method);
5121 _assert(imp_ != NULL);
5130 /* Add Source View {{{ */
5131 @interface AddSourceView : RVPage {
5132 _transient Database *database_;
5135 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5139 @implementation AddSourceView
5141 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5142 if ((self = [super initWithBook:book]) != nil) {
5143 database_ = database;
5149 /* Source Cell {{{ */
5150 @interface SourceCell : UITableCell {
5153 NSString *description_;
5159 - (SourceCell *) initWithSource:(Source *)source;
5163 @implementation SourceCell
5168 [description_ release];
5173 - (SourceCell *) initWithSource:(Source *)source {
5174 if ((self = [super init]) != nil) {
5176 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5178 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5179 icon_ = [icon_ retain];
5181 origin_ = [[source name] retain];
5182 label_ = [[source uri] retain];
5183 description_ = [[source description] retain];
5187 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5189 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5196 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5200 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5204 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5206 [super drawContentInRect:rect selected:selected];
5211 /* Source Table {{{ */
5212 @interface SourceTable : RVPage {
5213 _transient Database *database_;
5214 UISectionList *list_;
5215 NSMutableArray *sources_;
5216 UIActionSheet *alert_;
5220 UIProgressHUD *hud_;
5223 //NSURLConnection *installer_;
5224 NSURLConnection *trivial_bz2_;
5225 NSURLConnection *trivial_gz_;
5226 //NSURLConnection *automatic_;
5231 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5235 @implementation SourceTable
5237 - (void) _deallocConnection:(NSURLConnection *)connection {
5238 if (connection != nil) {
5239 [connection cancel];
5240 //[connection setDelegate:nil];
5241 [connection release];
5246 [[list_ table] setDelegate:nil];
5247 [list_ setDataSource:nil];
5256 //[self _deallocConnection:installer_];
5257 [self _deallocConnection:trivial_gz_];
5258 [self _deallocConnection:trivial_bz2_];
5259 //[self _deallocConnection:automatic_];
5266 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5267 return offset_ == 0 ? 1 : 2;
5270 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5271 switch (section + (offset_ == 0 ? 1 : 0)) {
5272 case 0: return CYLocalize("ENTERED_BY_USER");
5273 case 1: return CYLocalize("INSTALLED_BY_PACKAGE");
5281 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5282 switch (section + (offset_ == 0 ? 1 : 0)) {
5284 case 1: return offset_;
5292 - (int) numberOfRowsInTable:(UITable *)table {
5293 return [sources_ count];
5296 - (float) table:(UITable *)table heightForRow:(int)row {
5297 Source *source = [sources_ objectAtIndex:row];
5298 return [source description] == nil ? 56 : 73;
5301 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5302 Source *source = [sources_ objectAtIndex:row];
5303 // XXX: weird warning, stupid selectors ;P
5304 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5307 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5311 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5315 - (void) tableRowSelected:(NSNotification*)notification {
5316 UITable *table([list_ table]);
5317 int row([table selectedRow]);
5321 Source *source = [sources_ objectAtIndex:row];
5323 PackageTable *packages = [[[FilteredPackageTable alloc]
5326 title:[source label]
5327 filter:@selector(isVisibleInSource:)
5331 [packages setDelegate:delegate_];
5333 [book_ pushPage:packages];
5336 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5337 Source *source = [sources_ objectAtIndex:row];
5338 return [source record] != nil;
5341 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5342 [[list_ table] setDeleteConfirmationRow:row];
5345 - (void) table:(UITable *)table deleteRow:(int)row {
5346 Source *source = [sources_ objectAtIndex:row];
5347 [Sources_ removeObjectForKey:[source key]];
5348 [delegate_ syncData];
5352 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5355 @"./", @"Distribution",
5356 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5358 [delegate_ syncData];
5361 - (NSString *) getWarning {
5362 NSString *href(href_);
5363 NSRange colon([href rangeOfString:@"://"]);
5364 if (colon.location != NSNotFound)
5365 href = [href substringFromIndex:(colon.location + 3)];
5366 href = [href stringByAddingPercentEscapes];
5367 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5368 href = [href stringByCachingURLWithCurrentCDN];
5370 NSURL *url([NSURL URLWithString:href]);
5372 NSStringEncoding encoding;
5373 NSError *error(nil);
5375 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5376 return [warning length] == 0 ? nil : warning;
5380 - (void) _endConnection:(NSURLConnection *)connection {
5381 NSURLConnection **field = NULL;
5382 if (connection == trivial_bz2_)
5383 field = &trivial_bz2_;
5384 else if (connection == trivial_gz_)
5385 field = &trivial_gz_;
5386 _assert(field != NULL);
5387 [connection release];
5391 trivial_bz2_ == nil &&
5397 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5400 UIActionSheet *sheet = [[[UIActionSheet alloc]
5401 initWithTitle:CYLocalize("SOURCE_WARNING")
5402 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_ANYWAY"), CYLocalize("CANCEL"), nil]
5403 defaultButtonIndex:0
5408 [sheet setNumberOfRows:1];
5410 [sheet setBodyText:warning];
5411 [sheet popupAlertAnimated:YES];
5414 } else if (error_ != nil) {
5415 UIActionSheet *sheet = [[[UIActionSheet alloc]
5416 initWithTitle:CYLocalize("VERIFICATION_ERROR")
5417 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5418 defaultButtonIndex:0
5423 [sheet setBodyText:[error_ localizedDescription]];
5424 [sheet popupAlertAnimated:YES];
5426 UIActionSheet *sheet = [[[UIActionSheet alloc]
5427 initWithTitle:CYLocalize("NOT_REPOSITORY")
5428 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5429 defaultButtonIndex:0
5434 [sheet setBodyText:CYLocalize("NOT_REPOSITORY_EX")];
5435 [sheet popupAlertAnimated:YES];
5438 [delegate_ setStatusBarShowsProgress:NO];
5439 [delegate_ removeProgressHUD:hud_];
5449 if (error_ != nil) {
5456 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5457 switch ([response statusCode]) {
5463 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5464 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5466 error_ = [error retain];
5467 [self _endConnection:connection];
5470 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5471 [self _endConnection:connection];
5474 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5475 NSMutableURLRequest *request = [NSMutableURLRequest
5476 requestWithURL:[NSURL URLWithString:href]
5477 cachePolicy:NSURLRequestUseProtocolCachePolicy
5478 timeoutInterval:20.0
5481 [request setHTTPMethod:method];
5483 if (Machine_ != NULL)
5484 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5485 if (UniqueID_ != nil)
5486 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5489 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5491 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5494 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5495 NSString *context([sheet context]);
5497 if ([context isEqualToString:@"source"]) {
5500 NSString *href = [[sheet textField] text];
5502 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5504 if (![href hasSuffix:@"/"])
5505 href_ = [href stringByAppendingString:@"/"];
5508 href_ = [href_ retain];
5510 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5511 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5512 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5516 hud_ = [[delegate_ addProgressHUD] retain];
5517 [hud_ setText:CYLocalize("VERIFYING_URL")];
5528 } else if ([context isEqualToString:@"trivial"])
5530 else if ([context isEqualToString:@"urlerror"])
5532 else if ([context isEqualToString:@"warning"]) {
5552 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5553 if ((self = [super initWithBook:book]) != nil) {
5554 database_ = database;
5555 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5557 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5558 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5559 [list_ setShouldHideHeaderInShortLists:NO];
5561 [self addSubview:list_];
5562 [list_ setDataSource:self];
5564 UITableColumn *column = [[UITableColumn alloc]
5565 initWithTitle:CYLocalize("NAME")
5567 width:[self frame].size.width
5570 UITable *table = [list_ table];
5571 [table setSeparatorStyle:1];
5572 [table addTableColumn:column];
5573 [table setDelegate:self];
5577 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5578 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5582 - (void) reloadData {
5584 _assert(list.ReadMainList());
5586 [sources_ removeAllObjects];
5587 [sources_ addObjectsFromArray:[database_ sources]];
5589 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5592 int count = [sources_ count];
5593 for (offset_ = 0; offset_ != count; ++offset_) {
5594 Source *source = [sources_ objectAtIndex:offset_];
5595 if ([source record] == nil)
5602 - (void) resetViewAnimated:(BOOL)animated {
5603 [list_ resetViewAnimated:animated];
5606 - (void) _leftButtonClicked {
5607 /*[book_ pushPage:[[[AddSourceView alloc]
5612 UIActionSheet *sheet = [[[UIActionSheet alloc]
5613 initWithTitle:CYLocalize("ENTER_APT_URL")
5614 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_SOURCE"), CYLocalize("CANCEL"), nil]
5615 defaultButtonIndex:0
5620 [sheet setNumberOfRows:1];
5622 [sheet addTextFieldWithValue:@"http://" label:@""];
5624 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5625 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5626 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5627 [traits setKeyboardType:UIKeyboardTypeURL];
5628 // XXX: UIReturnKeyDone
5629 [traits setReturnKeyType:UIReturnKeyNext];
5631 [sheet popupAlertAnimated:YES];
5634 - (void) _rightButtonClicked {
5635 UITable *table = [list_ table];
5636 BOOL editing = [table isRowDeletionEnabled];
5637 [table enableRowDeletion:!editing animated:YES];
5638 [book_ reloadButtonsForPage:self];
5641 - (NSString *) title {
5642 return CYLocalize("SOURCES");
5645 - (NSString *) leftButtonTitle {
5646 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("ADD") : nil;
5649 - (id) rightButtonTitle {
5650 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("DONE") : CYLocalize("EDIT");
5653 - (UINavigationButtonStyle) rightButtonStyle {
5654 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5660 /* Installed View {{{ */
5661 @interface InstalledView : RVPage {
5662 _transient Database *database_;
5663 FilteredPackageTable *packages_;
5667 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5671 @implementation InstalledView
5674 [packages_ release];
5678 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5679 if ((self = [super initWithBook:book]) != nil) {
5680 database_ = database;
5682 packages_ = [[FilteredPackageTable alloc]
5686 filter:@selector(isInstalledAndVisible:)
5687 with:[NSNumber numberWithBool:YES]
5690 [self addSubview:packages_];
5692 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5693 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5697 - (void) resetViewAnimated:(BOOL)animated {
5698 [packages_ resetViewAnimated:animated];
5701 - (void) reloadData {
5702 [packages_ reloadData];
5705 - (void) _rightButtonClicked {
5706 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5707 [packages_ reloadData];
5709 [book_ reloadButtonsForPage:self];
5712 - (NSString *) title {
5713 return CYLocalize("INSTALLED");
5716 - (NSString *) backButtonTitle {
5717 return CYLocalize("PACKAGES");
5720 - (id) rightButtonTitle {
5721 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? CYLocalize("EXPERT") : CYLocalize("SIMPLE");
5724 - (UINavigationButtonStyle) rightButtonStyle {
5725 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5728 - (void) setDelegate:(id)delegate {
5729 [super setDelegate:delegate];
5730 [packages_ setDelegate:delegate];
5737 @interface HomeView : BrowserView {
5742 @implementation HomeView
5744 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5745 NSString *context([sheet context]);
5747 if ([context isEqualToString:@"about"])
5750 [super alertSheet:sheet buttonClicked:button];
5753 - (void) _leftButtonClicked {
5754 UIActionSheet *sheet = [[[UIActionSheet alloc]
5755 initWithTitle:CYLocalize("ABOUT_CYDIA")
5756 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
5757 defaultButtonIndex:0
5763 @"Copyright (C) 2008-2009\n"
5764 "Jay Freeman (saurik)\n"
5765 "saurik@saurik.com\n"
5766 "http://www.saurik.com/\n"
5769 "http://www.theokorigroup.com/\n"
5771 "College of Creative Studies,\n"
5772 "University of California,\n"
5774 "http://www.ccs.ucsb.edu/"
5777 [sheet popupAlertAnimated:YES];
5780 - (NSString *) leftButtonTitle {
5781 return CYLocalize("ABOUT");
5786 /* Manage View {{{ */
5787 @interface ManageView : BrowserView {
5792 @implementation ManageView
5794 - (NSString *) title {
5795 return CYLocalize("MANAGE");
5798 - (void) _leftButtonClicked {
5799 [delegate_ askForSettings];
5802 - (NSString *) leftButtonTitle {
5803 return CYLocalize("SETTINGS");
5807 - (id) _rightButtonTitle {
5808 return Queuing_ ? CYLocalize("QUEUE") : nil;
5811 - (UINavigationButtonStyle) rightButtonStyle {
5812 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5815 - (void) _rightButtonClicked {
5820 - (bool) isLoading {
5827 #include <BrowserView.m>
5829 /* Cydia Book {{{ */
5830 @interface CYBook : RVBook <
5833 _transient Database *database_;
5834 UINavigationBar *overlay_;
5835 UINavigationBar *underlay_;
5836 UIProgressIndicator *indicator_;
5837 UITextLabel *prompt_;
5838 UIProgressBar *progress_;
5839 UINavigationButton *cancel_;
5843 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
5849 @implementation CYBook
5853 [indicator_ release];
5855 [progress_ release];
5860 - (NSString *) getTitleForPage:(RVPage *)page {
5861 return [super getTitleForPage:page];
5869 [UIView beginAnimations:nil context:NULL];
5871 CGRect ovrframe = [overlay_ frame];
5872 ovrframe.origin.y = 0;
5873 [overlay_ setFrame:ovrframe];
5875 CGRect barframe = [navbar_ frame];
5876 barframe.origin.y += ovrframe.size.height;
5877 [navbar_ setFrame:barframe];
5879 CGRect trnframe = [transition_ frame];
5880 trnframe.origin.y += ovrframe.size.height;
5881 trnframe.size.height -= ovrframe.size.height;
5882 [transition_ setFrame:trnframe];
5884 [UIView endAnimations];
5886 [indicator_ startAnimation];
5887 [prompt_ setText:CYLocalize("UPDATING_DATABASE")];
5888 [progress_ setProgress:0];
5891 [overlay_ addSubview:cancel_];
5894 detachNewThreadSelector:@selector(_update)
5903 [indicator_ stopAnimation];
5905 [UIView beginAnimations:nil context:NULL];
5907 CGRect ovrframe = [overlay_ frame];
5908 ovrframe.origin.y = -ovrframe.size.height;
5909 [overlay_ setFrame:ovrframe];
5911 CGRect barframe = [navbar_ frame];
5912 barframe.origin.y -= ovrframe.size.height;
5913 [navbar_ setFrame:barframe];
5915 CGRect trnframe = [transition_ frame];
5916 trnframe.origin.y -= ovrframe.size.height;
5917 trnframe.size.height += ovrframe.size.height;
5918 [transition_ setFrame:trnframe];
5920 [UIView commitAnimations];
5922 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
5925 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
5926 if ((self = [super initWithFrame:frame]) != nil) {
5927 database_ = database;
5929 CGRect ovrrect = [navbar_ bounds];
5930 ovrrect.size.height = [UINavigationBar defaultSize].height;
5931 ovrrect.origin.y = -ovrrect.size.height;
5933 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5934 [self addSubview:overlay_];
5936 ovrrect.origin.y = frame.size.height;
5937 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5938 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
5939 [self addSubview:underlay_];
5941 [overlay_ setBarStyle:1];
5942 [underlay_ setBarStyle:1];
5944 int barstyle = [overlay_ _barStyle:NO];
5945 bool ugly = barstyle == 0;
5947 UIProgressIndicatorStyle style = ugly ?
5948 UIProgressIndicatorStyleMediumBrown :
5949 UIProgressIndicatorStyleMediumWhite;
5951 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
5952 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
5953 CGRect indrect = {{indoffset, indoffset}, indsize};
5955 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
5956 [indicator_ setStyle:style];
5957 [overlay_ addSubview:indicator_];
5959 CGSize prmsize = {215, indsize.height + 4};
5962 indoffset * 2 + indsize.width,
5966 unsigned(ovrrect.size.height - prmsize.height) / 2
5969 UIFont *font = [UIFont systemFontOfSize:15];
5971 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
5973 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
5974 [prompt_ setBackgroundColor:[UIColor clearColor]];
5975 [prompt_ setFont:font];
5977 [overlay_ addSubview:prompt_];
5979 CGSize prgsize = {75, 100};
5982 ovrrect.size.width - prgsize.width - 10,
5983 (ovrrect.size.height - prgsize.height) / 2
5986 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
5987 [progress_ setStyle:0];
5988 [overlay_ addSubview:progress_];
5990 cancel_ = [[UINavigationButton alloc] initWithTitle:CYLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
5991 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
5993 CGRect frame = [cancel_ frame];
5994 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
5995 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
5996 [cancel_ setFrame:frame];
5998 [cancel_ setBarStyle:barstyle];
6002 - (void) _onCancel {
6004 [cancel_ removeFromSuperview];
6007 - (void) _update { _pooled
6009 status.setDelegate(self);
6011 [database_ updateWithStatus:status];
6014 performSelectorOnMainThread:@selector(_update_)
6020 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
6021 [prompt_ setText:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), error]];
6024 - (void) setProgressTitle:(NSString *)title {
6026 performSelectorOnMainThread:@selector(_setProgressTitle:)
6032 - (void) setProgressPercent:(float)percent {
6034 performSelectorOnMainThread:@selector(_setProgressPercent:)
6035 withObject:[NSNumber numberWithFloat:percent]
6040 - (void) startProgress {
6043 - (void) addProgressOutput:(NSString *)output {
6045 performSelectorOnMainThread:@selector(_addProgressOutput:)
6051 - (bool) isCancelling:(size_t)received {
6055 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6059 - (void) _setProgressTitle:(NSString *)title {
6060 [prompt_ setText:title];
6063 - (void) _setProgressPercent:(NSNumber *)percent {
6064 [progress_ setProgress:[percent floatValue]];
6067 - (void) _addProgressOutput:(NSString *)output {
6072 /* Cydia:// Protocol {{{ */
6073 @interface CydiaURLProtocol : NSURLProtocol {
6078 @implementation CydiaURLProtocol
6080 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6081 NSURL *url([request URL]);
6084 NSString *scheme([[url scheme] lowercaseString]);
6085 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6090 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6094 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6095 id<NSURLProtocolClient> client([self client]);
6097 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6099 NSData *data(UIImagePNGRepresentation(icon));
6101 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6102 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6103 [client URLProtocol:self didLoadData:data];
6104 [client URLProtocolDidFinishLoading:self];
6108 - (void) startLoading {
6109 id<NSURLProtocolClient> client([self client]);
6110 NSURLRequest *request([self request]);
6112 NSURL *url([request URL]);
6113 NSString *href([url absoluteString]);
6115 NSString *path([href substringFromIndex:8]);
6116 NSRange slash([path rangeOfString:@"/"]);
6119 if (slash.location == NSNotFound) {
6123 command = [path substringToIndex:slash.location];
6124 path = [path substringFromIndex:(slash.location + 1)];
6127 Database *database([Database sharedInstance]);
6129 if ([command isEqualToString:@"package-icon"]) {
6132 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6133 Package *package([database packageWithName:path]);
6136 UIImage *icon([package icon]);
6137 [self _returnPNGWithImage:icon forRequest:request];
6138 } else if ([command isEqualToString:@"source-icon"]) {
6141 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6142 NSString *source(Simplify(path));
6143 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6145 icon = [UIImage applicationImageNamed:@"unknown.png"];
6146 [self _returnPNGWithImage:icon forRequest:request];
6147 } else if ([command isEqualToString:@"uikit-image"]) {
6150 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6151 UIImage *icon(_UIImageWithName(path));
6152 [self _returnPNGWithImage:icon forRequest:request];
6153 } else if ([command isEqualToString:@"section-icon"]) {
6156 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6157 NSString *section(Simplify(path));
6158 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6160 icon = [UIImage applicationImageNamed:@"unknown.png"];
6161 [self _returnPNGWithImage:icon forRequest:request];
6163 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6167 - (void) stopLoading {
6173 /* Sections View {{{ */
6174 @interface SectionsView : RVPage {
6175 _transient Database *database_;
6176 NSMutableArray *sections_;
6177 NSMutableArray *filtered_;
6178 UITransitionView *transition_;
6184 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6185 - (void) reloadData;
6190 @implementation SectionsView
6193 [list_ setDataSource:nil];
6194 [list_ setDelegate:nil];
6196 [sections_ release];
6197 [filtered_ release];
6198 [transition_ release];
6200 [accessory_ release];
6204 - (int) numberOfRowsInTable:(UITable *)table {
6205 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6208 - (float) table:(UITable *)table heightForRow:(int)row {
6212 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6214 reusing = [[[SectionCell alloc] init] autorelease];
6215 [(SectionCell *)reusing setSection:(editing_ ?
6216 [sections_ objectAtIndex:row] :
6217 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6218 ) editing:editing_];
6222 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6226 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6230 - (void) tableRowSelected:(NSNotification *)notification {
6231 int row = [[notification object] selectedRow];
6242 title = CYLocalize("ALL_PACKAGES");
6244 section = [filtered_ objectAtIndex:(row - 1)];
6245 name = [section name];
6248 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6251 title = CYLocalize("NO_SECTION");
6255 PackageTable *table = [[[FilteredPackageTable alloc]
6259 filter:@selector(isVisiblyUninstalledInSection:)
6263 [table setDelegate:delegate_];
6265 [book_ pushPage:table];
6268 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6269 if ((self = [super initWithBook:book]) != nil) {
6270 database_ = database;
6272 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6273 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6275 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6276 [self addSubview:transition_];
6278 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6279 [transition_ transition:0 toView:list_];
6281 UITableColumn *column = [[[UITableColumn alloc]
6282 initWithTitle:CYLocalize("NAME")
6284 width:[self frame].size.width
6287 [list_ setDataSource:self];
6288 [list_ setSeparatorStyle:1];
6289 [list_ addTableColumn:column];
6290 [list_ setDelegate:self];
6291 [list_ setReusesTableCells:YES];
6295 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6296 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6300 - (void) reloadData {
6301 NSArray *packages = [database_ packages];
6303 [sections_ removeAllObjects];
6304 [filtered_ removeAllObjects];
6307 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6308 SectionMap sections;
6309 sections.resize(64);
6311 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6315 for (Package *package in packages) {
6316 NSString *name([package section]);
6317 NSString *key(name == nil ? @"" : name);
6322 _profile(SectionsView$reloadData$Section)
6323 section = §ions[key];
6324 if (*section == nil) {
6325 _profile(SectionsView$reloadData$Section$Allocate)
6326 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6331 [*section addToCount];
6333 _profile(SectionsView$reloadData$Filter)
6334 if (![package valid] || [package installed] != nil || ![package visible])
6338 [*section addToRow];
6342 _profile(SectionsView$reloadData$Section)
6343 section = [sections objectForKey:key];
6344 if (section == nil) {
6345 _profile(SectionsView$reloadData$Section$Allocate)
6346 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6347 [sections setObject:section forKey:key];
6352 [section addToCount];
6354 _profile(SectionsView$reloadData$Filter)
6355 if (![package valid] || [package installed] != nil || ![package visible])
6365 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6366 [sections_ addObject:i->second];
6368 [sections_ addObjectsFromArray:[sections allValues]];
6371 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6373 for (Section *section in sections_) {
6374 size_t count([section row]);
6378 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6379 [section setCount:count];
6380 [filtered_ addObject:section];
6387 - (void) resetView {
6389 [self _rightButtonClicked];
6392 - (void) resetViewAnimated:(BOOL)animated {
6393 [list_ resetViewAnimated:animated];
6396 - (void) _rightButtonClicked {
6397 if ((editing_ = !editing_))
6400 [delegate_ updateData];
6401 [book_ reloadTitleForPage:self];
6402 [book_ reloadButtonsForPage:self];
6405 - (NSString *) title {
6406 return editing_ ? CYLocalize("SECTION_VISIBILITY") : CYLocalize("INSTALL_BY_SECTION");
6409 - (NSString *) backButtonTitle {
6410 return CYLocalize("SECTIONS");
6413 - (id) rightButtonTitle {
6414 return [sections_ count] == 0 ? nil : editing_ ? CYLocalize("DONE") : CYLocalize("EDIT");
6417 - (UINavigationButtonStyle) rightButtonStyle {
6418 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6421 - (UIView *) accessoryView {
6427 /* Changes View {{{ */
6428 @interface ChangesView : RVPage {
6429 _transient Database *database_;
6430 NSMutableArray *packages_;
6431 NSMutableArray *sections_;
6432 UISectionList *list_;
6436 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6437 - (void) reloadData;
6441 @implementation ChangesView
6444 [[list_ table] setDelegate:nil];
6445 [list_ setDataSource:nil];
6447 [packages_ release];
6448 [sections_ release];
6453 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6454 return [sections_ count];
6457 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6458 return [[sections_ objectAtIndex:section] name];
6461 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6462 return [[sections_ objectAtIndex:section] row];
6465 - (int) numberOfRowsInTable:(UITable *)table {
6466 return [packages_ count];
6469 - (float) table:(UITable *)table heightForRow:(int)row {
6470 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6473 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6475 reusing = [[[PackageCell alloc] init] autorelease];
6476 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6480 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6484 - (void) tableRowSelected:(NSNotification *)notification {
6485 int row = [[notification object] selectedRow];
6488 Package *package = [packages_ objectAtIndex:row];
6489 PackageView *view([delegate_ packageView]);
6490 [view setDelegate:delegate_];
6491 [view setPackage:package];
6492 [book_ pushPage:view];
6495 - (void) _leftButtonClicked {
6496 [(CYBook *)book_ update];
6497 [self reloadButtons];
6500 - (void) _rightButtonClicked {
6501 [delegate_ distUpgrade];
6504 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6505 if ((self = [super initWithBook:book]) != nil) {
6506 database_ = database;
6508 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6509 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6511 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6512 [self addSubview:list_];
6514 [list_ setShouldHideHeaderInShortLists:NO];
6515 [list_ setDataSource:self];
6516 //[list_ setSectionListStyle:1];
6518 UITableColumn *column = [[[UITableColumn alloc]
6519 initWithTitle:CYLocalize("NAME")
6521 width:[self frame].size.width
6524 UITable *table = [list_ table];
6525 [table setSeparatorStyle:1];
6526 [table addTableColumn:column];
6527 [table setDelegate:self];
6528 [table setReusesTableCells:YES];
6532 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6533 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6537 - (void) reloadData {
6538 NSArray *packages = [database_ packages];
6540 [packages_ removeAllObjects];
6541 [sections_ removeAllObjects];
6544 for (Package *package in packages)
6546 [package installed] == nil && [package valid] && [package visible] ||
6547 [package upgradableAndEssential:YES]
6549 [packages_ addObject:package];
6552 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6555 Section *upgradable = [[[Section alloc] initWithName:CYLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6556 Section *ignored = [[[Section alloc] initWithName:CYLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6557 Section *section = nil;
6561 bool unseens = false;
6563 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6565 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6566 Package *package = [packages_ objectAtIndex:offset];
6568 BOOL uae = [package upgradableAndEssential:YES];
6574 _profile(ChangesView$reloadData$Remember)
6575 seen = [package seen];
6578 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6583 name = CYLocalize("UNKNOWN");
6585 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6589 _profile(ChangesView$reloadData$Allocate)
6590 name = [NSString stringWithFormat:CYLocalize("NEW_AT"), name];
6591 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6592 [sections_ addObject:section];
6596 [section addToCount];
6597 } else if ([package ignored])
6598 [ignored addToCount];
6601 [upgradable addToCount];
6606 CFRelease(formatter);
6609 Section *last = [sections_ lastObject];
6610 size_t count = [last count];
6611 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6612 [sections_ removeLastObject];
6615 if ([ignored count] != 0)
6616 [sections_ insertObject:ignored atIndex:0];
6618 [sections_ insertObject:upgradable atIndex:0];
6621 [self reloadButtons];
6624 - (void) resetViewAnimated:(BOOL)animated {
6625 [list_ resetViewAnimated:animated];
6628 - (NSString *) leftButtonTitle {
6629 return [(CYBook *)book_ updating] ? nil : CYLocalize("REFRESH");
6632 - (id) rightButtonTitle {
6633 return upgrades_ == 0 ? nil : [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6636 - (NSString *) title {
6637 return CYLocalize("CHANGES");
6642 /* Search View {{{ */
6643 @protocol SearchViewDelegate
6644 - (void) showKeyboard:(BOOL)show;
6647 @interface SearchView : RVPage {
6649 UISearchField *field_;
6650 UITransitionView *transition_;
6651 FilteredPackageTable *table_;
6652 UIPreferencesTable *advanced_;
6658 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6659 - (void) reloadData;
6663 @implementation SearchView
6666 [field_ setDelegate:nil];
6668 [accessory_ release];
6670 [transition_ release];
6672 [advanced_ release];
6677 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6681 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6683 case 0: return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("ADVANCED_SEARCH"), CYLocalize("COMING_SOON")];
6685 default: _assert(false);
6689 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6693 default: _assert(false);
6697 - (void) _showKeyboard:(BOOL)show {
6698 CGSize keysize = [UIKeyboard defaultSize];
6699 CGRect keydown = [book_ pageBounds];
6700 CGRect keyup = keydown;
6701 keyup.size.height -= keysize.height - ButtonBarHeight_;
6703 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6705 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6706 [animation setSignificantRectFields:8];
6709 [animation setStartFrame:keydown];
6710 [animation setEndFrame:keyup];
6712 [animation setStartFrame:keyup];
6713 [animation setEndFrame:keydown];
6716 UIAnimator *animator = [UIAnimator sharedAnimator];
6719 addAnimations:[NSArray arrayWithObjects:animation, nil]
6720 withDuration:(KeyboardTime_ - delay)
6725 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6727 [delegate_ showKeyboard:show];
6730 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6731 [self _showKeyboard:YES];
6734 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
6735 [self _showKeyboard:NO];
6738 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
6740 NSString *text([field_ text]);
6741 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6747 - (void) textFieldClearButtonPressed:(UITextField *)field {
6751 - (void) keyboardInputShouldDelete:(id)input {
6755 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
6756 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6760 [field_ resignFirstResponder];
6765 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6766 if ((self = [super initWithBook:book]) != nil) {
6767 CGRect pageBounds = [book_ pageBounds];
6769 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6770 [self addSubview:transition_];
6772 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6774 [advanced_ setReusesTableCells:YES];
6775 [advanced_ setDataSource:self];
6776 [advanced_ reloadData];
6778 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6779 CGColor dimmed(space_, 0, 0, 0, 0.5);
6780 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
6782 table_ = [[FilteredPackageTable alloc]
6786 filter:@selector(isUnfilteredAndSearchedForBy:)
6790 [table_ setShouldHideHeaderInShortLists:NO];
6791 [transition_ transition:0 toView:table_];
6800 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
6807 [self bounds].size.width - area.origin.x - 18;
6809 area.size.height = [UISearchField defaultHeight];
6811 field_ = [[UISearchField alloc] initWithFrame:area];
6813 UIFont *font = [UIFont systemFontOfSize:16];
6814 [field_ setFont:font];
6816 [field_ setPlaceholder:CYLocalize("SEARCH_EX")];
6817 [field_ setDelegate:self];
6819 [field_ setPaddingTop:5];
6821 UITextInputTraits *traits([field_ textInputTraits]);
6822 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6823 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6824 [traits setReturnKeyType:UIReturnKeySearch];
6826 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
6828 accessory_ = [[UIView alloc] initWithFrame:accrect];
6829 [accessory_ addSubview:field_];
6831 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
6832 [configure setShowPressFeedback:YES];
6833 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
6834 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
6835 [accessory_ addSubview:configure];*/
6837 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6838 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6844 LKAnimation *animation = [LKTransition animation];
6845 [animation setType:@"oglFlip"];
6846 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
6847 [animation setFillMode:@"extended"];
6848 [animation setTransitionFlags:3];
6849 [animation setDuration:10];
6850 [animation setSpeed:0.35];
6851 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
6852 [[transition_ _layer] addAnimation:animation forKey:0];
6853 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
6854 flipped_ = !flipped_;
6858 - (void) configurePushed {
6859 [field_ resignFirstResponder];
6863 - (void) resetViewAnimated:(BOOL)animated {
6866 [table_ resetViewAnimated:animated];
6869 - (void) _reloadData {
6872 - (void) reloadData {
6875 [table_ setObject:[field_ text]];
6876 _profile(SearchView$reloadData)
6877 [table_ reloadData];
6880 [table_ resetCursor];
6883 - (UIView *) accessoryView {
6887 - (NSString *) title {
6891 - (NSString *) backButtonTitle {
6892 return CYLocalize("SEARCH");
6895 - (void) setDelegate:(id)delegate {
6896 [table_ setDelegate:delegate];
6897 [super setDelegate:delegate];
6903 @interface SettingsView : RVPage {
6904 _transient Database *database_;
6907 UIPreferencesTable *table_;
6908 _UISwitchSlider *subscribedSwitch_;
6909 _UISwitchSlider *ignoredSwitch_;
6910 UIPreferencesControlTableCell *subscribedCell_;
6911 UIPreferencesControlTableCell *ignoredCell_;
6914 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6918 @implementation SettingsView
6921 [table_ setDataSource:nil];
6924 if (package_ != nil)
6927 [subscribedSwitch_ release];
6928 [ignoredSwitch_ release];
6929 [subscribedCell_ release];
6930 [ignoredCell_ release];
6934 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6935 if (package_ == nil)
6941 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6942 if (package_ == nil)
6949 default: _assert(false);
6955 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
6956 if (package_ == nil)
6963 default: _assert(false);
6969 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6970 if (package_ == nil)
6977 default: _assert(false);
6983 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
6984 if (package_ == nil)
6987 _UISwitchSlider *slider([cell control]);
6988 BOOL value([slider value] != 0);
6989 NSMutableDictionary *metadata([package_ metadata]);
6992 if (NSNumber *number = [metadata objectForKey:key])
6993 before = [number boolValue];
6997 if (value != before) {
6998 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7000 [delegate_ updateData];
7004 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7005 [self onSomething:cell withKey:@"IsSubscribed"];
7008 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7009 [self onSomething:cell withKey:@"IsIgnored"];
7012 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7013 if (package_ == nil)
7017 case 0: switch (row) {
7019 return subscribedCell_;
7021 return ignoredCell_;
7022 default: _assert(false);
7025 case 1: switch (row) {
7027 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7028 [cell setShowSelection:NO];
7029 [cell setTitle:CYLocalize("SHOW_ALL_CHANGES_EX")];
7033 default: _assert(false);
7036 default: _assert(false);
7042 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7043 if ((self = [super initWithBook:book])) {
7044 database_ = database;
7045 name_ = [package retain];
7047 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7048 [self addSubview:table_];
7050 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7051 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
7053 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7054 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
7056 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7057 [subscribedCell_ setShowSelection:NO];
7058 [subscribedCell_ setTitle:CYLocalize("SHOW_ALL_CHANGES")];
7059 [subscribedCell_ setControl:subscribedSwitch_];
7061 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7062 [ignoredCell_ setShowSelection:NO];
7063 [ignoredCell_ setTitle:CYLocalize("IGNORE_UPGRADES")];
7064 [ignoredCell_ setControl:ignoredSwitch_];
7066 [table_ setDataSource:self];
7071 - (void) resetViewAnimated:(BOOL)animated {
7072 [table_ resetViewAnimated:animated];
7075 - (void) reloadData {
7076 if (package_ != nil)
7077 [package_ autorelease];
7078 package_ = [database_ packageWithName:name_];
7079 if (package_ != nil) {
7081 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7082 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7085 [table_ reloadData];
7088 - (NSString *) title {
7089 return CYLocalize("SETTINGS");
7094 /* Signature View {{{ */
7095 @interface SignatureView : BrowserView {
7096 _transient Database *database_;
7100 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7104 @implementation SignatureView
7111 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7113 [super webView:sender didClearWindowObject:window forFrame:frame];
7116 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7117 if ((self = [super initWithBook:book]) != nil) {
7118 database_ = database;
7119 package_ = [package retain];
7124 - (void) resetViewAnimated:(BOOL)animated {
7127 - (void) reloadData {
7128 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7134 @interface Cydia : UIApplication <
7135 ConfirmationViewDelegate,
7136 ProgressViewDelegate,
7145 UIToolbar *buttonbar_;
7149 NSMutableArray *essential_;
7150 NSMutableArray *broken_;
7152 Database *database_;
7153 ProgressView *progress_;
7157 UIKeyboard *keyboard_;
7158 UIProgressHUD *hud_;
7160 SectionsView *sections_;
7161 ChangesView *changes_;
7162 ManageView *manage_;
7163 SearchView *search_;
7165 PackageView *package_;
7170 @implementation Cydia
7173 if ([broken_ count] != 0) {
7174 int count = [broken_ count];
7176 UIActionSheet *sheet = [[[UIActionSheet alloc]
7177 initWithTitle:(count == 1 ? CYLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:CYLocalize("HALFINSTALLED_PACKAGES"), count])
7178 buttons:[NSArray arrayWithObjects:
7179 CYLocalize("FORCIBLY_CLEAR"),
7180 CYLocalize("TEMPORARY_IGNORE"),
7182 defaultButtonIndex:0
7187 [sheet setBodyText:CYLocalize("HALFINSTALLED_PACKAGE_EX")];
7188 [sheet popupAlertAnimated:YES];
7189 } else if (!Ignored_ && [essential_ count] != 0) {
7190 int count = [essential_ count];
7192 UIActionSheet *sheet = [[[UIActionSheet alloc]
7193 initWithTitle:(count == 1 ? CYLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:CYLocalize("ESSENTIAL_UPGRADES"), count])
7194 buttons:[NSArray arrayWithObjects:
7195 CYLocalize("UPGRADE_ESSENTIAL"),
7196 CYLocalize("COMPLETE_UPGRADE"),
7197 CYLocalize("TEMPORARY_IGNORE"),
7199 defaultButtonIndex:0
7204 [sheet setBodyText:CYLocalize("ESSENTIAL_UPGRADE_EX")];
7205 [sheet popupAlertAnimated:YES];
7209 - (void) _reloadData {
7212 static bool loaded(false);
7213 UIProgressHUD *hud([self addProgressHUD]);
7214 [hud setText:(loaded ? CYLocalize("RELOADING_DATA") : CYLocalize("LOADING_DATA"))];
7217 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7220 [self removeProgressHUD:hud];
7224 [essential_ removeAllObjects];
7225 [broken_ removeAllObjects];
7227 NSArray *packages = [database_ packages];
7228 for (Package *package in packages) {
7230 [broken_ addObject:package];
7231 if ([package upgradableAndEssential:NO]) {
7232 if ([package essential])
7233 [essential_ addObject:package];
7239 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7240 [buttonbar_ setBadgeValue:badge forButton:3];
7241 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7242 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7243 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7244 [self setApplicationBadge:badge];
7246 [self setApplicationBadgeString:badge];
7248 [buttonbar_ setBadgeValue:nil forButton:3];
7249 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7250 [buttonbar_ setBadgeAnimated:NO forButton:3];
7251 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7252 [self removeApplicationBadge];
7253 else // XXX: maybe use setApplicationBadgeString also?
7254 [self setApplicationIconBadgeNumber:0];
7258 [buttonbar_ setBadgeValue:nil forButton:4];
7262 // XXX: what is this line of code for?
7263 if ([packages count] == 0);
7264 else if (Loaded_ || ManualRefresh) loaded:
7269 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7270 NSTimeInterval interval([update timeIntervalSinceNow]);
7271 if (interval <= 0 && interval > -600)
7279 - (void) _saveConfig {
7282 NSString *error(nil);
7283 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7285 NSError *error(nil);
7286 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7287 NSLog(@"failure to save metadata data: %@", error);
7290 NSLog(@"failure to serialize metadata: %@", error);
7298 - (void) updateData {
7301 /* XXX: this is just stupid */
7302 if (tag_ != 2 && sections_ != nil)
7303 [sections_ reloadData];
7304 if (tag_ != 3 && changes_ != nil)
7305 [changes_ reloadData];
7306 if (tag_ != 5 && search_ != nil)
7307 [search_ reloadData];
7317 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7318 _assert(file != NULL);
7320 NSArray *keys = [Sources_ allKeys];
7322 for (NSString *key in keys) {
7323 NSDictionary *source = [Sources_ objectForKey:key];
7325 fprintf(file, "%s %s %s\n",
7326 [[source objectForKey:@"Type"] UTF8String],
7327 [[source objectForKey:@"URI"] UTF8String],
7328 [[source objectForKey:@"Distribution"] UTF8String]
7337 detachNewThreadSelector:@selector(update_)
7340 title:CYLocalize("UPDATING_SOURCES")
7344 - (void) reloadData {
7345 @synchronized (self) {
7346 if (confirm_ == nil)
7352 pkgProblemResolver *resolver = [database_ resolver];
7354 resolver->InstallProtect();
7355 if (!resolver->Resolve(true))
7359 - (void) popUpBook:(RVBook *)book {
7360 [underlay_ popSubview:book];
7363 - (CGRect) popUpBounds {
7364 return [underlay_ bounds];
7368 [database_ prepare];
7370 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7371 [confirm_ setDelegate:self];
7373 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7374 [page setDelegate:self];
7376 [confirm_ setPage:page];
7377 [self popUpBook:confirm_];
7381 @synchronized (self) {
7386 - (void) clearPackage:(Package *)package {
7387 @synchronized (self) {
7394 - (void) installPackage:(Package *)package {
7395 @synchronized (self) {
7402 - (void) removePackage:(Package *)package {
7403 @synchronized (self) {
7410 - (void) distUpgrade {
7411 @synchronized (self) {
7412 [database_ upgrade];
7418 [self slideUp:[[[UIActionSheet alloc]
7420 buttons:[NSArray arrayWithObjects:CYLocalize("CONTINUE_QUEUING"), CYLocalize("CANCEL_CLEAR"), nil]
7421 defaultButtonIndex:1
7428 @synchronized (self) {
7431 if (confirm_ != nil) {
7439 [overlay_ removeFromSuperview];
7443 detachNewThreadSelector:@selector(perform)
7446 title:CYLocalize("RUNNING")
7450 - (void) bootstrap_ {
7452 [database_ upgrade];
7453 [database_ prepare];
7454 [database_ perform];
7457 /* XXX: replace and localize */
7458 - (void) bootstrap {
7460 detachNewThreadSelector:@selector(bootstrap_)
7463 title:@"Bootstrap Install"
7467 - (void) progressViewIsComplete:(ProgressView *)progress {
7468 if (confirm_ != nil) {
7469 [underlay_ addSubview:overlay_];
7470 [confirm_ popFromSuperviewAnimated:NO];
7476 - (void) setPage:(RVPage *)page {
7477 [page resetViewAnimated:NO];
7478 [page setDelegate:self];
7479 [book_ setPage:page];
7482 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7483 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7484 [browser loadURL:url];
7488 - (void) _setHomePage {
7489 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7492 - (SectionsView *) sectionsView {
7493 if (sections_ == nil)
7494 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7498 - (void) buttonBarItemTapped:(id)sender {
7499 unsigned tag = [sender tag];
7501 [book_ resetViewAnimated:YES];
7503 } else if (tag_ == 2 && tag != 2)
7504 [[self sectionsView] resetView];
7507 case 1: [self _setHomePage]; break;
7509 case 2: [self setPage:[self sectionsView]]; break;
7510 case 3: [self setPage:changes_]; break;
7511 case 4: [self setPage:manage_]; break;
7512 case 5: [self setPage:search_]; break;
7514 default: _assert(false);
7520 - (void) applicationWillSuspend {
7522 [super applicationWillSuspend];
7525 - (void) askForSettings {
7526 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
7528 UIActionSheet *role = [[[UIActionSheet alloc]
7529 initWithTitle:CYLocalize("WHO_ARE_YOU")
7530 buttons:[NSArray arrayWithObjects:
7531 [NSString stringWithFormat:parenthetical, CYLocalize("USER"), CYLocalize("USER_EX")],
7532 [NSString stringWithFormat:parenthetical, CYLocalize("HACKER"), CYLocalize("HACKER_EX")],
7533 [NSString stringWithFormat:parenthetical, CYLocalize("DEVELOPER"), CYLocalize("DEVELOPER_EX")],
7535 defaultButtonIndex:-1
7540 [role setBodyText:CYLocalize("ROLE_EX")];
7541 [role popupAlertAnimated:YES];
7544 - (void) setPackageView:(PackageView *)view {
7545 if (package_ == nil)
7546 package_ = [view retain];
7549 - (PackageView *) packageView {
7552 if (package_ == nil)
7553 view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7556 view = [package_ autorelease];
7565 [self setStatusBarShowsProgress:NO];
7566 [self removeProgressHUD:hud_];
7571 pid_t pid = ExecFork();
7573 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7574 perror("launchctl stop");
7581 [self askForSettings];
7586 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7588 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7589 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7590 0, 0, screenrect.size.width, screenrect.size.height - 48
7591 ) database:database_];
7593 [book_ setDelegate:self];
7595 [overlay_ addSubview:book_];
7597 NSArray *buttonitems = [NSArray arrayWithObjects:
7598 [NSDictionary dictionaryWithObjectsAndKeys:
7599 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7600 @"home-up.png", kUIButtonBarButtonInfo,
7601 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7602 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7603 self, kUIButtonBarButtonTarget,
7604 @"Cydia", kUIButtonBarButtonTitle,
7605 @"0", kUIButtonBarButtonType,
7608 [NSDictionary dictionaryWithObjectsAndKeys:
7609 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7610 @"install-up.png", kUIButtonBarButtonInfo,
7611 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7612 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7613 self, kUIButtonBarButtonTarget,
7614 CYLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7615 @"0", kUIButtonBarButtonType,
7618 [NSDictionary dictionaryWithObjectsAndKeys:
7619 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7620 @"changes-up.png", kUIButtonBarButtonInfo,
7621 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7622 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7623 self, kUIButtonBarButtonTarget,
7624 CYLocalize("CHANGES"), kUIButtonBarButtonTitle,
7625 @"0", kUIButtonBarButtonType,
7628 [NSDictionary dictionaryWithObjectsAndKeys:
7629 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7630 @"manage-up.png", kUIButtonBarButtonInfo,
7631 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7632 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7633 self, kUIButtonBarButtonTarget,
7634 CYLocalize("MANAGE"), kUIButtonBarButtonTitle,
7635 @"0", kUIButtonBarButtonType,
7638 [NSDictionary dictionaryWithObjectsAndKeys:
7639 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7640 @"search-up.png", kUIButtonBarButtonInfo,
7641 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7642 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7643 self, kUIButtonBarButtonTarget,
7644 CYLocalize("SEARCH"), kUIButtonBarButtonTitle,
7645 @"0", kUIButtonBarButtonType,
7649 buttonbar_ = [[UIToolbar alloc]
7651 withFrame:CGRectMake(
7652 0, screenrect.size.height - ButtonBarHeight_,
7653 screenrect.size.width, ButtonBarHeight_
7655 withItemList:buttonitems
7658 [buttonbar_ setDelegate:self];
7659 [buttonbar_ setBarStyle:1];
7660 [buttonbar_ setButtonBarTrackingMode:2];
7662 int buttons[5] = {1, 2, 3, 4, 5};
7663 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7664 [buttonbar_ showButtonGroup:0 withDuration:0];
7666 for (int i = 0; i != 5; ++i)
7667 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7668 i * 64 + 2, 1, 60, ButtonBarHeight_
7671 [buttonbar_ showSelectionForButton:1];
7672 [overlay_ addSubview:buttonbar_];
7674 [UIKeyboard initImplementationNow];
7675 CGSize keysize = [UIKeyboard defaultSize];
7676 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7677 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7678 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
7679 [overlay_ addSubview:keyboard_];
7682 [underlay_ addSubview:overlay_];
7686 [self sectionsView];
7687 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7688 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7690 manage_ = (ManageView *) [[self
7691 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7692 withClass:[ManageView class]
7695 [self setPackageView:[self packageView]];
7702 [self _setHomePage];
7705 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7706 NSString *context([sheet context]);
7708 if ([context isEqualToString:@"missing"])
7710 else if ([context isEqualToString:@"cancel"]) {
7728 @synchronized (self) {
7733 [buttonbar_ setBadgeValue:CYLocalize("Q_D") forButton:4];
7737 if (confirm_ != nil) {
7742 } else if ([context isEqualToString:@"fixhalf"]) {
7745 @synchronized (self) {
7746 for (Package *broken in broken_) {
7749 NSString *id = [broken id];
7750 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7751 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7752 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7753 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7762 [broken_ removeAllObjects];
7771 } else if ([context isEqualToString:@"role"]) {
7773 case 1: Role_ = @"User"; break;
7774 case 2: Role_ = @"Hacker"; break;
7775 case 3: Role_ = @"Developer"; break;
7782 bool reset = Settings_ != nil;
7784 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7788 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7798 } else if ([context isEqualToString:@"upgrade"]) {
7801 @synchronized (self) {
7802 for (Package *essential in essential_)
7803 [essential install];
7826 - (void) reorganize { _pooled
7827 system("/usr/libexec/cydia/free.sh");
7828 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
7831 - (void) applicationSuspend:(__GSEvent *)event {
7832 if (hud_ == nil && ![progress_ isRunning])
7833 [super applicationSuspend:event];
7836 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7838 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7841 - (void) _setSuspended:(BOOL)value {
7843 [super _setSuspended:value];
7846 - (UIProgressHUD *) addProgressHUD {
7847 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
7848 [window_ setUserInteractionEnabled:NO];
7850 [progress_ addSubview:hud];
7854 - (void) removeProgressHUD:(UIProgressHUD *)hud {
7856 [hud removeFromSuperview];
7857 [window_ setUserInteractionEnabled:YES];
7860 - (void) openMailToURL:(NSURL *)url {
7861 // XXX: this makes me sad
7863 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
7865 [UIApp openURL:url];// asPanel:YES];
7869 - (void) clearFirstResponder {
7870 if (id responder = [window_ firstResponder])
7871 [responder resignFirstResponder];
7874 - (RVPage *) pageForPackage:(NSString *)name {
7875 if (Package *package = [database_ packageWithName:name]) {
7876 PackageView *view([self packageView]);
7877 [view setPackage:package];
7880 UIActionSheet *sheet = [[[UIActionSheet alloc]
7881 initWithTitle:CYLocalize("CANNOT_LOCATE_PACKAGE")
7882 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
7883 defaultButtonIndex:0
7888 [sheet setBodyText:[NSString stringWithFormat:CYLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
7890 [sheet popupAlertAnimated:YES];
7895 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
7899 NSString *scheme([[url scheme] lowercaseString]);
7900 if (![scheme isEqualToString:@"cydia"])
7902 NSString *path([url absoluteString]);
7903 if ([path length] < 8)
7905 path = [path substringFromIndex:8];
7906 if (![path hasPrefix:@"/"])
7907 path = [@"/" stringByAppendingString:path];
7909 if ([path isEqualToString:@"/add-source"])
7910 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
7911 else if ([path isEqualToString:@"/storage"])
7912 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[BrowserView class]];
7913 else if ([path isEqualToString:@"/sources"])
7914 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
7915 else if ([path isEqualToString:@"/packages"])
7916 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
7917 else if ([path hasPrefix:@"/url/"])
7918 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[BrowserView class]];
7919 else if ([path hasPrefix:@"/launch/"])
7920 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
7921 else if ([path hasPrefix:@"/package-settings/"])
7922 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
7923 else if ([path hasPrefix:@"/package-signature/"])
7924 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
7925 else if ([path hasPrefix:@"/package/"])
7926 return [self pageForPackage:[path substringFromIndex:9]];
7927 else if ([path hasPrefix:@"/files/"]) {
7928 NSString *name = [path substringFromIndex:7];
7930 if (Package *package = [database_ packageWithName:name]) {
7931 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
7932 [files setPackage:package];
7940 - (void) applicationOpenURL:(NSURL *)url {
7941 [super applicationOpenURL:url];
7943 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
7944 [self setPage:page];
7945 [buttonbar_ showSelectionForButton:tag];
7950 - (void) applicationDidFinishLaunching:(id)unused {
7952 Font12_ = [[UIFont systemFontOfSize:12] retain];
7953 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
7954 Font14_ = [[UIFont systemFontOfSize:14] retain];
7955 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
7956 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
7960 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
7961 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
7963 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
7965 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7966 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
7968 [window_ orderFront:self];
7969 [window_ makeKey:self];
7970 [window_ setHidden:NO];
7972 database_ = [Database sharedInstance];
7973 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
7974 [database_ setDelegate:progress_];
7975 [window_ setContentView:progress_];
7977 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
7978 [progress_ setContentView:underlay_];
7980 [progress_ resetView];
7983 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
7984 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
7985 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
7986 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
7987 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
7988 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
7989 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
7991 [self setIdleTimerDisabled:YES];
7993 hud_ = [[self addProgressHUD] retain];
7994 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
7996 [self setStatusBarShowsProgress:YES];
7999 detachNewThreadSelector:@selector(reorganize)
8007 - (void) showKeyboard:(BOOL)show {
8008 CGSize keysize = [UIKeyboard defaultSize];
8009 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8010 CGRect keyup = keydown;
8011 keyup.origin.y -= keysize.height;
8013 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
8014 [animation setSignificantRectFields:2];
8017 [animation setStartFrame:keydown];
8018 [animation setEndFrame:keyup];
8019 [keyboard_ activate];
8021 [animation setStartFrame:keyup];
8022 [animation setEndFrame:keydown];
8023 [keyboard_ deactivate];
8026 [[UIAnimator sharedAnimator]
8027 addAnimations:[NSArray arrayWithObjects:animation, nil]
8028 withDuration:KeyboardTime_
8033 - (void) slideUp:(UIActionSheet *)alert {
8035 [alert presentSheetFromButtonBar:buttonbar_];
8037 [alert presentSheetInView:overlay_];
8042 void AddPreferences(NSString *plist) { _pooled
8043 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
8044 _assert(settings != NULL);
8045 NSMutableArray *items = [settings objectForKey:@"items"];
8049 for (NSMutableDictionary *item in items) {
8050 NSString *label = [item objectForKey:@"label"];
8051 if (label != nil && [label isEqualToString:@"Cydia"]) {
8058 for (size_t i(0); i != [items count]; ++i) {
8059 NSDictionary *item([items objectAtIndex:i]);
8060 NSString *label = [item objectForKey:@"label"];
8061 if (label != nil && [label isEqualToString:@"General"]) {
8062 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
8063 @"CydiaSettings", @"bundle",
8064 @"PSLinkCell", @"cell",
8065 [NSNumber numberWithBool:YES], @"hasIcon",
8066 [NSNumber numberWithBool:YES], @"isController",
8068 nil] atIndex:(i + 1)];
8074 _assert([settings writeToFile:plist atomically:YES] == YES);
8079 id Alloc_(id self, SEL selector) {
8080 id object = alloc_(self, selector);
8081 lprintf("[%s]A-%p\n", self->isa->name, object);
8086 id Dealloc_(id self, SEL selector) {
8087 id object = dealloc_(self, selector);
8088 lprintf("[%s]D-%p\n", self->isa->name, object);
8092 Class $WebDefaultUIKitDelegate;
8094 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
8096 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
8097 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8098 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8099 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
8102 int main(int argc, char *argv[]) { _pooled
8105 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8107 /* Library Hacks {{{ */
8108 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8110 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8111 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8112 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8113 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8114 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8117 /* Set Locale {{{ */
8118 Locale_ = CFLocaleCopyCurrent();
8119 Languages_ = [NSLocale preferredLanguages];
8120 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8121 //NSLog(@"%@", [Languages_ description]);
8123 if (Languages_ == nil || [Languages_ count] == 0)
8126 lang = [[Languages_ objectAtIndex:0] UTF8String];
8127 setenv("LANG", lang, true);
8128 //std::setlocale(LC_ALL, lang);
8129 NSLog(@"Setting Language: %s", lang);
8132 // XXX: apr_app_initialize?
8135 /* Parse Arguments {{{ */
8136 bool substrate(false);
8142 for (int argi(1); argi != argc; ++argi)
8143 if (strcmp(argv[argi], "--") == 0) {
8145 argv[argi] = argv[0];
8151 for (int argi(1); argi != arge; ++argi)
8152 if (strcmp(args[argi], "--bootstrap") == 0)
8154 else if (strcmp(args[argi], "--substrate") == 0)
8157 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8162 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
8163 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
8164 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
8165 Sounds_Keyboard_ = [keyboard boolValue];
8168 App_ = [[NSBundle mainBundle] bundlePath];
8169 Home_ = NSHomeDirectory();
8174 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8175 alloc_ = alloc->method_imp;
8176 alloc->method_imp = (IMP) &Alloc_;*/
8178 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8179 dealloc_ = dealloc->method_imp;
8180 dealloc->method_imp = (IMP) &Dealloc_;*/
8185 size = sizeof(maxproc);
8186 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8187 perror("sysctlbyname(\"kern.maxproc\", ?)");
8188 else if (maxproc < 64) {
8190 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8191 perror("sysctlbyname(\"kern.maxproc\", #)");
8194 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8195 char *machine = new char[size];
8196 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8197 perror("sysctlbyname(\"hw.machine\", ?)");
8201 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8203 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8204 Build_ = [system objectForKey:@"ProductBuildVersion"];
8205 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8206 Product_ = [info objectForKey:@"SafariProductVersion"];
8207 Safari_ = [info objectForKey:@"CFBundleVersion"];
8210 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8211 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
8213 /* Load Database {{{ */
8215 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8217 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8220 if (Metadata_ == NULL)
8221 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8223 Settings_ = [Metadata_ objectForKey:@"Settings"];
8225 Packages_ = [Metadata_ objectForKey:@"Packages"];
8226 Sections_ = [Metadata_ objectForKey:@"Sections"];
8227 Sources_ = [Metadata_ objectForKey:@"Sources"];
8230 if (Settings_ != nil)
8231 Role_ = [Settings_ objectForKey:@"Role"];
8233 if (Packages_ == nil) {
8234 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8235 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8238 if (Sections_ == nil) {
8239 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8240 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8243 if (Sources_ == nil) {
8244 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8245 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8250 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8253 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8254 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8255 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8256 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8258 if (access("/User", F_OK) != 0) {
8260 system("/usr/libexec/cydia/firmware.sh");
8264 _assert([[NSFileManager defaultManager]
8265 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8266 withIntermediateDirectories:YES
8271 if (access("/tmp/cydia.chk", F_OK) == 0) {
8272 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8273 _assert(errno == ENOENT);
8274 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8275 _assert(errno == ENOENT);
8278 _assert(pkgInitConfig(*_config));
8279 _assert(pkgInitSystem(*_config, _system));
8282 _config->Set("APT::Acquire::Translation", lang);
8283 _config->Set("Acquire::http::Timeout", 15);
8284 _config->Set("Acquire::http::MaxParallel", 4);
8286 /* Color Choices {{{ */
8287 space_ = CGColorSpaceCreateDeviceRGB();
8289 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8290 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8291 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8292 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8293 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8294 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8295 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8296 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8297 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8298 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8299 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8300 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8301 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8302 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8303 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8306 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8307 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8310 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8312 /* UIKit Configuration {{{ */
8313 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8314 if ($GSFontSetUseLegacyFontMetrics != NULL)
8315 $GSFontSetUseLegacyFontMetrics(YES);
8317 UIKeyboardDisableAutomaticAppearance();
8321 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8323 CGColorSpaceRelease(space_);