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 TraceLogging (1 && !ForRelease)
401 #define ProfileTimes (0 && !ForRelease)
402 #define ForSaurik (0 && !ForRelease)
403 #define LogBrowser (0 && !ForRelease)
404 #define TrackResize (0 && !ForRelease)
405 #define ManualRefresh (1 && !ForRelease)
406 #define ShowInternals (0 && !ForRelease)
407 #define IgnoreInstall (0 && !ForRelease)
408 #define RecycleWebViews 0
409 #define AlwaysReload (1 && !ForRelease)
413 #define _trace(args...)
418 #define _profile(name) {
421 #define PrintTimes() do {} while (false)
425 typedef uint32_t (*SKRadixFunction)(id, void *);
427 @interface NSMutableArray (Radix)
428 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
429 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
437 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
438 struct RadixItem_ *lhs(swap), *rhs(swap + count);
440 static const size_t width = 32;
441 static const size_t bits = 11;
442 static const size_t slots = 1 << bits;
443 static const size_t passes = (width + (bits - 1)) / bits;
445 size_t *hist(new size_t[slots]);
447 for (size_t pass(0); pass != passes; ++pass) {
448 memset(hist, 0, sizeof(size_t) * slots);
450 for (size_t i(0); i != count; ++i) {
451 uint32_t key(lhs[i].key);
453 key &= _not(uint32_t) >> width - bits;
458 for (size_t i(0); i != slots; ++i) {
459 size_t local(offset);
464 for (size_t i(0); i != count; ++i) {
465 uint32_t key(lhs[i].key);
467 key &= _not(uint32_t) >> width - bits;
468 rhs[hist[key]++] = lhs[i];
471 RadixItem_ *tmp(lhs);
478 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
479 for (size_t i(0); i != count; ++i)
480 [values addObject:[self objectAtIndex:lhs[i].index]];
481 [self setArray:values];
486 @implementation NSMutableArray (Radix)
488 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
489 size_t count([self count]);
494 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
495 [invocation setSelector:selector];
496 [invocation setArgument:&object atIndex:2];
498 /* XXX: this is an unsafe optimization of doomy hell */
499 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
500 _assert(method != NULL);
501 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
502 _assert(imp != NULL);
505 struct RadixItem_ *swap(new RadixItem_[count * 2]);
507 for (size_t i(0); i != count; ++i) {
508 RadixItem_ &item(swap[i]);
511 id object([self objectAtIndex:i]);
514 [invocation setTarget:object];
516 [invocation getReturnValue:&item.key];
518 item.key = imp(object, selector, object);
522 RadixSort_(self, count, swap);
525 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
526 size_t count([self count]);
527 struct RadixItem_ *swap(new RadixItem_[count * 2]);
529 for (size_t i(0); i != count; ++i) {
530 RadixItem_ &item(swap[i]);
533 id object([self objectAtIndex:i]);
534 item.key = function(object, argument);
537 RadixSort_(self, count, swap);
542 /* Insertion Sort {{{ */
544 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
545 const char *ptr = (const char *)list;
547 CFIndex half = count / 2;
548 const char *probe = ptr + elementSize * half;
549 CFComparisonResult cr = comparator(element, probe, context);
550 if (0 == cr) return (probe - (const char *)list) / elementSize;
551 ptr = (cr < 0) ? ptr : probe + elementSize;
552 count = (cr < 0) ? half : (half + (count & 1) - 1);
554 return (ptr - (const char *)list) / elementSize;
557 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
558 const char *ptr = (const char *)list;
560 CFIndex half = count / 2;
561 const char *probe = ptr + elementSize * half;
562 CFComparisonResult cr = comparator(element, probe, context);
563 if (0 == cr) return (probe - (const char *)list) / elementSize;
564 ptr = (cr < 0) ? ptr : probe + elementSize;
565 count = (cr < 0) ? half : (half + (count & 1) - 1);
567 return (ptr - (const char *)list) / elementSize;
570 #define HistogramInsertionSort 0
572 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
573 if (range.length == 0)
575 const void **values(new const void *[range.length]);
576 CFArrayGetValues(array, range, values);
578 #if HistogramInsertionSort
579 uint32_t total(0), *offsets(new uint32_t[range.length]);
582 for (CFIndex index(1); index != range.length; ++index) {
583 const void *value(values[index]);
584 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
585 CFIndex correct(index);
586 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
589 if (correct != index) {
590 size_t offset(index - correct);
591 #if HistogramInsertionSort
595 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
597 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
598 values[correct] = value;
602 CFArrayReplaceValues(array, range, values, range.length);
605 #if HistogramInsertionSort
606 for (CFIndex index(0); index != range.length; ++index)
607 if (offsets[index] != 0)
608 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
609 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
616 /* Apple Bug Fixes {{{ */
617 @implementation UIWebDocumentView (Cydia)
619 - (void) _setScrollerOffset:(CGPoint)offset {
620 UIScroller *scroller([self _scroller]);
622 CGSize size([scroller contentSize]);
623 CGSize bounds([scroller bounds].size);
626 max.x = size.width - bounds.width;
627 max.y = size.height - bounds.height;
635 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
636 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
638 [scroller setOffset:offset];
645 kUIControlEventMouseDown = 1 << 0,
646 kUIControlEventMouseMovedInside = 1 << 2, // mouse moved inside control target
647 kUIControlEventMouseMovedOutside = 1 << 3, // mouse moved outside control target
648 kUIControlEventMouseUpInside = 1 << 6, // mouse up inside control target
649 kUIControlEventMouseUpOutside = 1 << 7, // mouse up outside control target
650 kUIControlAllEvents = (kUIControlEventMouseDown | kUIControlEventMouseMovedInside | kUIControlEventMouseMovedOutside | kUIControlEventMouseUpInside | kUIControlEventMouseUpOutside)
651 } UIControlEventMasks;
653 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
654 size_t length([self length] - state->state);
657 else if (length > count)
659 for (size_t i(0); i != length; ++i)
660 objects[i] = [self item:state->state++];
661 state->itemsPtr = objects;
662 state->mutationsPtr = (unsigned long *) self;
666 @interface NSString (UIKit)
667 - (NSString *) stringByAddingPercentEscapes;
668 - (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
671 @interface NSString (Cydia)
672 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
673 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
674 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
675 - (NSComparisonResult) compareByPath:(NSString *)other;
676 - (NSString *) stringByCachingURLWithCurrentCDN;
677 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
680 @implementation NSString (Cydia)
682 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
683 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
686 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
687 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
688 memcpy(data, bytes, length);
689 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
692 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
693 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
696 - (NSComparisonResult) compareByPath:(NSString *)other {
697 NSString *prefix = [self commonPrefixWithString:other options:0];
698 size_t length = [prefix length];
700 NSRange lrange = NSMakeRange(length, [self length] - length);
701 NSRange rrange = NSMakeRange(length, [other length] - length);
703 lrange = [self rangeOfString:@"/" options:0 range:lrange];
704 rrange = [other rangeOfString:@"/" options:0 range:rrange];
706 NSComparisonResult value;
708 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
709 value = NSOrderedSame;
710 else if (lrange.location == NSNotFound)
711 value = NSOrderedAscending;
712 else if (rrange.location == NSNotFound)
713 value = NSOrderedDescending;
715 value = NSOrderedSame;
717 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
718 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
719 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
720 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
722 NSComparisonResult result = [lpath compare:rpath];
723 return result == NSOrderedSame ? value : result;
726 - (NSString *) stringByCachingURLWithCurrentCDN {
728 stringByReplacingOccurrencesOfString:@"://"
729 withString:@"://ne.edgecastcdn.net/8003A4/"
731 /* XXX: this is somewhat inaccurate */
732 range:NSMakeRange(0, 10)
736 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
737 return [(id)CFURLCreateStringByAddingPercentEscapes(
742 kCFStringEncodingUTF8
748 static inline NSString *CYLocalizeEx(NSString *key, NSString *value = nil) {
749 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:nil];
752 #define CYLocalize(key) CYLocalizeEx(@ key)
760 _finline void clear_() {
766 _finline bool empty() const {
770 _finline size_t size() const {
774 _finline char *data() const {
778 _finline void clear() {
783 _finline CYString() :
790 _finline ~CYString() {
794 void operator =(const CYString &rhs) {
798 if (rhs.cache_ == nil)
801 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
804 void set(apr_pool_t *pool, const char *data, size_t size) {
810 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
811 memcpy(temp, data, size);
818 _finline void set(apr_pool_t *pool, const char *data) {
819 set(pool, data, data == NULL ? 0 : strlen(data));
822 _finline void set(apr_pool_t *pool, const std::string &rhs) {
823 set(pool, rhs.data(), rhs.size());
826 bool operator ==(const CYString &rhs) const {
827 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
830 operator CFStringRef() {
831 if (cache_ == NULL) {
834 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
838 _finline operator id() {
839 return (NSString *) static_cast<CFStringRef>(*this);
844 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
847 struct NSStringMapHash :
848 std::unary_function<NSString *, size_t>
850 _finline size_t operator ()(NSString *value) const {
851 return CFStringHashNSString((CFStringRef) value);
855 struct NSStringMapLess :
856 std::binary_function<NSString *, NSString *, bool>
858 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
859 return [lhs compare:rhs] == NSOrderedAscending;
863 struct NSStringMapEqual :
864 std::binary_function<NSString *, NSString *, bool>
866 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
867 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
868 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
869 //[lhs isEqualToString:rhs];
873 /* Perl-Compatible RegEx {{{ */
883 Pcre(const char *regex) :
888 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
891 lprintf("%d:%s\n", offset, error);
895 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
896 matches_ = new int[(capture_ + 1) * 3];
904 NSString *operator [](size_t match) {
905 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
908 bool operator ()(NSString *data) {
909 // XXX: length is for characters, not for bytes
910 return operator ()([data UTF8String], [data length]);
913 bool operator ()(const char *data, size_t size) {
915 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
919 /* Mime Addresses {{{ */
920 @interface Address : NSObject {
926 - (NSString *) address;
928 - (void) setAddress:(NSString *)address;
930 + (Address *) addressWithString:(NSString *)string;
931 - (Address *) initWithString:(NSString *)string;
934 @implementation Address
943 - (NSString *) name {
947 - (NSString *) address {
951 - (void) setAddress:(NSString *)address {
953 [address_ autorelease];
957 address_ = [address retain];
960 + (Address *) addressWithString:(NSString *)string {
961 return [[[Address alloc] initWithString:string] autorelease];
964 + (NSArray *) _attributeKeys {
965 return [NSArray arrayWithObjects:@"address", @"name", nil];
968 - (NSArray *) attributeKeys {
969 return [[self class] _attributeKeys];
972 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
973 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
976 - (Address *) initWithString:(NSString *)string {
977 if ((self = [super init]) != nil) {
978 const char *data = [string UTF8String];
979 size_t size = [string length];
981 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
983 if (address_r(data, size)) {
984 name_ = [address_r[1] retain];
985 address_ = [address_r[2] retain];
987 name_ = [string retain];
995 /* CoreGraphics Primitives {{{ */
1006 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
1009 Set(space, red, green, blue, alpha);
1014 CGColorRelease(color_);
1021 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1023 float color[] = {red, green, blue, alpha};
1024 color_ = CGColorCreate(space, color);
1027 operator CGColorRef() {
1033 extern "C" void UISetColor(CGColorRef color);
1035 /* Random Global Variables {{{ */
1036 static const int PulseInterval_ = 50000;
1037 static const int ButtonBarHeight_ = 48;
1038 static const float KeyboardTime_ = 0.3f;
1040 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1041 #define SandboxTemplate_ "/usr/share/sandbox/SandboxTemplate.sb"
1042 #define NotifyConfig_ "/etc/notify.conf"
1044 static bool Queuing_;
1046 static CGColor Blue_;
1047 static CGColor Blueish_;
1048 static CGColor Black_;
1049 static CGColor Off_;
1050 static CGColor White_;
1051 static CGColor Gray_;
1052 static CGColor Green_;
1053 static CGColor Purple_;
1054 static CGColor Purplish_;
1056 static UIColor *InstallingColor_;
1057 static UIColor *RemovingColor_;
1059 static NSString *App_;
1060 static NSString *Home_;
1061 static BOOL Sounds_Keyboard_;
1063 static BOOL Advanced_;
1064 static BOOL Loaded_;
1065 static BOOL Ignored_;
1067 static UIFont *Font12_;
1068 static UIFont *Font12Bold_;
1069 static UIFont *Font14_;
1070 static UIFont *Font18Bold_;
1071 static UIFont *Font22Bold_;
1073 static const char *Machine_ = NULL;
1074 static const NSString *UniqueID_ = nil;
1075 static const NSString *Build_ = nil;
1076 static const NSString *Product_ = nil;
1077 static const NSString *Safari_ = nil;
1079 CFLocaleRef Locale_;
1080 NSArray *Languages_;
1081 CGColorSpaceRef space_;
1086 static NSDictionary *SectionMap_;
1087 static NSMutableDictionary *Metadata_;
1088 static _transient NSMutableDictionary *Settings_;
1089 static _transient NSString *Role_;
1090 static _transient NSMutableDictionary *Packages_;
1091 static _transient NSMutableDictionary *Sections_;
1092 static _transient NSMutableDictionary *Sources_;
1093 static bool Changed_;
1094 static NSDate *now_;
1097 static NSMutableArray *Documents_;
1100 NSString *GetLastUpdate() {
1101 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1104 return CYLocalize("NEVER_OR_UNKNOWN");
1106 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1107 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1109 CFRelease(formatter);
1111 return [(NSString *) formatted autorelease];
1114 /* Display Helpers {{{ */
1115 inline float Interpolate(float begin, float end, float fraction) {
1116 return (end - begin) * fraction + begin;
1119 /* XXX: localize this! */
1120 NSString *SizeString(double size) {
1121 bool negative = size < 0;
1126 while (size > 1024) {
1131 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1133 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1136 NSString *StripVersion(const char *version) {
1137 const char *colon(strchr(version, ':'));
1139 version = colon + 1;
1140 return [NSString stringWithUTF8String:version];
1143 NSString *StripVersion(NSString *version) {
1144 NSRange colon = [version rangeOfString:@":"];
1145 if (colon.location != NSNotFound)
1146 version = [version substringFromIndex:(colon.location + 1)];
1150 NSString *LocalizeSection(NSString *section) {
1151 static Pcre title_r("^(.*?) \\((.*)\\)$");
1152 if (title_r(section)) {
1153 NSString *parent(title_r[1]);
1154 NSString *child(title_r[2]);
1156 return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"),
1157 LocalizeSection(parent),
1158 LocalizeSection(child)
1162 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1165 NSString *Simplify(NSString *title) {
1166 const char *data = [title UTF8String];
1167 size_t size = [title length];
1169 static Pcre square_r("^\\[(.*)\\]$");
1170 if (square_r(data, size))
1171 return Simplify(square_r[1]);
1173 static Pcre paren_r("^\\((.*)\\)$");
1174 if (paren_r(data, size))
1175 return Simplify(paren_r[1]);
1177 static Pcre title_r("^(.*?) \\((.*)\\)$");
1178 if (title_r(data, size))
1179 return Simplify(title_r[1]);
1185 bool isSectionVisible(NSString *section) {
1186 NSDictionary *metadata([Sections_ objectForKey:section]);
1187 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1188 return hidden == nil || ![hidden boolValue];
1191 /* Delegate Prototypes {{{ */
1195 @interface NSObject (ProgressDelegate)
1198 @implementation NSObject(ProgressDelegate)
1200 - (void) _setProgressError:(NSArray *)args {
1201 [self performSelector:@selector(setProgressError:forPackage:)
1202 withObject:[args objectAtIndex:0]
1203 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1209 @protocol ProgressDelegate
1210 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1211 - (void) setProgressTitle:(NSString *)title;
1212 - (void) setProgressPercent:(float)percent;
1213 - (void) startProgress;
1214 - (void) addProgressOutput:(NSString *)output;
1215 - (bool) isCancelling:(size_t)received;
1218 @protocol ConfigurationDelegate
1219 - (void) repairWithSelector:(SEL)selector;
1220 - (void) setConfigurationData:(NSString *)data;
1225 @protocol CydiaDelegate
1226 - (void) setPackageView:(PackageView *)view;
1227 - (void) clearPackage:(Package *)package;
1228 - (void) installPackage:(Package *)package;
1229 - (void) removePackage:(Package *)package;
1230 - (void) slideUp:(UIActionSheet *)alert;
1231 - (void) distUpgrade;
1232 - (void) updateData;
1234 - (void) askForSettings;
1235 - (UIProgressHUD *) addProgressHUD;
1236 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1237 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag;
1238 - (RVPage *) pageForPackage:(NSString *)name;
1239 - (void) openMailToURL:(NSURL *)url;
1240 - (void) clearFirstResponder;
1241 - (PackageView *) packageView;
1245 /* Status Delegation {{{ */
1247 public pkgAcquireStatus
1250 _transient NSObject<ProgressDelegate> *delegate_;
1258 void setDelegate(id delegate) {
1259 delegate_ = delegate;
1262 virtual bool MediaChange(std::string media, std::string drive) {
1266 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1269 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1270 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1271 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
1274 virtual void Done(pkgAcquire::ItemDesc &item) {
1277 virtual void Fail(pkgAcquire::ItemDesc &item) {
1279 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1280 item.Owner->Status == pkgAcquire::Item::StatDone
1284 std::string &error(item.Owner->ErrorText);
1288 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1289 NSArray *fields([description componentsSeparatedByString:@" "]);
1290 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1292 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1293 withObject:[NSArray arrayWithObjects:
1294 [NSString stringWithUTF8String:error.c_str()],
1301 virtual bool Pulse(pkgAcquire *Owner) {
1302 bool value = pkgAcquireStatus::Pulse(Owner);
1305 double(CurrentBytes + CurrentItems) /
1306 double(TotalBytes + TotalItems)
1309 [delegate_ setProgressPercent:percent];
1310 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1313 virtual void Start() {
1314 [delegate_ startProgress];
1317 virtual void Stop() {
1321 /* Progress Delegation {{{ */
1326 _transient id<ProgressDelegate> delegate_;
1329 virtual void Update() {
1330 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1331 [delegate_ setProgressPercent:(Percent / 100)];*/
1340 void setDelegate(id delegate) {
1341 delegate_ = delegate;
1344 virtual void Done() {
1345 //[delegate_ setProgressPercent:1];
1350 /* Database Interface {{{ */
1351 @interface Database : NSObject {
1357 pkgCacheFile cache_;
1358 pkgDepCache::Policy *policy_;
1359 pkgRecords *records_;
1360 pkgProblemResolver *resolver_;
1361 pkgAcquire *fetcher_;
1363 SPtr<pkgPackageManager> manager_;
1364 pkgSourceList *list_;
1366 NSMutableDictionary *sources_;
1367 NSMutableArray *packages_;
1369 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1378 + (Database *) sharedInstance;
1381 - (void) _readCydia:(NSNumber *)fd;
1382 - (void) _readStatus:(NSNumber *)fd;
1383 - (void) _readOutput:(NSNumber *)fd;
1387 - (Package *) packageWithName:(NSString *)name;
1389 - (pkgCacheFile &) cache;
1390 - (pkgDepCache::Policy *) policy;
1391 - (pkgRecords *) records;
1392 - (pkgProblemResolver *) resolver;
1393 - (pkgAcquire &) fetcher;
1394 - (pkgSourceList &) list;
1395 - (NSArray *) packages;
1396 - (NSArray *) sources;
1397 - (void) reloadData;
1405 - (void) updateWithStatus:(Status &)status;
1407 - (void) setDelegate:(id)delegate;
1408 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1412 /* Source Class {{{ */
1413 @interface Source : NSObject {
1414 NSString *description_;
1420 NSString *distribution_;
1424 NSString *defaultIcon_;
1426 NSDictionary *record_;
1430 - (Source *) initWithMetaIndex:(metaIndex *)index;
1432 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1434 - (NSString *) supportForPackage:(NSString *)package;
1436 - (NSDictionary *) record;
1440 - (NSString *) distribution;
1441 - (NSString *) type;
1443 - (NSString *) host;
1445 - (NSString *) name;
1446 - (NSString *) description;
1447 - (NSString *) label;
1448 - (NSString *) origin;
1449 - (NSString *) version;
1451 - (NSString *) defaultIcon;
1455 @implementation Source
1457 #define _clear(field) \
1464 _clear(distribution_)
1467 _clear(description_)
1472 _clear(defaultIcon_)
1481 + (NSArray *) _attributeKeys {
1482 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1485 - (NSArray *) attributeKeys {
1486 return [[self class] _attributeKeys];
1489 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1490 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1493 - (void) setMetaIndex:(metaIndex *)index {
1496 trusted_ = index->IsTrusted();
1498 uri_ = [[NSString stringWithUTF8String:index->GetURI().c_str()] retain];
1499 distribution_ = [[NSString stringWithUTF8String:index->GetDist().c_str()] retain];
1500 type_ = [[NSString stringWithUTF8String:index->GetType()] retain];
1502 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1503 if (dindex != NULL) {
1504 std::ifstream release(dindex->MetaIndexFile("Release").c_str());
1506 while (std::getline(release, line)) {
1507 std::string::size_type colon(line.find(':'));
1508 if (colon == std::string::npos)
1511 std::string name(line.substr(0, colon));
1512 std::string value(line.substr(colon + 1));
1513 while (!value.empty() && value[0] == ' ')
1514 value = value.substr(1);
1516 if (name == "Default-Icon")
1517 defaultIcon_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1518 else if (name == "Description")
1519 description_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1520 else if (name == "Label")
1521 label_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1522 else if (name == "Origin")
1523 origin_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1524 else if (name == "Support")
1525 support_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1526 else if (name == "Version")
1527 version_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1531 record_ = [Sources_ objectForKey:[self key]];
1533 record_ = [record_ retain];
1536 - (Source *) initWithMetaIndex:(metaIndex *)index {
1537 if ((self = [super init]) != nil) {
1538 [self setMetaIndex:index];
1542 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1543 NSDictionary *lhr = [self record];
1544 NSDictionary *rhr = [source record];
1547 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1549 NSString *lhs = [self name];
1550 NSString *rhs = [source name];
1552 if ([lhs length] != 0 && [rhs length] != 0) {
1553 unichar lhc = [lhs characterAtIndex:0];
1554 unichar rhc = [rhs characterAtIndex:0];
1556 if (isalpha(lhc) && !isalpha(rhc))
1557 return NSOrderedAscending;
1558 else if (!isalpha(lhc) && isalpha(rhc))
1559 return NSOrderedDescending;
1562 return [lhs compare:rhs options:LaxCompareOptions_];
1565 - (NSString *) supportForPackage:(NSString *)package {
1566 return support_ == nil ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1569 - (NSDictionary *) record {
1577 - (NSString *) uri {
1581 - (NSString *) distribution {
1582 return distribution_;
1585 - (NSString *) type {
1589 - (NSString *) key {
1590 return [NSString stringWithFormat:@"%@:%@:%@", type_, uri_, distribution_];
1593 - (NSString *) host {
1594 return [[[NSURL URLWithString:[self uri]] host] lowercaseString];
1597 - (NSString *) name {
1598 return origin_ == nil ? [self host] : origin_;
1601 - (NSString *) description {
1602 return description_;
1605 - (NSString *) label {
1606 return label_ == nil ? [self host] : label_;
1609 - (NSString *) origin {
1613 - (NSString *) version {
1617 - (NSString *) defaultIcon {
1618 return defaultIcon_;
1623 /* Relationship Class {{{ */
1624 @interface Relationship : NSObject {
1629 - (NSString *) type;
1631 - (NSString *) name;
1635 @implementation Relationship
1643 - (NSString *) type {
1651 - (NSString *) name {
1658 /* Package Class {{{ */
1659 @interface Package : NSObject {
1662 pkgCache::VerIterator version_;
1663 pkgCache::PkgIterator iterator_;
1664 _transient Database *database_;
1665 pkgCache::VerFileIterator file_;
1671 NSString *section$_;
1676 NSString *installed_;
1682 CYString depiction_;
1695 NSArray *relationships_;
1697 NSMutableDictionary *metadata_;
1698 _transient NSDate *firstSeen_;
1699 _transient NSDate *lastSeen_;
1703 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1704 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1706 - (pkgCache::PkgIterator) iterator;
1708 - (NSString *) section;
1709 - (NSString *) simpleSection;
1711 - (NSString *) longSection;
1712 - (NSString *) shortSection;
1716 - (Address *) maintainer;
1718 - (NSString *) longDescription;
1719 - (NSString *) shortDescription;
1722 - (NSMutableDictionary *) metadata;
1724 - (BOOL) subscribed;
1727 - (NSString *) latest;
1728 - (NSString *) installed;
1731 - (BOOL) upgradableAndEssential:(BOOL)essential;
1734 - (BOOL) unfiltered;
1738 - (BOOL) halfConfigured;
1739 - (BOOL) halfInstalled;
1741 - (NSString *) mode;
1744 - (NSString *) name;
1746 - (NSString *) homepage;
1747 - (NSString *) depiction;
1748 - (Address *) author;
1750 - (NSString *) support;
1752 - (NSArray *) files;
1753 - (NSArray *) relationships;
1754 - (NSArray *) warnings;
1755 - (NSArray *) applications;
1757 - (Source *) source;
1758 - (NSString *) role;
1760 - (BOOL) matches:(NSString *)text;
1762 - (bool) hasSupportingRole;
1763 - (BOOL) hasTag:(NSString *)tag;
1764 - (NSString *) primaryPurpose;
1765 - (NSArray *) purposes;
1766 - (bool) isCommercial;
1768 - (CYString &) cyname;
1770 - (uint32_t) compareBySection:(NSArray *)sections;
1772 - (uint32_t) compareForChanges;
1777 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1778 - (bool) isInstalledAndVisible:(NSNumber *)number;
1779 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1780 - (bool) isVisibleInSource:(Source *)source;
1784 uint32_t PackageChangesRadix(Package *self, void *) {
1789 uint32_t timestamp : 30;
1790 uint32_t ignored : 1;
1791 uint32_t upgradable : 1;
1795 bool upgradable([self upgradableAndEssential:YES]);
1796 value.bits.upgradable = upgradable ? 1 : 0;
1799 value.bits.timestamp = 0;
1800 value.bits.ignored = [self ignored] ? 0 : 1;
1801 value.bits.upgradable = 1;
1803 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1804 value.bits.ignored = 0;
1805 value.bits.upgradable = 0;
1808 return _not(uint32_t) - value.key;
1811 _finline static void Stifle(uint8_t &value) {
1814 uint32_t PackagePrefixRadix(Package *self, void *context) {
1815 size_t offset(reinterpret_cast<size_t>(context));
1816 CYString &name([self cyname]);
1818 size_t size(name.size());
1821 char *text(name.data());
1824 if (!isdigit(text[0]))
1828 while (size != digits && isdigit(text[digits]))
1838 if (offset == 0 && zeros != 0) {
1839 memset(data, '0', zeros);
1840 memcpy(data + zeros, text, 4 - zeros);
1842 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1843 if (size <= offset - zeros)
1846 text += offset - zeros;
1847 size -= offset - zeros;
1850 memcpy(data, text, 4);
1852 memcpy(data, text, size);
1853 memset(data + size, 0, 4 - size);
1856 for (size_t i(0); i != 4; ++i)
1857 if (isalpha(data[i]))
1862 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1864 /* XXX: ntohl may be more honest */
1865 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1868 CYString &(*PackageName)(Package *self, SEL sel);
1870 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1871 _profile(PackageNameCompare)
1872 CYString &lhi(PackageName(lhs, @selector(cyname)));
1873 CYString &rhi(PackageName(rhs, @selector(cyname)));
1874 CFStringRef lhn(lhi), rhn(rhi);
1876 _profile(PackageNameCompare$NumbersLast)
1877 if (!lhi.empty() && !rhi.empty()) {
1878 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1879 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1880 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1881 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1882 return lha ? NSOrderedAscending : NSOrderedDescending;
1886 CFIndex length = CFStringGetLength(lhn);
1888 _profile(PackageNameCompare$Compare)
1889 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1894 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1895 return PackageNameCompare(*lhs, *rhs, context);
1898 struct PackageNameOrdering :
1899 std::binary_function<Package *, Package *, bool>
1901 _finline bool operator ()(Package *lhs, Package *rhs) const {
1902 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1906 @implementation Package
1908 - (NSString *) description {
1909 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1915 if (section$_ != nil)
1916 [section$_ release];
1920 if (installed_ != nil)
1921 [installed_ release];
1923 if (sponsor$_ != nil)
1924 [sponsor$_ release];
1925 if (author$_ != nil)
1932 if (relationships_ != nil)
1933 [relationships_ release];
1934 if (metadata_ != nil)
1935 [metadata_ release];
1940 + (NSString *) webScriptNameForSelector:(SEL)selector {
1941 if (selector == @selector(hasTag:))
1947 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1948 return [self webScriptNameForSelector:selector] == nil;
1951 + (NSArray *) _attributeKeys {
1952 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];
1955 - (NSArray *) attributeKeys {
1956 return [[self class] _attributeKeys];
1959 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1960 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1963 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
1964 if ((self = [super init]) != nil) {
1965 _profile(Package$initWithVersion)
1966 @synchronized (database) {
1967 era_ = [database era];
1970 iterator_ = version.ParentPkg();
1971 database_ = database;
1973 _profile(Package$initWithVersion$Latest)
1974 latest_ = [StripVersion(version_.VerStr()) retain];
1977 pkgCache::VerIterator current(iterator_.CurrentVer());
1979 installed_ = [StripVersion(current.VerStr()) retain];
1981 if (!version_.end())
1982 file_ = version_.FileList();
1984 pkgCache &cache([database_ cache]);
1985 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
1988 _profile(Package$initWithVersion$Name)
1989 id_.set(pool, iterator_.Name());
1993 source_ = [database_ getSource:file_.File()];
1998 _profile(Package$initWithVersion$Parse)
1999 pkgRecords::Parser *parser;
2001 _profile(Package$initWithVersion$Parse$Lookup)
2002 parser = &[database_ records]->Lookup(file_);
2008 _profile(Package$initWithVersion$Parse$Find)
2015 {"depiction", &depiction_},
2016 {"homepage", &homepage_},
2017 {"website", &website},
2018 {"support", &support_},
2019 {"sponsor", &sponsor_},
2020 {"author", &author_},
2024 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2025 const char *start, *end;
2027 if (parser->Find(names[i].name_, start, end)) {
2028 CYString &value(*names[i].value_);
2029 _profile(Package$initWithVersion$Parse$Value)
2030 value.set(pool, start, end - start);
2036 _profile(Package$initWithVersion$Parse$Tagline)
2037 tagline_.set(pool, parser->ShortDesc());
2040 _profile(Package$initWithVersion$Parse$Retain)
2041 if (!homepage_.empty())
2042 homepage_ = website;
2043 if (homepage_ == depiction_)
2046 tags_ = [[tag componentsSeparatedByString:@", "] retain];
2050 _profile(Package$initWithVersion$Tags)
2052 for (NSString *tag in tags_)
2053 if ([tag hasPrefix:@"role::"]) {
2054 role_ = [[tag substringFromIndex:6] retain];
2059 bool changed(false);
2060 NSString *key([id_ lowercaseString]);
2062 _profile(Package$initWithVersion$Metadata)
2063 metadata_ = [Packages_ objectForKey:key];
2065 if (metadata_ == nil) {
2066 firstSeen_ = [now_ retain];
2068 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2069 firstSeen_, @"FirstSeen",
2070 latest_, @"LastVersion",
2075 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2076 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2078 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2079 subscribed_ = [subscribed boolValue];
2081 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2083 if (firstSeen_ == nil) {
2084 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2085 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2089 if (version == nil) {
2090 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2092 } else if (![version isEqualToString:latest_]) {
2093 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2095 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2100 metadata_ = [metadata_ retain];
2103 [Packages_ setObject:metadata_ forKey:key];
2108 _profile(Package$initWithVersion$Section)
2109 section_.set(pool, iterator_.Section());
2112 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2113 visible_ = [self hasSupportingRole] && [self unfiltered];
2114 } _end } return self;
2117 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2118 pkgCache::VerIterator version;
2120 _profile(Package$packageWithIterator$GetCandidateVer)
2121 version = [database policy]->GetCandidateVer(iterator);
2127 return [[[Package alloc]
2128 initWithVersion:version
2135 - (pkgCache::PkgIterator) iterator {
2139 - (NSString *) section {
2140 if (section$_ == nil) {
2141 if (section_.empty())
2144 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2145 NSString *name(section_);
2148 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2149 if (NSString *rename = [value objectForKey:@"Rename"]) {
2154 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2158 - (NSString *) simpleSection {
2159 if (NSString *section = [self section])
2160 return Simplify(section);
2165 - (NSString *) longSection {
2166 return LocalizeSection(section_);
2169 - (NSString *) shortSection {
2170 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2173 - (NSString *) uri {
2176 pkgIndexFile *index;
2177 pkgCache::PkgFileIterator file(file_.File());
2178 if (![database_ list].FindIndex(file, index))
2180 return [NSString stringWithUTF8String:iterator_->Path];
2181 //return [NSString stringWithUTF8String:file.Site()];
2182 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2186 - (Address *) maintainer {
2189 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2190 const std::string &maintainer(parser->Maintainer());
2191 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2195 return version_.end() ? 0 : version_->InstalledSize;
2198 - (NSString *) longDescription {
2201 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2202 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2204 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2205 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2206 if ([lines count] < 2)
2209 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2210 for (size_t i(1), e([lines count]); i != e; ++i) {
2211 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2212 [trimmed addObject:trim];
2215 return [trimmed componentsJoinedByString:@"\n"];
2218 - (NSString *) shortDescription {
2223 _profile(Package$index)
2224 CFStringRef name((CFStringRef) [self name]);
2225 if (CFStringGetLength(name) == 0)
2227 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2228 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2230 return toupper(character);
2234 - (NSMutableDictionary *) metadata {
2239 if (subscribed_ && lastSeen_ != nil)
2244 - (BOOL) subscribed {
2249 NSDictionary *metadata([self metadata]);
2250 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2251 return [ignored boolValue];
2256 - (NSString *) latest {
2260 - (NSString *) installed {
2265 return !version_.end();
2268 - (BOOL) upgradableAndEssential:(BOOL)essential {
2269 _profile(Package$upgradableAndEssential)
2270 pkgCache::VerIterator current(iterator_.CurrentVer());
2272 return essential && essential_ && visible_;
2274 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2278 - (BOOL) essential {
2283 return [database_ cache][iterator_].InstBroken();
2286 - (BOOL) unfiltered {
2287 NSString *section([self section]);
2288 return section == nil || isSectionVisible(section);
2296 unsigned char current(iterator_->CurrentState);
2297 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2300 - (BOOL) halfConfigured {
2301 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2304 - (BOOL) halfInstalled {
2305 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2309 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2310 return state.Mode != pkgDepCache::ModeKeep;
2313 - (NSString *) mode {
2314 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2316 switch (state.Mode) {
2317 case pkgDepCache::ModeDelete:
2318 if ((state.iFlags & pkgDepCache::Purge) != 0)
2322 case pkgDepCache::ModeKeep:
2323 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2324 return @"REINSTALL";
2325 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2329 case pkgDepCache::ModeInstall:
2330 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2331 return @"REINSTALL";
2332 else*/ switch (state.Status) {
2334 return @"DOWNGRADE";
2340 return @"NEW_INSTALL";
2353 - (NSString *) name {
2354 return name_.empty() ? id_ : name_;
2357 - (UIImage *) icon {
2358 NSString *section = [self simpleSection];
2362 if ([icon_ hasPrefix:@"file:///"])
2363 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2364 if (icon == nil) if (section != nil)
2365 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2366 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2367 if ([dicon hasPrefix:@"file:///"])
2368 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2370 icon = [UIImage applicationImageNamed:@"unknown.png"];
2374 - (NSString *) homepage {
2378 - (NSString *) depiction {
2382 - (Address *) sponsor {
2383 if (sponsor$_ == nil) {
2384 if (sponsor_.empty())
2386 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2390 - (Address *) author {
2391 if (author$_ == nil) {
2392 if (author_.empty())
2394 author$_ = [[Address addressWithString:author_] retain];
2398 - (NSString *) support {
2399 return !support_.empty() ? support_ : [[self source] supportForPackage:id_];
2402 - (NSArray *) files {
2403 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2404 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2407 fin.open([path UTF8String]);
2412 while (std::getline(fin, line))
2413 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2418 - (NSArray *) relationships {
2419 return relationships_;
2422 - (NSArray *) warnings {
2423 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2424 const char *name(iterator_.Name());
2426 size_t length(strlen(name));
2427 if (length < 2) invalid:
2428 [warnings addObject:CYLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2429 else for (size_t i(0); i != length; ++i)
2431 /* XXX: technically this is not allowed */
2432 (name[i] < 'A' || name[i] > 'Z') &&
2433 (name[i] < 'a' || name[i] > 'z') &&
2434 (name[i] < '0' || name[i] > '9') &&
2435 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2438 if (strcmp(name, "cydia") != 0) {
2440 bool _private = false;
2443 bool repository = [[self section] isEqualToString:@"Repositories"];
2445 if (NSArray *files = [self files])
2446 for (NSString *file in files)
2447 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2449 else if (!_private && [file isEqualToString:@"/private"])
2451 else if (!stash && [file isEqualToString:@"/var/stash"])
2454 /* XXX: this is not sensitive enough. only some folders are valid. */
2455 if (cydia && !repository)
2456 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2458 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/private"]];
2460 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2463 return [warnings count] == 0 ? nil : warnings;
2466 - (NSArray *) applications {
2467 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2469 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2471 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2472 if (NSArray *files = [self files])
2473 for (NSString *file in files)
2474 if (application_r(file)) {
2475 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2476 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2477 if ([id isEqualToString:me])
2480 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2482 display = application_r[1];
2484 NSString *bundle([file stringByDeletingLastPathComponent]);
2485 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2486 if (icon == nil || [icon length] == 0)
2488 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2490 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2491 [applications addObject:application];
2493 [application addObject:id];
2494 [application addObject:display];
2495 [application addObject:url];
2498 return [applications count] == 0 ? nil : applications;
2501 - (Source *) source {
2503 @synchronized (database_) {
2504 if ([database_ era] != era_ || file_.end())
2507 source_ = [database_ getSource:file_.File()];
2519 - (NSString *) role {
2523 - (BOOL) matches:(NSString *)text {
2529 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2530 if (range.location != NSNotFound)
2533 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2534 if (range.location != NSNotFound)
2537 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2538 if (range.location != NSNotFound)
2544 - (bool) hasSupportingRole {
2547 if ([role_ isEqualToString:@"enduser"])
2549 if ([Role_ isEqualToString:@"User"])
2551 if ([role_ isEqualToString:@"hacker"])
2553 if ([Role_ isEqualToString:@"Hacker"])
2555 if ([role_ isEqualToString:@"developer"])
2557 if ([Role_ isEqualToString:@"Developer"])
2562 - (BOOL) hasTag:(NSString *)tag {
2563 return tags_ == nil ? NO : [tags_ containsObject:tag];
2566 - (NSString *) primaryPurpose {
2567 for (NSString *tag in tags_)
2568 if ([tag hasPrefix:@"purpose::"])
2569 return [tag substringFromIndex:9];
2573 - (NSArray *) purposes {
2574 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2575 for (NSString *tag in tags_)
2576 if ([tag hasPrefix:@"purpose::"])
2577 [purposes addObject:[tag substringFromIndex:9]];
2578 return [purposes count] == 0 ? nil : purposes;
2581 - (bool) isCommercial {
2582 return [self hasTag:@"cydia::commercial"];
2585 - (CYString &) cyname {
2586 return name_.empty() ? id_ : name_;
2589 - (uint32_t) compareBySection:(NSArray *)sections {
2590 NSString *section([self section]);
2591 for (size_t i(0), e([sections count]); i != e; ++i) {
2592 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2596 return _not(uint32_t);
2599 - (uint32_t) compareForChanges {
2604 uint32_t timestamp : 30;
2605 uint32_t ignored : 1;
2606 uint32_t upgradable : 1;
2610 bool upgradable([self upgradableAndEssential:YES]);
2611 value.bits.upgradable = upgradable ? 1 : 0;
2614 value.bits.timestamp = 0;
2615 value.bits.ignored = [self ignored] ? 0 : 1;
2616 value.bits.upgradable = 1;
2618 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2619 value.bits.ignored = 0;
2620 value.bits.upgradable = 0;
2623 return _not(uint32_t) - value.key;
2627 pkgProblemResolver *resolver = [database_ resolver];
2628 resolver->Clear(iterator_);
2629 resolver->Protect(iterator_);
2633 pkgProblemResolver *resolver = [database_ resolver];
2634 resolver->Clear(iterator_);
2635 resolver->Protect(iterator_);
2636 pkgCacheFile &cache([database_ cache]);
2637 cache->MarkInstall(iterator_, false);
2638 pkgDepCache::StateCache &state((*cache)[iterator_]);
2639 if (!state.Install())
2640 cache->SetReInstall(iterator_, true);
2644 pkgProblemResolver *resolver = [database_ resolver];
2645 resolver->Clear(iterator_);
2646 resolver->Protect(iterator_);
2647 resolver->Remove(iterator_);
2648 [database_ cache]->MarkDelete(iterator_, true);
2651 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2652 _profile(Package$isUnfilteredAndSearchedForBy)
2655 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2656 value &= [self unfiltered];
2659 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2660 value &= [self matches:search];
2667 - (bool) isInstalledAndVisible:(NSNumber *)number {
2668 return (![number boolValue] || [self visible]) && [self installed] != nil;
2671 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2672 NSString *section = [self section];
2676 [self installed] == nil && (
2678 section == nil && [name length] == 0 ||
2679 [name isEqualToString:section]
2683 - (bool) isVisibleInSource:(Source *)source {
2684 return [self source] == source && [self visible];
2689 /* Section Class {{{ */
2690 @interface Section : NSObject {
2695 NSString *localized_;
2698 - (NSComparisonResult) compareByLocalized:(Section *)section;
2699 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2700 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2701 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2702 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2703 - (NSString *) name;
2710 - (void) addToCount;
2712 - (void) setCount:(size_t)count;
2713 - (NSString *) localized;
2717 @implementation Section
2721 if (localized_ != nil)
2722 [localized_ release];
2726 - (NSComparisonResult) compareByLocalized:(Section *)section {
2727 NSString *lhs(localized_);
2728 NSString *rhs([section localized]);
2730 /*if ([lhs length] != 0 && [rhs length] != 0) {
2731 unichar lhc = [lhs characterAtIndex:0];
2732 unichar rhc = [rhs characterAtIndex:0];
2734 if (isalpha(lhc) && !isalpha(rhc))
2735 return NSOrderedAscending;
2736 else if (!isalpha(lhc) && isalpha(rhc))
2737 return NSOrderedDescending;
2740 return [lhs compare:rhs options:LaxCompareOptions_];
2743 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2744 if ((self = [self initWithName:name localize:NO]) != nil) {
2745 if (localized != nil)
2746 localized_ = [localized retain];
2750 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2751 return [self initWithName:name row:0 localize:localize];
2754 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2755 if ((self = [super init]) != nil) {
2756 name_ = [name retain];
2760 localized_ = [LocalizeSection(name_) retain];
2764 /* XXX: localize the index thingees */
2765 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2766 if ((self = [super init]) != nil) {
2767 name_ = [(index == '#' ? @"123" : [NSString stringWithCharacters:&index length:1]) retain];
2773 - (NSString *) name {
2793 - (void) addToCount {
2797 - (void) setCount:(size_t)count {
2801 - (NSString *) localized {
2809 static NSArray *Finishes_;
2811 /* Database Implementation {{{ */
2812 @implementation Database
2814 + (Database *) sharedInstance {
2815 static Database *instance;
2816 if (instance == nil)
2817 instance = [[Database alloc] init];
2827 NSRecycleZone(zone_);
2828 // XXX: malloc_destroy_zone(zone_);
2829 apr_pool_destroy(pool_);
2833 - (void) _readCydia:(NSNumber *)fd { _pooled
2834 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2835 std::istream is(&ib);
2838 static Pcre finish_r("^finish:([^:]*)$");
2840 while (std::getline(is, line)) {
2841 const char *data(line.c_str());
2842 size_t size = line.size();
2843 lprintf("C:%s\n", data);
2845 if (finish_r(data, size)) {
2846 NSString *finish = finish_r[1];
2847 int index = [Finishes_ indexOfObject:finish];
2848 if (index != INT_MAX && index > Finish_)
2856 - (void) _readStatus:(NSNumber *)fd { _pooled
2857 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2858 std::istream is(&ib);
2861 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2862 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2864 while (std::getline(is, line)) {
2865 const char *data(line.c_str());
2866 size_t size = line.size();
2867 lprintf("S:%s\n", data);
2869 if (conffile_r(data, size)) {
2870 [delegate_ setConfigurationData:conffile_r[1]];
2871 } else if (strncmp(data, "status: ", 8) == 0) {
2872 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2873 [delegate_ setProgressTitle:string];
2874 } else if (pmstatus_r(data, size)) {
2875 std::string type([pmstatus_r[1] UTF8String]);
2876 NSString *id = pmstatus_r[2];
2878 float percent([pmstatus_r[3] floatValue]);
2879 [delegate_ setProgressPercent:(percent / 100)];
2881 NSString *string = pmstatus_r[4];
2883 if (type == "pmerror")
2884 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2885 withObject:[NSArray arrayWithObjects:string, id, nil]
2888 else if (type == "pmstatus") {
2889 [delegate_ setProgressTitle:string];
2890 } else if (type == "pmconffile")
2891 [delegate_ setConfigurationData:string];
2892 else _assert(false);
2893 } else _assert(false);
2899 - (void) _readOutput:(NSNumber *)fd { _pooled
2900 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2901 std::istream is(&ib);
2904 while (std::getline(is, line)) {
2905 lprintf("O:%s\n", line.c_str());
2906 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2916 - (Package *) packageWithName:(NSString *)name {
2917 if (static_cast<pkgDepCache *>(cache_) == NULL)
2919 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
2920 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
2923 - (Database *) init {
2924 if ((self = [super init]) != nil) {
2931 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
2932 apr_pool_create(&pool_, NULL);
2934 sources_ = [[NSMutableDictionary dictionaryWithCapacity:16] retain];
2935 packages_ = [[NSMutableArray alloc] init];
2939 _assert(pipe(fds) != -1);
2942 _config->Set("APT::Keep-Fds::", cydiafd_);
2943 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
2946 detachNewThreadSelector:@selector(_readCydia:)
2948 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2951 _assert(pipe(fds) != -1);
2955 detachNewThreadSelector:@selector(_readStatus:)
2957 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2960 _assert(pipe(fds) != -1);
2961 _assert(dup2(fds[0], 0) != -1);
2962 _assert(close(fds[0]) != -1);
2964 input_ = fdopen(fds[1], "a");
2966 _assert(pipe(fds) != -1);
2967 _assert(dup2(fds[1], 1) != -1);
2968 _assert(close(fds[1]) != -1);
2971 detachNewThreadSelector:@selector(_readOutput:)
2973 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2978 - (pkgCacheFile &) cache {
2982 - (pkgDepCache::Policy *) policy {
2986 - (pkgRecords *) records {
2990 - (pkgProblemResolver *) resolver {
2994 - (pkgAcquire &) fetcher {
2998 - (pkgSourceList &) list {
3002 - (NSArray *) packages {
3006 - (NSArray *) sources {
3007 return [sources_ allValues];
3010 - (NSArray *) issues {
3011 if (cache_->BrokenCount() == 0)
3014 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3016 for (Package *package in packages_) {
3017 if (![package broken])
3019 pkgCache::PkgIterator pkg([package iterator]);
3021 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3022 [entry addObject:[package name]];
3023 [issues addObject:entry];
3025 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3029 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3030 pkgCache::DepIterator start;
3031 pkgCache::DepIterator end;
3032 dep.GlobOr(start, end); // ++dep
3034 if (!cache_->IsImportantDep(end))
3036 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3039 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3040 [entry addObject:failure];
3041 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3043 Package *package([self packageWithName:[NSString stringWithUTF8String:start.TargetPkg().Name()]]);
3044 [failure addObject:[package name]];
3046 pkgCache::PkgIterator target(start.TargetPkg());
3047 if (target->ProvidesList != 0)
3048 [failure addObject:@"?"];
3050 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3052 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3053 else if (!cache_[target].CandidateVerIter(cache_).end())
3054 [failure addObject:@"-"];
3055 else if (target->ProvidesList == 0)
3056 [failure addObject:@"!"];
3058 [failure addObject:@"%"];
3062 if (start.TargetVer() != 0)
3063 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3074 - (void) reloadData { _pooled
3075 @synchronized (self) {
3097 apr_pool_clear(pool_);
3098 NSRecycleZone(zone_);
3100 int chk(creat("/tmp/cydia.chk", 0644));
3105 if (!cache_.Open(progress_, true)) {
3107 if (!_error->PopMessage(error))
3110 lprintf("cache_.Open():[%s]\n", error.c_str());
3112 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3113 [delegate_ repairWithSelector:@selector(configure)];
3114 else if (error == "The package lists or status file could not be parsed or opened.")
3115 [delegate_ repairWithSelector:@selector(update)];
3116 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3117 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3118 // else if (error == "The list of sources could not be read.")
3119 else _assert(false);
3125 unlink("/tmp/cydia.chk");
3127 now_ = [[NSDate date] retain];
3129 policy_ = new pkgDepCache::Policy();
3130 records_ = new pkgRecords(cache_);
3131 resolver_ = new pkgProblemResolver(cache_);
3132 fetcher_ = new pkgAcquire(&status_);
3135 list_ = new pkgSourceList();
3136 _assert(list_->ReadMainList());
3138 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3139 _assert(pkgApplyStatus(cache_));
3141 if (cache_->BrokenCount() != 0) {
3142 _assert(pkgFixBroken(cache_));
3143 _assert(cache_->BrokenCount() == 0);
3144 _assert(pkgMinimizeUpgrade(cache_));
3149 std::string lists(_config->FindDir("Dir::State::lists"));
3151 [sources_ removeAllObjects];
3152 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3153 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3154 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3155 if (debPackagesIndex *packages = dynamic_cast<debPackagesIndex *>(*index))
3157 setObject:[[[Source alloc] initWithMetaIndex:*source] autorelease]
3158 forKey:[NSString stringWithFormat:@"%s%s",
3160 URItoFileName(packages->IndexURI("Packages")).c_str()
3168 /*std::vector<Package *> packages;
3169 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3170 [packages_ release];
3173 [packages_ removeAllObjects];
3177 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3178 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3179 //packages.push_back(package);
3180 [packages_ addObject:package];
3184 /*if (packages.empty())
3185 packages_ = [[NSArray alloc] init];
3187 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3190 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3191 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3192 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3200 /*if (!packages.empty())
3201 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3202 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3204 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3206 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3208 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3214 - (void) configure {
3215 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3216 system([dpkg UTF8String]);
3224 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3225 _assert(!_error->PendingError());
3228 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3231 public pkgArchiveCleaner
3234 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3239 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3241 while (_error->PopMessage(error))
3242 lprintf("ArchiveCleaner: %s\n", error.c_str());
3247 pkgRecords records(cache_);
3249 lock_ = new FileFd();
3250 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3251 _assert(!_error->PendingError());
3254 // XXX: explain this with an error message
3255 _assert(list.ReadMainList());
3257 manager_ = (_system->CreatePM(cache_));
3258 _assert(manager_->GetArchives(fetcher_, &list, &records));
3259 _assert(!_error->PendingError());
3263 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3265 _assert(list.ReadMainList());
3266 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3267 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3270 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3275 bool failed = false;
3276 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3277 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3280 std::string uri = (*item)->DescURI();
3281 std::string error = (*item)->ErrorText;
3283 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3286 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3287 withObject:[NSArray arrayWithObjects:
3288 [NSString stringWithUTF8String:error.c_str()],
3300 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3302 if (_error->PendingError()) {
3307 if (result == pkgPackageManager::Failed) {
3312 if (result != pkgPackageManager::Completed) {
3317 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3319 _assert(list.ReadMainList());
3320 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3321 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3324 if (![before isEqualToArray:after])
3329 _assert(pkgDistUpgrade(cache_));
3333 [self updateWithStatus:status_];
3336 - (void) updateWithStatus:(Status &)status {
3338 _assert(list.ReadMainList());
3341 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3342 _assert(!_error->PendingError());
3344 pkgAcquire fetcher(&status);
3345 _assert(list.GetIndexes(&fetcher));
3347 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3348 bool failed = false;
3349 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3350 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3351 (*item)->Finished();
3355 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3356 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3357 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3360 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3365 - (void) setDelegate:(id)delegate {
3366 delegate_ = delegate;
3367 status_.setDelegate(delegate);
3368 progress_.setDelegate(delegate);
3371 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3372 if (const char *name = file.FileName())
3373 if (Source *source = [sources_ objectForKey:[NSString stringWithUTF8String:name]])
3381 /* PopUp Windows {{{ */
3382 @interface PopUpView : UIView {
3383 _transient id delegate_;
3384 UITransitionView *transition_;
3389 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3393 @implementation PopUpView
3396 [transition_ setDelegate:nil];
3397 [transition_ release];
3403 [transition_ transition:UITransitionPushFromTop toView:nil];
3406 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3407 if (from != nil && to == nil)
3408 [self removeFromSuperview];
3411 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3412 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3413 delegate_ = delegate;
3415 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3416 [self addSubview:transition_];
3418 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3420 [view addSubview:self];
3422 [transition_ setDelegate:self];
3424 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3425 [transition_ transition:UITransitionNone toView:blank];
3426 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3434 /* Mail Composition {{{ */
3435 @interface MailToView : PopUpView {
3436 MailComposeController *controller_;
3439 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
3443 @implementation MailToView
3446 [controller_ release];
3450 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
3454 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
3455 NSLog(@"did:%@", delivery);
3456 // [UIApp setStatusBarShowsProgress:NO];
3457 if ([controller error]){
3458 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3459 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3460 [mailAlertSheet setBodyText:[controller error]];
3461 [mailAlertSheet popupAlertAnimated:YES];
3465 - (void) showError {
3466 NSLog(@"%@", [controller_ error]);
3467 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3468 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3469 [mailAlertSheet setBodyText:[controller_ error]];
3470 [mailAlertSheet popupAlertAnimated:YES];
3473 - (void) deliverMessage { _pooled
3477 if (![controller_ deliverMessage])
3478 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
3481 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
3482 if ([controller_ needsDelivery])
3483 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
3488 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
3489 if ((self = [super initWithView:view delegate:delegate]) != nil) {
3490 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
3491 [controller_ setDelegate:self];
3492 [controller_ initializeUI];
3493 [controller_ setupForURL:url];
3495 UIView *view([controller_ view]);
3496 [overlay_ addSubview:view];
3504 /* Confirmation View {{{ */
3505 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3506 if (!iterator.end())
3507 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3508 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3510 pkgCache::PkgIterator package(dep.TargetPkg());
3513 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3520 @protocol ConfirmationViewDelegate
3526 @interface ConfirmationView : BrowserView {
3527 _transient Database *database_;
3528 UIActionSheet *essential_;
3535 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3539 @implementation ConfirmationView
3546 if (essential_ != nil)
3547 [essential_ release];
3553 [book_ popFromSuperviewAnimated:YES];
3556 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3557 NSString *context([sheet context]);
3559 if ([context isEqualToString:@"remove"]) {
3567 [delegate_ confirm];
3574 } else if ([context isEqualToString:@"unable"]) {
3578 [super alertSheet:sheet buttonClicked:button];
3581 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3582 [super webView:sender didClearWindowObject:window forFrame:frame];
3583 [window setValue:changes_ forKey:@"changes"];
3584 [window setValue:issues_ forKey:@"issues"];
3585 [window setValue:sizes_ forKey:@"sizes"];
3588 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3589 if ((self = [super initWithBook:book]) != nil) {
3590 database_ = database;
3592 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3593 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3594 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3595 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3596 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3600 pkgDepCache::Policy *policy([database_ policy]);
3602 pkgCacheFile &cache([database_ cache]);
3603 NSArray *packages = [database_ packages];
3604 for (Package *package in packages) {
3605 pkgCache::PkgIterator iterator = [package iterator];
3606 pkgDepCache::StateCache &state(cache[iterator]);
3608 NSString *name([package name]);
3610 if (state.NewInstall())
3611 [installing addObject:name];
3612 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3613 [reinstalling addObject:name];
3614 else if (state.Upgrade())
3615 [upgrading addObject:name];
3616 else if (state.Downgrade())
3617 [downgrading addObject:name];
3618 else if (state.Delete()) {
3619 if ([package essential])
3621 [removing addObject:name];
3624 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3625 substrate_ |= DepSubstrate(iterator.CurrentVer());
3630 else if (Advanced_ || true) {
3631 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
3633 essential_ = [[UIActionSheet alloc]
3634 initWithTitle:CYLocalize("REMOVING_ESSENTIALS")
3635 buttons:[NSArray arrayWithObjects:
3636 [NSString stringWithFormat:parenthetical, CYLocalize("CANCEL_OPERATION"), CYLocalize("SAFE")],
3637 [NSString stringWithFormat:parenthetical, CYLocalize("FORCE_REMOVAL"), CYLocalize("UNSAFE")],
3639 defaultButtonIndex:0
3645 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3647 [essential_ setBodyText:CYLocalize("REMOVING_ESSENTIALS_EX")];
3649 essential_ = [[UIActionSheet alloc]
3650 initWithTitle:CYLocalize("UNABLE_TO_COMPLY")
3651 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3652 defaultButtonIndex:0
3657 [essential_ setBodyText:CYLocalize("UNABLE_TO_COMPLY_EX")];
3660 changes_ = [[NSArray alloc] initWithObjects:
3668 issues_ = [database_ issues];
3670 issues_ = [issues_ retain];
3672 sizes_ = [[NSArray alloc] initWithObjects:
3673 SizeString([database_ fetcher].FetchNeeded()),
3674 SizeString([database_ fetcher].PartialPresent()),
3675 SizeString([database_ cache]->UsrSize()),
3678 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3682 - (NSString *) backButtonTitle {
3683 return CYLocalize("CONFIRM");
3686 - (NSString *) leftButtonTitle {
3687 return [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("CANCEL"), CYLocalize("QUEUE")];
3690 - (id) rightButtonTitle {
3691 return issues_ != nil ? nil : [super rightButtonTitle];
3694 - (id) _rightButtonTitle {
3695 #if AlwaysReload || IgnoreInstall
3696 return [super _rightButtonTitle];
3698 return CYLocalize("CONFIRM");
3702 - (void) _leftButtonClicked {
3707 - (void) _rightButtonClicked {
3709 return [super _rightButtonClicked];
3711 if (essential_ != nil)
3712 [essential_ popupAlertAnimated:YES];
3716 [delegate_ confirm];
3724 /* Progress Data {{{ */
3725 @interface ProgressData : NSObject {
3731 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3738 @implementation ProgressData
3740 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3741 if ((self = [super init]) != nil) {
3742 selector_ = selector;
3762 /* Progress View {{{ */
3763 @interface ProgressView : UIView <
3764 ConfigurationDelegate,
3767 _transient Database *database_;
3769 UIView *background_;
3770 UITransitionView *transition_;
3772 UINavigationBar *navbar_;
3773 UIProgressBar *progress_;
3774 UITextView *output_;
3775 UITextLabel *status_;
3776 UIPushButton *close_;
3779 SHA1SumValue springlist_;
3780 SHA1SumValue notifyconf_;
3781 SHA1SumValue sandplate_;
3784 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
3786 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
3787 - (void) setContentView:(UIView *)view;
3790 - (void) _retachThread;
3791 - (void) _detachNewThreadData:(ProgressData *)data;
3792 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
3798 @protocol ProgressViewDelegate
3799 - (void) progressViewIsComplete:(ProgressView *)sender;
3802 @implementation ProgressView
3805 [transition_ setDelegate:nil];
3806 [navbar_ setDelegate:nil];
3809 if (background_ != nil)
3810 [background_ release];
3811 [transition_ release];
3814 [progress_ release];
3821 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3822 if (bootstrap_ && from == overlay_ && to == view_)
3826 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
3827 if ((self = [super initWithFrame:frame]) != nil) {
3828 database_ = database;
3829 delegate_ = delegate;
3831 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3832 [transition_ setDelegate:self];
3834 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3837 [overlay_ setBackgroundColor:[UIColor blackColor]];
3839 background_ = [[UIView alloc] initWithFrame:[self bounds]];
3840 [background_ setBackgroundColor:[UIColor blackColor]];
3841 [self addSubview:background_];
3844 [self addSubview:transition_];
3846 CGSize navsize = [UINavigationBar defaultSize];
3847 CGRect navrect = {{0, 0}, navsize};
3849 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
3850 [overlay_ addSubview:navbar_];
3852 [navbar_ setBarStyle:1];
3853 [navbar_ setDelegate:self];
3855 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
3856 [navbar_ pushNavigationItem:navitem];
3858 CGRect bounds = [overlay_ bounds];
3859 CGSize prgsize = [UIProgressBar defaultSize];
3862 (bounds.size.width - prgsize.width) / 2,
3863 bounds.size.height - prgsize.height - 20
3866 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3867 [progress_ setStyle:0];
3869 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3871 bounds.size.height - prgsize.height - 50,
3872 bounds.size.width - 20,
3876 [status_ setColor:[UIColor whiteColor]];
3877 [status_ setBackgroundColor:[UIColor clearColor]];
3879 [status_ setCentersHorizontally:YES];
3880 //[status_ setFont:font];
3883 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3885 navrect.size.height + 20,
3886 bounds.size.width - 20,
3887 bounds.size.height - navsize.height - 62 - navrect.size.height
3891 //[output_ setTextFont:@"Courier New"];
3892 [output_ setTextSize:12];
3894 [output_ setTextColor:[UIColor whiteColor]];
3895 [output_ setBackgroundColor:[UIColor clearColor]];
3897 [output_ setMarginTop:0];
3898 [output_ setAllowsRubberBanding:YES];
3899 [output_ setEditable:NO];
3901 [overlay_ addSubview:output_];
3903 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3905 bounds.size.height - prgsize.height - 50,
3906 bounds.size.width - 20,
3910 [close_ setAutosizesToFit:NO];
3911 [close_ setDrawsShadow:YES];
3912 [close_ setStretchBackground:YES];
3913 [close_ setEnabled:YES];
3915 UIFont *bold = [UIFont boldSystemFontOfSize:22];
3916 [close_ setTitleFont:bold];
3918 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
3919 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
3920 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
3924 - (void) setContentView:(UIView *)view {
3925 view_ = [view retain];
3928 - (void) resetView {
3929 [transition_ transition:6 toView:view_];
3932 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3933 NSString *context([sheet context]);
3935 if ([context isEqualToString:@"error"])
3937 else if ([context isEqualToString:@"conffile"]) {
3938 FILE *input = [database_ input];
3942 fprintf(input, "N\n");
3946 fprintf(input, "Y\n");
3957 - (void) closeButtonPushed {
3966 [delegate_ suspendWithAnimation:YES];
3970 system("launchctl stop com.apple.SpringBoard");
3974 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
3983 - (void) _retachThread {
3984 UINavigationItem *item = [navbar_ topItem];
3985 [item setTitle:CYLocalize("COMPLETE")];
3987 [overlay_ addSubview:close_];
3988 [progress_ removeFromSuperview];
3989 [status_ removeFromSuperview];
3991 [delegate_ progressViewIsComplete:self];
3994 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
3995 MMap mmap(file, MMap::ReadOnly);
3997 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3998 if (!(sandplate_ == sha1.Result()))
4003 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4004 MMap mmap(file, MMap::ReadOnly);
4006 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4007 if (!(notifyconf_ == sha1.Result()))
4012 FileFd file(SpringBoard_, FileFd::ReadOnly);
4013 MMap mmap(file, MMap::ReadOnly);
4015 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4016 if (!(springlist_ == sha1.Result()))
4021 case 0: [close_ setTitle:CYLocalize("RETURN_TO_CYDIA")]; break;
4022 case 1: [close_ setTitle:CYLocalize("CLOSE_CYDIA")]; break;
4023 case 2: [close_ setTitle:CYLocalize("RESTART_SPRINGBOARD")]; break;
4024 case 3: [close_ setTitle:CYLocalize("RELOAD_SPRINGBOARD")]; break;
4025 case 4: [close_ setTitle:CYLocalize("REBOOT_DEVICE")]; break;
4028 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4030 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
4031 [cache autorelease];
4033 NSFileManager *manager = [NSFileManager defaultManager];
4034 NSError *error = nil;
4036 id system = [cache objectForKey:@"System"];
4041 if (stat(Cache_, &info) == -1)
4044 [system removeAllObjects];
4046 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4047 for (NSString *app in apps)
4048 if ([app hasSuffix:@".app"]) {
4049 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4050 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4051 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4053 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4054 [info setObject:path forKey:@"Path"];
4055 [info setObject:@"System" forKey:@"ApplicationType"];
4056 [system addInfoDictionary:info];
4062 [cache writeToFile:@Cache_ atomically:YES];
4064 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
4066 if (chmod(Cache_, info.st_mode) == -1)
4070 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4073 notify_post("com.apple.mobile.application_installed");
4075 [delegate_ setStatusBarShowsProgress:NO];
4078 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4079 [[data target] performSelector:[data selector] withObject:[data object]];
4082 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4085 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4086 UINavigationItem *item = [navbar_ topItem];
4087 [item setTitle:title];
4089 [status_ setText:nil];
4090 [output_ setText:@""];
4091 [progress_ setProgress:0];
4093 [close_ removeFromSuperview];
4094 [overlay_ addSubview:progress_];
4095 [overlay_ addSubview:status_];
4097 [delegate_ setStatusBarShowsProgress:YES];
4101 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4102 MMap mmap(file, MMap::ReadOnly);
4104 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4105 sandplate_ = sha1.Result();
4109 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4110 MMap mmap(file, MMap::ReadOnly);
4112 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4113 notifyconf_ = sha1.Result();
4117 FileFd file(SpringBoard_, FileFd::ReadOnly);
4118 MMap mmap(file, MMap::ReadOnly);
4120 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4121 springlist_ = sha1.Result();
4124 [transition_ transition:6 toView:overlay_];
4127 detachNewThreadSelector:@selector(_detachNewThreadData:)
4129 withObject:[[ProgressData alloc]
4130 initWithSelector:selector
4137 - (void) repairWithSelector:(SEL)selector {
4139 detachNewThreadSelector:selector
4142 title:CYLocalize("REPAIRING")
4146 - (void) setConfigurationData:(NSString *)data {
4148 performSelectorOnMainThread:@selector(_setConfigurationData:)
4154 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4155 Package *package = id == nil ? nil : [database_ packageWithName:id];
4157 UIActionSheet *sheet = [[[UIActionSheet alloc]
4158 initWithTitle:(package == nil ? id : [package name])
4159 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
4160 defaultButtonIndex:0
4165 [sheet setBodyText:error];
4166 [sheet popupAlertAnimated:YES];
4169 - (void) setProgressTitle:(NSString *)title {
4171 performSelectorOnMainThread:@selector(_setProgressTitle:)
4177 - (void) setProgressPercent:(float)percent {
4179 performSelectorOnMainThread:@selector(_setProgressPercent:)
4180 withObject:[NSNumber numberWithFloat:percent]
4185 - (void) startProgress {
4188 - (void) addProgressOutput:(NSString *)output {
4190 performSelectorOnMainThread:@selector(_addProgressOutput:)
4196 - (bool) isCancelling:(size_t)received {
4200 - (void) _setConfigurationData:(NSString *)data {
4201 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4203 _assert(conffile_r(data));
4205 NSString *ofile = conffile_r[1];
4206 //NSString *nfile = conffile_r[2];
4208 UIActionSheet *sheet = [[[UIActionSheet alloc]
4209 initWithTitle:CYLocalize("CONFIGURATION_UPGRADE")
4210 buttons:[NSArray arrayWithObjects:
4211 CYLocalize("KEEP_OLD_COPY"),
4212 CYLocalize("ACCEPT_NEW_COPY"),
4213 // XXX: CYLocalize("SEE_WHAT_CHANGED"),
4215 defaultButtonIndex:0
4220 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", CYLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4221 [sheet popupAlertAnimated:YES];
4224 - (void) _setProgressTitle:(NSString *)title {
4225 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4226 for (size_t i(0), e([words count]); i != e; ++i) {
4227 NSString *word([words objectAtIndex:i]);
4228 if (Package *package = [database_ packageWithName:word])
4229 [words replaceObjectAtIndex:i withObject:[package name]];
4232 [status_ setText:[words componentsJoinedByString:@" "]];
4235 - (void) _setProgressPercent:(NSNumber *)percent {
4236 [progress_ setProgress:[percent floatValue]];
4239 - (void) _addProgressOutput:(NSString *)output {
4240 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4241 CGSize size = [output_ contentSize];
4242 CGRect rect = {{0, size.height}, {size.width, 0}};
4243 [output_ scrollRectToVisible:rect animated:YES];
4246 - (BOOL) isRunning {
4253 /* Package Cell {{{ */
4254 @interface PackageCell : UITableCell {
4257 NSString *description_;
4264 UITextLabel *status_;
4268 - (PackageCell *) init;
4269 - (void) setPackage:(Package *)package;
4271 + (int) heightForPackage:(Package *)package;
4275 @implementation PackageCell
4277 - (void) clearPackage {
4288 if (description_ != nil) {
4289 [description_ release];
4293 if (source_ != nil) {
4298 if (badge_ != nil) {
4308 [self clearPackage];
4315 - (PackageCell *) init {
4316 if ((self = [super init]) != nil) {
4318 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4319 [status_ setBackgroundColor:[UIColor clearColor]];
4320 [status_ setFont:small];
4325 - (void) setPackage:(Package *)package {
4326 [self clearPackage];
4328 Source *source = [package source];
4330 icon_ = [[package icon] retain];
4331 name_ = [[package name] retain];
4332 description_ = [[package shortDescription] retain];
4333 commercial_ = [package isCommercial];
4335 package_ = [package retain];
4337 NSString *label = nil;
4338 bool trusted = false;
4340 if (source != nil) {
4341 label = [source label];
4342 trusted = [source trusted];
4343 } else if ([[package id] isEqualToString:@"firmware"])
4344 label = CYLocalize("APPLE");
4346 label = [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("UNKNOWN"), CYLocalize("LOCAL")];
4348 NSString *from(label);
4350 NSString *section = [package simpleSection];
4351 if (section != nil && ![section isEqualToString:label]) {
4352 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4353 from = [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), from, section];
4356 from = [NSString stringWithFormat:CYLocalize("FROM"), from];
4357 source_ = [from retain];
4359 if (NSString *purpose = [package primaryPurpose])
4360 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4361 badge_ = [badge_ retain];
4364 if (NSString *mode = [package mode]) {
4365 [badge_ setImage:[UIImage applicationImageNamed:
4366 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4369 [status_ setText:[NSString stringWithFormat:CYLocalize("QUEUED_FOR"), CYLocalize(mode)]];
4370 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4371 } else if ([package half]) {
4372 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4373 [status_ setText:CYLocalize("PACKAGE_DAMAGED")];
4374 [status_ setColor:[UIColor redColor]];
4376 [badge_ setImage:nil];
4377 [status_ setText:nil];
4384 - (void) drawRect:(CGRect)rect {
4388 if (NSString *mode = [package_ mode]) {
4389 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4390 color = remove ? RemovingColor_ : InstallingColor_;
4392 color = [UIColor whiteColor];
4394 [self setBackgroundColor:color];
4398 [super drawRect:rect];
4401 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4403 CGContextRef context(UIGraphicsGetCurrentContext());
4404 [[self backgroundColor] set];
4406 back.size.height -= 1;
4407 CGContextFillRect(context, back);
4410 [super drawBackgroundInRect:rect withFade:fade];
4413 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4416 rect.size = [icon_ size];
4418 rect.size.width /= 2;
4419 rect.size.height /= 2;
4421 rect.origin.x = 25 - rect.size.width / 2;
4422 rect.origin.y = 25 - rect.size.height / 2;
4424 [icon_ drawInRect:rect];
4427 if (badge_ != nil) {
4428 CGSize size = [badge_ size];
4430 [badge_ drawAtPoint:CGPointMake(
4431 36 - size.width / 2,
4432 36 - size.height / 2
4440 UISetColor(commercial_ ? Purple_ : Black_);
4441 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4442 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4445 UISetColor(commercial_ ? Purplish_ : Gray_);
4446 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4448 [super drawContentInRect:rect selected:selected];
4451 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4453 [super setSelected:selected withFade:fade];
4456 + (int) heightForPackage:(Package *)package {
4457 NSString *tagline([package shortDescription]);
4458 int height = tagline == nil || [tagline length] == 0 ? -17 : 0;
4460 if ([package hasMode] || [package half])
4469 /* Section Cell {{{ */
4470 @interface SectionCell : UISimpleTableCell {
4475 _UISwitchSlider *switch_;
4480 - (void) setSection:(Section *)section editing:(BOOL)editing;
4484 @implementation SectionCell
4486 - (void) clearSection {
4487 if (section_ != nil) {
4497 if (count_ != nil) {
4504 [self clearSection];
4511 if ((self = [super init]) != nil) {
4512 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4514 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4515 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4519 - (void) onSwitch:(id)sender {
4520 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4521 if (metadata == nil) {
4522 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4523 [Sections_ setObject:metadata forKey:section_];
4527 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4530 - (void) setSection:(Section *)section editing:(BOOL)editing {
4531 if (editing != editing_) {
4533 [switch_ removeFromSuperview];
4535 [self addSubview:switch_];
4539 [self clearSection];
4541 if (section == nil) {
4542 name_ = [CYLocalize("ALL_PACKAGES") retain];
4545 section_ = [section localized];
4546 if (section_ != nil)
4547 section_ = [section_ retain];
4548 name_ = [(section_ == nil ? CYLocalize("NO_SECTION") : section_) retain];
4549 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4552 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4556 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4557 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4564 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4566 CGSize size = [count_ sizeWithFont:Font14_];
4570 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4572 [super drawContentInRect:rect selected:selected];
4578 /* File Table {{{ */
4579 @interface FileTable : RVPage {
4580 _transient Database *database_;
4583 NSMutableArray *files_;
4587 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4588 - (void) setPackage:(Package *)package;
4592 @implementation FileTable
4595 if (package_ != nil)
4604 - (int) numberOfRowsInTable:(UITable *)table {
4605 return files_ == nil ? 0 : [files_ count];
4608 - (float) table:(UITable *)table heightForRow:(int)row {
4612 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4613 if (reusing == nil) {
4614 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4615 UIFont *font = [UIFont systemFontOfSize:16];
4616 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4618 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4622 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4626 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4627 if ((self = [super initWithBook:book]) != nil) {
4628 database_ = database;
4630 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4632 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4633 [self addSubview:list_];
4635 UITableColumn *column = [[[UITableColumn alloc]
4636 initWithTitle:CYLocalize("NAME")
4638 width:[self frame].size.width
4641 [list_ setDataSource:self];
4642 [list_ setSeparatorStyle:1];
4643 [list_ addTableColumn:column];
4644 [list_ setDelegate:self];
4645 [list_ setReusesTableCells:YES];
4649 - (void) setPackage:(Package *)package {
4650 if (package_ != nil) {
4651 [package_ autorelease];
4660 [files_ removeAllObjects];
4662 if (package != nil) {
4663 package_ = [package retain];
4664 name_ = [[package id] retain];
4666 if (NSArray *files = [package files])
4667 [files_ addObjectsFromArray:files];
4669 if ([files_ count] != 0) {
4670 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4671 [files_ removeObjectAtIndex:0];
4672 [files_ sortUsingSelector:@selector(compareByPath:)];
4674 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4675 [stack addObject:@"/"];
4677 for (int i(0), e([files_ count]); i != e; ++i) {
4678 NSString *file = [files_ objectAtIndex:i];
4679 while (![file hasPrefix:[stack lastObject]])
4680 [stack removeLastObject];
4681 NSString *directory = [stack lastObject];
4682 [stack addObject:[file stringByAppendingString:@"/"]];
4683 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4684 ([stack count] - 2) * 3, "",
4685 [file substringFromIndex:[directory length]]
4694 - (void) resetViewAnimated:(BOOL)animated {
4695 [list_ resetViewAnimated:animated];
4698 - (void) reloadData {
4699 [self setPackage:[database_ packageWithName:name_]];
4700 [self reloadButtons];
4703 - (NSString *) title {
4704 return CYLocalize("INSTALLED_FILES");
4707 - (NSString *) backButtonTitle {
4708 return CYLocalize("FILES");
4713 /* Package View {{{ */
4714 @interface PackageView : BrowserView {
4715 _transient Database *database_;
4719 NSMutableArray *buttons_;
4722 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4723 - (void) setPackage:(Package *)package;
4727 @implementation PackageView
4730 if (package_ != nil)
4739 if ([self retainCount] == 1)
4740 [delegate_ setPackageView:self];
4744 /* XXX: this is not safe at all... localization of /fail/ */
4745 - (void) _clickButtonWithName:(NSString *)name {
4746 if ([name isEqualToString:CYLocalize("CLEAR")])
4747 [delegate_ clearPackage:package_];
4748 else if ([name isEqualToString:CYLocalize("INSTALL")])
4749 [delegate_ installPackage:package_];
4750 else if ([name isEqualToString:CYLocalize("REINSTALL")])
4751 [delegate_ installPackage:package_];
4752 else if ([name isEqualToString:CYLocalize("REMOVE")])
4753 [delegate_ removePackage:package_];
4754 else if ([name isEqualToString:CYLocalize("UPGRADE")])
4755 [delegate_ installPackage:package_];
4756 else _assert(false);
4759 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4760 NSString *context([sheet context]);
4762 if ([context isEqualToString:@"modify"]) {
4763 int count = [buttons_ count];
4764 _assert(count != 0);
4765 _assert(button <= count + 1);
4767 if (count != button - 1)
4768 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
4772 [super alertSheet:sheet buttonClicked:button];
4775 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
4776 return [super webView:sender didFinishLoadForFrame:frame];
4779 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4780 [super webView:sender didClearWindowObject:window forFrame:frame];
4781 [window setValue:package_ forKey:@"package"];
4784 - (bool) _allowJavaScriptPanel {
4789 - (void) __rightButtonClicked {
4790 int count = [buttons_ count];
4791 _assert(count != 0);
4794 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
4796 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
4797 [buttons addObjectsFromArray:buttons_];
4798 [buttons addObject:CYLocalize("CANCEL")];
4800 [delegate_ slideUp:[[[UIActionSheet alloc]
4803 defaultButtonIndex:([buttons count] - 1)
4810 - (void) _rightButtonClicked {
4812 [super _rightButtonClicked];
4814 [self __rightButtonClicked];
4818 - (id) _rightButtonTitle {
4819 int count = [buttons_ count];
4820 return count == 0 ? nil : count != 1 ? CYLocalize("MODIFY") : [buttons_ objectAtIndex:0];
4823 - (NSString *) backButtonTitle {
4827 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4828 if ((self = [super initWithBook:book]) != nil) {
4829 database_ = database;
4830 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
4831 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
4835 - (void) setPackage:(Package *)package {
4836 if (package_ != nil) {
4837 [package_ autorelease];
4846 [buttons_ removeAllObjects];
4848 if (package != nil) {
4849 package_ = [package retain];
4850 name_ = [[package id] retain];
4851 commercial_ = [package isCommercial];
4853 if ([package_ mode] != nil)
4854 [buttons_ addObject:CYLocalize("CLEAR")];
4855 if ([package_ source] == nil);
4856 else if ([package_ upgradableAndEssential:NO])
4857 [buttons_ addObject:CYLocalize("UPGRADE")];
4858 else if ([package_ installed] == nil)
4859 [buttons_ addObject:CYLocalize("INSTALL")];
4861 [buttons_ addObject:CYLocalize("REINSTALL")];
4862 if ([package_ installed] != nil)
4863 [buttons_ addObject:CYLocalize("REMOVE")];
4865 if (special_ != NULL) {
4866 CGRect frame([webview_ frame]);
4867 frame.size.width = 320;
4868 frame.size.height = 0;
4869 [webview_ setFrame:frame];
4871 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
4874 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
4876 [self setButtonTitle:nil withStyle:nil toFunction:nil];
4878 [self setFinishHook:nil];
4879 [self setPopupHook:nil];
4882 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
4883 [super callFunction:special_];
4887 [self reloadButtons];
4890 - (bool) isLoading {
4891 return commercial_ ? [super isLoading] : false;
4894 - (void) reloadData {
4895 [self setPackage:[database_ packageWithName:name_]];
4900 /* Package Table {{{ */
4901 @interface PackageTable : RVPage {
4902 _transient Database *database_;
4904 NSMutableArray *packages_;
4905 NSMutableArray *sections_;
4906 UISectionList *list_;
4909 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
4911 - (void) setDelegate:(id)delegate;
4913 - (void) reloadData;
4914 - (void) resetCursor;
4916 - (UISectionList *) list;
4918 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
4922 @implementation PackageTable
4925 [list_ setDataSource:nil];
4928 [packages_ release];
4929 [sections_ release];
4934 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
4935 return [sections_ count];
4938 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
4939 return [[sections_ objectAtIndex:section] name];
4942 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
4943 return [[sections_ objectAtIndex:section] row];
4946 - (int) numberOfRowsInTable:(UITable *)table {
4947 return [packages_ count];
4950 - (float) table:(UITable *)table heightForRow:(int)row {
4951 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
4954 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4956 reusing = [[[PackageCell alloc] init] autorelease];
4957 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
4961 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
4965 - (void) tableRowSelected:(NSNotification *)notification {
4966 int row = [[notification object] selectedRow];
4970 Package *package = [packages_ objectAtIndex:row];
4971 package = [database_ packageWithName:[package id]];
4972 PackageView *view([delegate_ packageView]);
4973 [view setPackage:package];
4974 [view setDelegate:delegate_];
4975 [book_ pushPage:view];
4978 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
4979 if ((self = [super initWithBook:book]) != nil) {
4980 database_ = database;
4981 title_ = [title retain];
4983 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
4984 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
4986 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
4987 [list_ setDataSource:self];
4989 UITableColumn *column = [[[UITableColumn alloc]
4990 initWithTitle:CYLocalize("NAME")
4992 width:[self frame].size.width
4995 UITable *table = [list_ table];
4996 [table setSeparatorStyle:1];
4997 [table addTableColumn:column];
4998 [table setDelegate:self];
4999 [table setReusesTableCells:YES];
5001 [self addSubview:list_];
5003 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5004 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5008 - (void) setDelegate:(id)delegate {
5009 delegate_ = delegate;
5012 - (bool) hasPackage:(Package *)package {
5016 - (void) reloadData {
5017 NSArray *packages = [database_ packages];
5019 [packages_ removeAllObjects];
5020 [sections_ removeAllObjects];
5022 _profile(PackageTable$reloadData$Filter)
5023 for (Package *package in packages)
5024 if ([self hasPackage:package])
5025 [packages_ addObject:package];
5028 Section *section = nil;
5030 _profile(PackageTable$reloadData$Section)
5031 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5035 _profile(PackageTable$reloadData$Section$Package)
5036 package = [packages_ objectAtIndex:offset];
5037 index = [package index];
5040 if (section == nil || [section index] != index) {
5041 _profile(PackageTable$reloadData$Section$Allocate)
5042 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5045 _profile(PackageTable$reloadData$Section$Add)
5046 [sections_ addObject:section];
5050 [section addToCount];
5054 _profile(PackageTable$reloadData$List)
5059 - (NSString *) title {
5063 - (void) resetViewAnimated:(BOOL)animated {
5064 [list_ resetViewAnimated:animated];
5067 - (void) resetCursor {
5068 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
5071 - (UISectionList *) list {
5075 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5076 [list_ setShouldHideHeaderInShortLists:hide];
5081 /* Filtered Package Table {{{ */
5082 @interface FilteredPackageTable : PackageTable {
5088 - (void) setObject:(id)object;
5090 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5094 @implementation FilteredPackageTable
5102 - (void) setObject:(id)object {
5108 object_ = [object retain];
5111 - (bool) hasPackage:(Package *)package {
5112 _profile(FilteredPackageTable$hasPackage)
5113 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5117 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5118 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5120 object_ = object == nil ? nil : [object retain];
5122 /* XXX: this is an unsafe optimization of doomy hell */
5123 Method method = class_getInstanceMethod([Package class], filter);
5124 _assert(method != NULL);
5125 imp_ = method_getImplementation(method);
5126 _assert(imp_ != NULL);
5135 /* Add Source View {{{ */
5136 @interface AddSourceView : RVPage {
5137 _transient Database *database_;
5140 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5144 @implementation AddSourceView
5146 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5147 if ((self = [super initWithBook:book]) != nil) {
5148 database_ = database;
5154 /* Source Cell {{{ */
5155 @interface SourceCell : UITableCell {
5158 NSString *description_;
5164 - (SourceCell *) initWithSource:(Source *)source;
5168 @implementation SourceCell
5173 [description_ release];
5178 - (SourceCell *) initWithSource:(Source *)source {
5179 if ((self = [super init]) != nil) {
5181 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5183 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5184 icon_ = [icon_ retain];
5186 origin_ = [[source name] retain];
5187 label_ = [[source uri] retain];
5188 description_ = [[source description] retain];
5192 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5194 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5201 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5205 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5209 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5211 [super drawContentInRect:rect selected:selected];
5216 /* Source Table {{{ */
5217 @interface SourceTable : RVPage {
5218 _transient Database *database_;
5219 UISectionList *list_;
5220 NSMutableArray *sources_;
5221 UIActionSheet *alert_;
5225 UIProgressHUD *hud_;
5228 //NSURLConnection *installer_;
5229 NSURLConnection *trivial_bz2_;
5230 NSURLConnection *trivial_gz_;
5231 //NSURLConnection *automatic_;
5236 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5240 @implementation SourceTable
5242 - (void) _deallocConnection:(NSURLConnection *)connection {
5243 if (connection != nil) {
5244 [connection cancel];
5245 //[connection setDelegate:nil];
5246 [connection release];
5251 [[list_ table] setDelegate:nil];
5252 [list_ setDataSource:nil];
5261 //[self _deallocConnection:installer_];
5262 [self _deallocConnection:trivial_gz_];
5263 [self _deallocConnection:trivial_bz2_];
5264 //[self _deallocConnection:automatic_];
5271 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5272 return offset_ == 0 ? 1 : 2;
5275 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5276 switch (section + (offset_ == 0 ? 1 : 0)) {
5277 case 0: return CYLocalize("ENTERED_BY_USER");
5278 case 1: return CYLocalize("INSTALLED_BY_PACKAGE");
5286 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5287 switch (section + (offset_ == 0 ? 1 : 0)) {
5289 case 1: return offset_;
5297 - (int) numberOfRowsInTable:(UITable *)table {
5298 return [sources_ count];
5301 - (float) table:(UITable *)table heightForRow:(int)row {
5302 Source *source = [sources_ objectAtIndex:row];
5303 return [source description] == nil ? 56 : 73;
5306 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5307 Source *source = [sources_ objectAtIndex:row];
5308 // XXX: weird warning, stupid selectors ;P
5309 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5312 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5316 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5320 - (void) tableRowSelected:(NSNotification*)notification {
5321 UITable *table([list_ table]);
5322 int row([table selectedRow]);
5326 Source *source = [sources_ objectAtIndex:row];
5328 PackageTable *packages = [[[FilteredPackageTable alloc]
5331 title:[source label]
5332 filter:@selector(isVisibleInSource:)
5336 [packages setDelegate:delegate_];
5338 [book_ pushPage:packages];
5341 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5342 Source *source = [sources_ objectAtIndex:row];
5343 return [source record] != nil;
5346 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5347 [[list_ table] setDeleteConfirmationRow:row];
5350 - (void) table:(UITable *)table deleteRow:(int)row {
5351 Source *source = [sources_ objectAtIndex:row];
5352 [Sources_ removeObjectForKey:[source key]];
5353 [delegate_ syncData];
5357 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5360 @"./", @"Distribution",
5361 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5363 [delegate_ syncData];
5366 - (NSString *) getWarning {
5367 NSString *href(href_);
5368 NSRange colon([href rangeOfString:@"://"]);
5369 if (colon.location != NSNotFound)
5370 href = [href substringFromIndex:(colon.location + 3)];
5371 href = [href stringByAddingPercentEscapes];
5372 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5373 href = [href stringByCachingURLWithCurrentCDN];
5375 NSURL *url([NSURL URLWithString:href]);
5377 NSStringEncoding encoding;
5378 NSError *error(nil);
5380 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5381 return [warning length] == 0 ? nil : warning;
5385 - (void) _endConnection:(NSURLConnection *)connection {
5386 NSURLConnection **field = NULL;
5387 if (connection == trivial_bz2_)
5388 field = &trivial_bz2_;
5389 else if (connection == trivial_gz_)
5390 field = &trivial_gz_;
5391 _assert(field != NULL);
5392 [connection release];
5396 trivial_bz2_ == nil &&
5402 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5405 UIActionSheet *sheet = [[[UIActionSheet alloc]
5406 initWithTitle:CYLocalize("SOURCE_WARNING")
5407 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_ANYWAY"), CYLocalize("CANCEL"), nil]
5408 defaultButtonIndex:0
5413 [sheet setNumberOfRows:1];
5415 [sheet setBodyText:warning];
5416 [sheet popupAlertAnimated:YES];
5419 } else if (error_ != nil) {
5420 UIActionSheet *sheet = [[[UIActionSheet alloc]
5421 initWithTitle:CYLocalize("VERIFICATION_ERROR")
5422 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5423 defaultButtonIndex:0
5428 [sheet setBodyText:[error_ localizedDescription]];
5429 [sheet popupAlertAnimated:YES];
5431 UIActionSheet *sheet = [[[UIActionSheet alloc]
5432 initWithTitle:CYLocalize("NOT_REPOSITORY")
5433 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5434 defaultButtonIndex:0
5439 [sheet setBodyText:CYLocalize("NOT_REPOSITORY_EX")];
5440 [sheet popupAlertAnimated:YES];
5443 [delegate_ setStatusBarShowsProgress:NO];
5444 [delegate_ removeProgressHUD:hud_];
5454 if (error_ != nil) {
5461 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5462 switch ([response statusCode]) {
5468 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5469 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5471 error_ = [error retain];
5472 [self _endConnection:connection];
5475 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5476 [self _endConnection:connection];
5479 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5480 NSMutableURLRequest *request = [NSMutableURLRequest
5481 requestWithURL:[NSURL URLWithString:href]
5482 cachePolicy:NSURLRequestUseProtocolCachePolicy
5483 timeoutInterval:20.0
5486 [request setHTTPMethod:method];
5488 if (Machine_ != NULL)
5489 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5490 if (UniqueID_ != nil)
5491 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5494 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5496 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5499 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5500 NSString *context([sheet context]);
5502 if ([context isEqualToString:@"source"]) {
5505 NSString *href = [[sheet textField] text];
5507 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5509 if (![href hasSuffix:@"/"])
5510 href_ = [href stringByAppendingString:@"/"];
5513 href_ = [href_ retain];
5515 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5516 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5517 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5521 hud_ = [[delegate_ addProgressHUD] retain];
5522 [hud_ setText:CYLocalize("VERIFYING_URL")];
5533 } else if ([context isEqualToString:@"trivial"])
5535 else if ([context isEqualToString:@"urlerror"])
5537 else if ([context isEqualToString:@"warning"]) {
5557 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5558 if ((self = [super initWithBook:book]) != nil) {
5559 database_ = database;
5560 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5562 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5563 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5564 [list_ setShouldHideHeaderInShortLists:NO];
5566 [self addSubview:list_];
5567 [list_ setDataSource:self];
5569 UITableColumn *column = [[UITableColumn alloc]
5570 initWithTitle:CYLocalize("NAME")
5572 width:[self frame].size.width
5575 UITable *table = [list_ table];
5576 [table setSeparatorStyle:1];
5577 [table addTableColumn:column];
5578 [table setDelegate:self];
5582 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5583 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5587 - (void) reloadData {
5589 _assert(list.ReadMainList());
5591 [sources_ removeAllObjects];
5592 [sources_ addObjectsFromArray:[database_ sources]];
5594 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5597 int count = [sources_ count];
5598 for (offset_ = 0; offset_ != count; ++offset_) {
5599 Source *source = [sources_ objectAtIndex:offset_];
5600 if ([source record] == nil)
5607 - (void) resetViewAnimated:(BOOL)animated {
5608 [list_ resetViewAnimated:animated];
5611 - (void) _leftButtonClicked {
5612 /*[book_ pushPage:[[[AddSourceView alloc]
5617 UIActionSheet *sheet = [[[UIActionSheet alloc]
5618 initWithTitle:CYLocalize("ENTER_APT_URL")
5619 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_SOURCE"), CYLocalize("CANCEL"), nil]
5620 defaultButtonIndex:0
5625 [sheet setNumberOfRows:1];
5627 [sheet addTextFieldWithValue:@"http://" label:@""];
5629 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5630 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5631 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5632 [traits setKeyboardType:UIKeyboardTypeURL];
5633 // XXX: UIReturnKeyDone
5634 [traits setReturnKeyType:UIReturnKeyNext];
5636 [sheet popupAlertAnimated:YES];
5639 - (void) _rightButtonClicked {
5640 UITable *table = [list_ table];
5641 BOOL editing = [table isRowDeletionEnabled];
5642 [table enableRowDeletion:!editing animated:YES];
5643 [book_ reloadButtonsForPage:self];
5646 - (NSString *) title {
5647 return CYLocalize("SOURCES");
5650 - (NSString *) leftButtonTitle {
5651 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("ADD") : nil;
5654 - (id) rightButtonTitle {
5655 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("DONE") : CYLocalize("EDIT");
5658 - (UINavigationButtonStyle) rightButtonStyle {
5659 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5665 /* Installed View {{{ */
5666 @interface InstalledView : RVPage {
5667 _transient Database *database_;
5668 FilteredPackageTable *packages_;
5672 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5676 @implementation InstalledView
5679 [packages_ release];
5683 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5684 if ((self = [super initWithBook:book]) != nil) {
5685 database_ = database;
5687 packages_ = [[FilteredPackageTable alloc]
5691 filter:@selector(isInstalledAndVisible:)
5692 with:[NSNumber numberWithBool:YES]
5695 [self addSubview:packages_];
5697 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5698 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5702 - (void) resetViewAnimated:(BOOL)animated {
5703 [packages_ resetViewAnimated:animated];
5706 - (void) reloadData {
5707 [packages_ reloadData];
5710 - (void) _rightButtonClicked {
5711 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5712 [packages_ reloadData];
5714 [book_ reloadButtonsForPage:self];
5717 - (NSString *) title {
5718 return CYLocalize("INSTALLED");
5721 - (NSString *) backButtonTitle {
5722 return CYLocalize("PACKAGES");
5725 - (id) rightButtonTitle {
5726 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? CYLocalize("EXPERT") : CYLocalize("SIMPLE");
5729 - (UINavigationButtonStyle) rightButtonStyle {
5730 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5733 - (void) setDelegate:(id)delegate {
5734 [super setDelegate:delegate];
5735 [packages_ setDelegate:delegate];
5742 @interface HomeView : BrowserView {
5747 @implementation HomeView
5749 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5750 NSString *context([sheet context]);
5752 if ([context isEqualToString:@"about"])
5755 [super alertSheet:sheet buttonClicked:button];
5758 - (void) _leftButtonClicked {
5759 UIActionSheet *sheet = [[[UIActionSheet alloc]
5760 initWithTitle:CYLocalize("ABOUT_CYDIA")
5761 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
5762 defaultButtonIndex:0
5768 @"Copyright (C) 2008-2009\n"
5769 "Jay Freeman (saurik)\n"
5770 "saurik@saurik.com\n"
5771 "http://www.saurik.com/\n"
5774 "http://www.theokorigroup.com/\n"
5776 "College of Creative Studies,\n"
5777 "University of California,\n"
5779 "http://www.ccs.ucsb.edu/"
5782 [sheet popupAlertAnimated:YES];
5785 - (NSString *) leftButtonTitle {
5786 return CYLocalize("ABOUT");
5791 /* Manage View {{{ */
5792 @interface ManageView : BrowserView {
5797 @implementation ManageView
5799 - (NSString *) title {
5800 return CYLocalize("MANAGE");
5803 - (void) _leftButtonClicked {
5804 [delegate_ askForSettings];
5807 - (NSString *) leftButtonTitle {
5808 return CYLocalize("SETTINGS");
5812 - (id) _rightButtonTitle {
5813 return Queuing_ ? CYLocalize("QUEUE") : nil;
5816 - (UINavigationButtonStyle) rightButtonStyle {
5817 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5820 - (void) _rightButtonClicked {
5825 - (bool) isLoading {
5832 #include <BrowserView.m>
5834 /* Cydia Book {{{ */
5835 @interface CYBook : RVBook <
5838 _transient Database *database_;
5839 UINavigationBar *overlay_;
5840 UINavigationBar *underlay_;
5841 UIProgressIndicator *indicator_;
5842 UITextLabel *prompt_;
5843 UIProgressBar *progress_;
5844 UINavigationButton *cancel_;
5848 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
5854 @implementation CYBook
5858 [indicator_ release];
5860 [progress_ release];
5865 - (NSString *) getTitleForPage:(RVPage *)page {
5866 return [super getTitleForPage:page];
5874 [UIView beginAnimations:nil context:NULL];
5876 CGRect ovrframe = [overlay_ frame];
5877 ovrframe.origin.y = 0;
5878 [overlay_ setFrame:ovrframe];
5880 CGRect barframe = [navbar_ frame];
5881 barframe.origin.y += ovrframe.size.height;
5882 [navbar_ setFrame:barframe];
5884 CGRect trnframe = [transition_ frame];
5885 trnframe.origin.y += ovrframe.size.height;
5886 trnframe.size.height -= ovrframe.size.height;
5887 [transition_ setFrame:trnframe];
5889 [UIView endAnimations];
5891 [indicator_ startAnimation];
5892 [prompt_ setText:CYLocalize("UPDATING_DATABASE")];
5893 [progress_ setProgress:0];
5896 [overlay_ addSubview:cancel_];
5899 detachNewThreadSelector:@selector(_update)
5908 [indicator_ stopAnimation];
5910 [UIView beginAnimations:nil context:NULL];
5912 CGRect ovrframe = [overlay_ frame];
5913 ovrframe.origin.y = -ovrframe.size.height;
5914 [overlay_ setFrame:ovrframe];
5916 CGRect barframe = [navbar_ frame];
5917 barframe.origin.y -= ovrframe.size.height;
5918 [navbar_ setFrame:barframe];
5920 CGRect trnframe = [transition_ frame];
5921 trnframe.origin.y -= ovrframe.size.height;
5922 trnframe.size.height += ovrframe.size.height;
5923 [transition_ setFrame:trnframe];
5925 [UIView commitAnimations];
5927 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
5930 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
5931 if ((self = [super initWithFrame:frame]) != nil) {
5932 database_ = database;
5934 CGRect ovrrect = [navbar_ bounds];
5935 ovrrect.size.height = [UINavigationBar defaultSize].height;
5936 ovrrect.origin.y = -ovrrect.size.height;
5938 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5939 [self addSubview:overlay_];
5941 ovrrect.origin.y = frame.size.height;
5942 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5943 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
5944 [self addSubview:underlay_];
5946 [overlay_ setBarStyle:1];
5947 [underlay_ setBarStyle:1];
5949 int barstyle = [overlay_ _barStyle:NO];
5950 bool ugly = barstyle == 0;
5952 UIProgressIndicatorStyle style = ugly ?
5953 UIProgressIndicatorStyleMediumBrown :
5954 UIProgressIndicatorStyleMediumWhite;
5956 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
5957 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
5958 CGRect indrect = {{indoffset, indoffset}, indsize};
5960 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
5961 [indicator_ setStyle:style];
5962 [overlay_ addSubview:indicator_];
5964 CGSize prmsize = {215, indsize.height + 4};
5967 indoffset * 2 + indsize.width,
5971 unsigned(ovrrect.size.height - prmsize.height) / 2
5974 UIFont *font = [UIFont systemFontOfSize:15];
5976 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
5978 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
5979 [prompt_ setBackgroundColor:[UIColor clearColor]];
5980 [prompt_ setFont:font];
5982 [overlay_ addSubview:prompt_];
5984 CGSize prgsize = {75, 100};
5987 ovrrect.size.width - prgsize.width - 10,
5988 (ovrrect.size.height - prgsize.height) / 2
5991 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
5992 [progress_ setStyle:0];
5993 [overlay_ addSubview:progress_];
5995 cancel_ = [[UINavigationButton alloc] initWithTitle:CYLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
5996 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
5998 CGRect frame = [cancel_ frame];
5999 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6000 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6001 [cancel_ setFrame:frame];
6003 [cancel_ setBarStyle:barstyle];
6007 - (void) _onCancel {
6009 [cancel_ removeFromSuperview];
6012 - (void) _update { _pooled
6014 status.setDelegate(self);
6016 [database_ updateWithStatus:status];
6019 performSelectorOnMainThread:@selector(_update_)
6025 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
6026 [prompt_ setText:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), error]];
6029 - (void) setProgressTitle:(NSString *)title {
6031 performSelectorOnMainThread:@selector(_setProgressTitle:)
6037 - (void) setProgressPercent:(float)percent {
6039 performSelectorOnMainThread:@selector(_setProgressPercent:)
6040 withObject:[NSNumber numberWithFloat:percent]
6045 - (void) startProgress {
6048 - (void) addProgressOutput:(NSString *)output {
6050 performSelectorOnMainThread:@selector(_addProgressOutput:)
6056 - (bool) isCancelling:(size_t)received {
6060 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6064 - (void) _setProgressTitle:(NSString *)title {
6065 [prompt_ setText:title];
6068 - (void) _setProgressPercent:(NSNumber *)percent {
6069 [progress_ setProgress:[percent floatValue]];
6072 - (void) _addProgressOutput:(NSString *)output {
6077 /* Cydia:// Protocol {{{ */
6078 @interface CydiaURLProtocol : NSURLProtocol {
6083 @implementation CydiaURLProtocol
6085 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6086 NSURL *url([request URL]);
6089 NSString *scheme([[url scheme] lowercaseString]);
6090 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6095 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6099 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6100 id<NSURLProtocolClient> client([self client]);
6102 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6104 NSData *data(UIImagePNGRepresentation(icon));
6106 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6107 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6108 [client URLProtocol:self didLoadData:data];
6109 [client URLProtocolDidFinishLoading:self];
6113 - (void) startLoading {
6114 id<NSURLProtocolClient> client([self client]);
6115 NSURLRequest *request([self request]);
6117 NSURL *url([request URL]);
6118 NSString *href([url absoluteString]);
6120 NSString *path([href substringFromIndex:8]);
6121 NSRange slash([path rangeOfString:@"/"]);
6124 if (slash.location == NSNotFound) {
6128 command = [path substringToIndex:slash.location];
6129 path = [path substringFromIndex:(slash.location + 1)];
6132 Database *database([Database sharedInstance]);
6134 if ([command isEqualToString:@"package-icon"]) {
6137 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6138 Package *package([database packageWithName:path]);
6141 UIImage *icon([package icon]);
6142 [self _returnPNGWithImage:icon forRequest:request];
6143 } else if ([command isEqualToString:@"source-icon"]) {
6146 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6147 NSString *source(Simplify(path));
6148 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6150 icon = [UIImage applicationImageNamed:@"unknown.png"];
6151 [self _returnPNGWithImage:icon forRequest:request];
6152 } else if ([command isEqualToString:@"uikit-image"]) {
6155 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6156 UIImage *icon(_UIImageWithName(path));
6157 [self _returnPNGWithImage:icon forRequest:request];
6158 } else if ([command isEqualToString:@"section-icon"]) {
6161 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6162 NSString *section(Simplify(path));
6163 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6165 icon = [UIImage applicationImageNamed:@"unknown.png"];
6166 [self _returnPNGWithImage:icon forRequest:request];
6168 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6172 - (void) stopLoading {
6178 /* Sections View {{{ */
6179 @interface SectionsView : RVPage {
6180 _transient Database *database_;
6181 NSMutableArray *sections_;
6182 NSMutableArray *filtered_;
6183 UITransitionView *transition_;
6189 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6190 - (void) reloadData;
6195 @implementation SectionsView
6198 [list_ setDataSource:nil];
6199 [list_ setDelegate:nil];
6201 [sections_ release];
6202 [filtered_ release];
6203 [transition_ release];
6205 [accessory_ release];
6209 - (int) numberOfRowsInTable:(UITable *)table {
6210 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6213 - (float) table:(UITable *)table heightForRow:(int)row {
6217 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6219 reusing = [[[SectionCell alloc] init] autorelease];
6220 [(SectionCell *)reusing setSection:(editing_ ?
6221 [sections_ objectAtIndex:row] :
6222 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6223 ) editing:editing_];
6227 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6231 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6235 - (void) tableRowSelected:(NSNotification *)notification {
6236 int row = [[notification object] selectedRow];
6247 title = CYLocalize("ALL_PACKAGES");
6249 section = [filtered_ objectAtIndex:(row - 1)];
6250 name = [section name];
6253 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6256 title = CYLocalize("NO_SECTION");
6260 PackageTable *table = [[[FilteredPackageTable alloc]
6264 filter:@selector(isVisiblyUninstalledInSection:)
6268 [table setDelegate:delegate_];
6270 [book_ pushPage:table];
6273 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6274 if ((self = [super initWithBook:book]) != nil) {
6275 database_ = database;
6277 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6278 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6280 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6281 [self addSubview:transition_];
6283 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6284 [transition_ transition:0 toView:list_];
6286 UITableColumn *column = [[[UITableColumn alloc]
6287 initWithTitle:CYLocalize("NAME")
6289 width:[self frame].size.width
6292 [list_ setDataSource:self];
6293 [list_ setSeparatorStyle:1];
6294 [list_ addTableColumn:column];
6295 [list_ setDelegate:self];
6296 [list_ setReusesTableCells:YES];
6300 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6301 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6305 - (void) reloadData {
6306 NSArray *packages = [database_ packages];
6308 [sections_ removeAllObjects];
6309 [filtered_ removeAllObjects];
6312 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6313 SectionMap sections;
6314 sections.resize(64);
6316 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6320 for (Package *package in packages) {
6321 NSString *name([package section]);
6322 NSString *key(name == nil ? @"" : name);
6327 _profile(SectionsView$reloadData$Section)
6328 section = §ions[key];
6329 if (*section == nil) {
6330 _profile(SectionsView$reloadData$Section$Allocate)
6331 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6336 [*section addToCount];
6338 _profile(SectionsView$reloadData$Filter)
6339 if (![package valid] || [package installed] != nil || ![package visible])
6343 [*section addToRow];
6347 _profile(SectionsView$reloadData$Section)
6348 section = [sections objectForKey:key];
6349 if (section == nil) {
6350 _profile(SectionsView$reloadData$Section$Allocate)
6351 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6352 [sections setObject:section forKey:key];
6357 [section addToCount];
6359 _profile(SectionsView$reloadData$Filter)
6360 if (![package valid] || [package installed] != nil || ![package visible])
6370 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6371 [sections_ addObject:i->second];
6373 [sections_ addObjectsFromArray:[sections allValues]];
6376 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6378 for (Section *section in sections_) {
6379 size_t count([section row]);
6383 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6384 [section setCount:count];
6385 [filtered_ addObject:section];
6392 - (void) resetView {
6394 [self _rightButtonClicked];
6397 - (void) resetViewAnimated:(BOOL)animated {
6398 [list_ resetViewAnimated:animated];
6401 - (void) _rightButtonClicked {
6402 if ((editing_ = !editing_))
6405 [delegate_ updateData];
6406 [book_ reloadTitleForPage:self];
6407 [book_ reloadButtonsForPage:self];
6410 - (NSString *) title {
6411 return editing_ ? CYLocalize("SECTION_VISIBILITY") : CYLocalize("INSTALL_BY_SECTION");
6414 - (NSString *) backButtonTitle {
6415 return CYLocalize("SECTIONS");
6418 - (id) rightButtonTitle {
6419 return [sections_ count] == 0 ? nil : editing_ ? CYLocalize("DONE") : CYLocalize("EDIT");
6422 - (UINavigationButtonStyle) rightButtonStyle {
6423 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6426 - (UIView *) accessoryView {
6432 /* Changes View {{{ */
6433 @interface ChangesView : RVPage {
6434 _transient Database *database_;
6435 NSMutableArray *packages_;
6436 NSMutableArray *sections_;
6437 UISectionList *list_;
6441 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6442 - (void) reloadData;
6446 @implementation ChangesView
6449 [[list_ table] setDelegate:nil];
6450 [list_ setDataSource:nil];
6452 [packages_ release];
6453 [sections_ release];
6458 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6459 return [sections_ count];
6462 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6463 return [[sections_ objectAtIndex:section] name];
6466 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6467 return [[sections_ objectAtIndex:section] row];
6470 - (int) numberOfRowsInTable:(UITable *)table {
6471 return [packages_ count];
6474 - (float) table:(UITable *)table heightForRow:(int)row {
6475 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6478 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6480 reusing = [[[PackageCell alloc] init] autorelease];
6481 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6485 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6489 - (void) tableRowSelected:(NSNotification *)notification {
6490 int row = [[notification object] selectedRow];
6493 Package *package = [packages_ objectAtIndex:row];
6494 PackageView *view([delegate_ packageView]);
6495 [view setDelegate:delegate_];
6496 [view setPackage:package];
6497 [book_ pushPage:view];
6500 - (void) _leftButtonClicked {
6501 [(CYBook *)book_ update];
6502 [self reloadButtons];
6505 - (void) _rightButtonClicked {
6506 [delegate_ distUpgrade];
6509 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6510 if ((self = [super initWithBook:book]) != nil) {
6511 database_ = database;
6513 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6514 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6516 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6517 [self addSubview:list_];
6519 [list_ setShouldHideHeaderInShortLists:NO];
6520 [list_ setDataSource:self];
6521 //[list_ setSectionListStyle:1];
6523 UITableColumn *column = [[[UITableColumn alloc]
6524 initWithTitle:CYLocalize("NAME")
6526 width:[self frame].size.width
6529 UITable *table = [list_ table];
6530 [table setSeparatorStyle:1];
6531 [table addTableColumn:column];
6532 [table setDelegate:self];
6533 [table setReusesTableCells:YES];
6537 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6538 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6542 - (void) reloadData {
6543 NSArray *packages = [database_ packages];
6545 [packages_ removeAllObjects];
6546 [sections_ removeAllObjects];
6549 for (Package *package in packages)
6551 [package installed] == nil && [package valid] && [package visible] ||
6552 [package upgradableAndEssential:YES]
6554 [packages_ addObject:package];
6557 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6560 Section *upgradable = [[[Section alloc] initWithName:CYLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6561 Section *ignored = [[[Section alloc] initWithName:CYLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6562 Section *section = nil;
6566 bool unseens = false;
6568 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6570 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6571 Package *package = [packages_ objectAtIndex:offset];
6573 BOOL uae = [package upgradableAndEssential:YES];
6579 _profile(ChangesView$reloadData$Remember)
6580 seen = [package seen];
6583 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6588 name = CYLocalize("UNKNOWN");
6590 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6594 _profile(ChangesView$reloadData$Allocate)
6595 name = [NSString stringWithFormat:CYLocalize("NEW_AT"), name];
6596 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6597 [sections_ addObject:section];
6601 [section addToCount];
6602 } else if ([package ignored])
6603 [ignored addToCount];
6606 [upgradable addToCount];
6611 CFRelease(formatter);
6614 Section *last = [sections_ lastObject];
6615 size_t count = [last count];
6616 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6617 [sections_ removeLastObject];
6620 if ([ignored count] != 0)
6621 [sections_ insertObject:ignored atIndex:0];
6623 [sections_ insertObject:upgradable atIndex:0];
6626 [self reloadButtons];
6629 - (void) resetViewAnimated:(BOOL)animated {
6630 [list_ resetViewAnimated:animated];
6633 - (NSString *) leftButtonTitle {
6634 return [(CYBook *)book_ updating] ? nil : CYLocalize("REFRESH");
6637 - (id) rightButtonTitle {
6638 return upgrades_ == 0 ? nil : [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6641 - (NSString *) title {
6642 return CYLocalize("CHANGES");
6647 /* Search View {{{ */
6648 @protocol SearchViewDelegate
6649 - (void) showKeyboard:(BOOL)show;
6652 @interface SearchView : RVPage {
6654 UISearchField *field_;
6655 UITransitionView *transition_;
6656 FilteredPackageTable *table_;
6657 UIPreferencesTable *advanced_;
6663 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6664 - (void) reloadData;
6668 @implementation SearchView
6671 [field_ setDelegate:nil];
6673 [accessory_ release];
6675 [transition_ release];
6677 [advanced_ release];
6682 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6686 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6688 case 0: return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("ADVANCED_SEARCH"), CYLocalize("COMING_SOON")];
6690 default: _assert(false);
6694 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6698 default: _assert(false);
6702 - (void) _showKeyboard:(BOOL)show {
6703 CGSize keysize = [UIKeyboard defaultSize];
6704 CGRect keydown = [book_ pageBounds];
6705 CGRect keyup = keydown;
6706 keyup.size.height -= keysize.height - ButtonBarHeight_;
6708 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6710 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6711 [animation setSignificantRectFields:8];
6714 [animation setStartFrame:keydown];
6715 [animation setEndFrame:keyup];
6717 [animation setStartFrame:keyup];
6718 [animation setEndFrame:keydown];
6721 UIAnimator *animator = [UIAnimator sharedAnimator];
6724 addAnimations:[NSArray arrayWithObjects:animation, nil]
6725 withDuration:(KeyboardTime_ - delay)
6730 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6732 [delegate_ showKeyboard:show];
6735 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6736 [self _showKeyboard:YES];
6739 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
6740 [self _showKeyboard:NO];
6743 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
6745 NSString *text([field_ text]);
6746 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6752 - (void) textFieldClearButtonPressed:(UITextField *)field {
6756 - (void) keyboardInputShouldDelete:(id)input {
6760 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
6761 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6765 [field_ resignFirstResponder];
6770 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6771 if ((self = [super initWithBook:book]) != nil) {
6772 CGRect pageBounds = [book_ pageBounds];
6774 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6775 [self addSubview:transition_];
6777 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6779 [advanced_ setReusesTableCells:YES];
6780 [advanced_ setDataSource:self];
6781 [advanced_ reloadData];
6783 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6784 CGColor dimmed(space_, 0, 0, 0, 0.5);
6785 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
6787 table_ = [[FilteredPackageTable alloc]
6791 filter:@selector(isUnfilteredAndSearchedForBy:)
6795 [table_ setShouldHideHeaderInShortLists:NO];
6796 [transition_ transition:0 toView:table_];
6805 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
6812 [self bounds].size.width - area.origin.x - 18;
6814 area.size.height = [UISearchField defaultHeight];
6816 field_ = [[UISearchField alloc] initWithFrame:area];
6818 UIFont *font = [UIFont systemFontOfSize:16];
6819 [field_ setFont:font];
6821 [field_ setPlaceholder:CYLocalize("SEARCH_EX")];
6822 [field_ setDelegate:self];
6824 [field_ setPaddingTop:5];
6826 UITextInputTraits *traits([field_ textInputTraits]);
6827 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6828 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6829 [traits setReturnKeyType:UIReturnKeySearch];
6831 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
6833 accessory_ = [[UIView alloc] initWithFrame:accrect];
6834 [accessory_ addSubview:field_];
6836 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
6837 [configure setShowPressFeedback:YES];
6838 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
6839 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
6840 [accessory_ addSubview:configure];*/
6842 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6843 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6849 LKAnimation *animation = [LKTransition animation];
6850 [animation setType:@"oglFlip"];
6851 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
6852 [animation setFillMode:@"extended"];
6853 [animation setTransitionFlags:3];
6854 [animation setDuration:10];
6855 [animation setSpeed:0.35];
6856 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
6857 [[transition_ _layer] addAnimation:animation forKey:0];
6858 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
6859 flipped_ = !flipped_;
6863 - (void) configurePushed {
6864 [field_ resignFirstResponder];
6868 - (void) resetViewAnimated:(BOOL)animated {
6871 [table_ resetViewAnimated:animated];
6874 - (void) _reloadData {
6877 - (void) reloadData {
6880 [table_ setObject:[field_ text]];
6881 _profile(SearchView$reloadData)
6882 [table_ reloadData];
6885 [table_ resetCursor];
6888 - (UIView *) accessoryView {
6892 - (NSString *) title {
6896 - (NSString *) backButtonTitle {
6897 return CYLocalize("SEARCH");
6900 - (void) setDelegate:(id)delegate {
6901 [table_ setDelegate:delegate];
6902 [super setDelegate:delegate];
6908 @interface SettingsView : RVPage {
6909 _transient Database *database_;
6912 UIPreferencesTable *table_;
6913 _UISwitchSlider *subscribedSwitch_;
6914 _UISwitchSlider *ignoredSwitch_;
6915 UIPreferencesControlTableCell *subscribedCell_;
6916 UIPreferencesControlTableCell *ignoredCell_;
6919 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6923 @implementation SettingsView
6926 [table_ setDataSource:nil];
6929 if (package_ != nil)
6932 [subscribedSwitch_ release];
6933 [ignoredSwitch_ release];
6934 [subscribedCell_ release];
6935 [ignoredCell_ release];
6939 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6940 if (package_ == nil)
6946 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6947 if (package_ == nil)
6954 default: _assert(false);
6960 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
6961 if (package_ == nil)
6968 default: _assert(false);
6974 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6975 if (package_ == nil)
6982 default: _assert(false);
6988 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
6989 if (package_ == nil)
6992 _UISwitchSlider *slider([cell control]);
6993 BOOL value([slider value] != 0);
6994 NSMutableDictionary *metadata([package_ metadata]);
6997 if (NSNumber *number = [metadata objectForKey:key])
6998 before = [number boolValue];
7002 if (value != before) {
7003 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7005 [delegate_ updateData];
7009 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7010 [self onSomething:cell withKey:@"IsSubscribed"];
7013 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7014 [self onSomething:cell withKey:@"IsIgnored"];
7017 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7018 if (package_ == nil)
7022 case 0: switch (row) {
7024 return subscribedCell_;
7026 return ignoredCell_;
7027 default: _assert(false);
7030 case 1: switch (row) {
7032 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7033 [cell setShowSelection:NO];
7034 [cell setTitle:CYLocalize("SHOW_ALL_CHANGES_EX")];
7038 default: _assert(false);
7041 default: _assert(false);
7047 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7048 if ((self = [super initWithBook:book])) {
7049 database_ = database;
7050 name_ = [package retain];
7052 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7053 [self addSubview:table_];
7055 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7056 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
7058 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7059 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
7061 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7062 [subscribedCell_ setShowSelection:NO];
7063 [subscribedCell_ setTitle:CYLocalize("SHOW_ALL_CHANGES")];
7064 [subscribedCell_ setControl:subscribedSwitch_];
7066 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7067 [ignoredCell_ setShowSelection:NO];
7068 [ignoredCell_ setTitle:CYLocalize("IGNORE_UPGRADES")];
7069 [ignoredCell_ setControl:ignoredSwitch_];
7071 [table_ setDataSource:self];
7076 - (void) resetViewAnimated:(BOOL)animated {
7077 [table_ resetViewAnimated:animated];
7080 - (void) reloadData {
7081 if (package_ != nil)
7082 [package_ autorelease];
7083 package_ = [database_ packageWithName:name_];
7084 if (package_ != nil) {
7086 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7087 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7090 [table_ reloadData];
7093 - (NSString *) title {
7094 return CYLocalize("SETTINGS");
7099 /* Signature View {{{ */
7100 @interface SignatureView : BrowserView {
7101 _transient Database *database_;
7105 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7109 @implementation SignatureView
7116 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7118 [super webView:sender didClearWindowObject:window forFrame:frame];
7121 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7122 if ((self = [super initWithBook:book]) != nil) {
7123 database_ = database;
7124 package_ = [package retain];
7129 - (void) resetViewAnimated:(BOOL)animated {
7132 - (void) reloadData {
7133 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7139 @interface Cydia : UIApplication <
7140 ConfirmationViewDelegate,
7141 ProgressViewDelegate,
7150 UIToolbar *buttonbar_;
7154 NSMutableArray *essential_;
7155 NSMutableArray *broken_;
7157 Database *database_;
7158 ProgressView *progress_;
7162 UIKeyboard *keyboard_;
7163 UIProgressHUD *hud_;
7165 SectionsView *sections_;
7166 ChangesView *changes_;
7167 ManageView *manage_;
7168 SearchView *search_;
7170 PackageView *package_;
7175 @implementation Cydia
7178 if ([broken_ count] != 0) {
7179 int count = [broken_ count];
7181 UIActionSheet *sheet = [[[UIActionSheet alloc]
7182 initWithTitle:(count == 1 ? CYLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:CYLocalize("HALFINSTALLED_PACKAGES"), count])
7183 buttons:[NSArray arrayWithObjects:
7184 CYLocalize("FORCIBLY_CLEAR"),
7185 CYLocalize("TEMPORARY_IGNORE"),
7187 defaultButtonIndex:0
7192 [sheet setBodyText:CYLocalize("HALFINSTALLED_PACKAGE_EX")];
7193 [sheet popupAlertAnimated:YES];
7194 } else if (!Ignored_ && [essential_ count] != 0) {
7195 int count = [essential_ count];
7197 UIActionSheet *sheet = [[[UIActionSheet alloc]
7198 initWithTitle:(count == 1 ? CYLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:CYLocalize("ESSENTIAL_UPGRADES"), count])
7199 buttons:[NSArray arrayWithObjects:
7200 CYLocalize("UPGRADE_ESSENTIAL"),
7201 CYLocalize("COMPLETE_UPGRADE"),
7202 CYLocalize("TEMPORARY_IGNORE"),
7204 defaultButtonIndex:0
7209 [sheet setBodyText:CYLocalize("ESSENTIAL_UPGRADE_EX")];
7210 [sheet popupAlertAnimated:YES];
7214 - (void) _reloadData {
7217 static bool loaded(false);
7218 UIProgressHUD *hud([self addProgressHUD]);
7219 [hud setText:(loaded ? CYLocalize("RELOADING_DATA") : CYLocalize("LOADING_DATA"))];
7222 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7225 [self removeProgressHUD:hud];
7229 [essential_ removeAllObjects];
7230 [broken_ removeAllObjects];
7232 NSArray *packages = [database_ packages];
7233 for (Package *package in packages) {
7235 [broken_ addObject:package];
7236 if ([package upgradableAndEssential:NO]) {
7237 if ([package essential])
7238 [essential_ addObject:package];
7244 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7245 [buttonbar_ setBadgeValue:badge forButton:3];
7246 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7247 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7248 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7249 [self setApplicationBadge:badge];
7251 [self setApplicationBadgeString:badge];
7253 [buttonbar_ setBadgeValue:nil forButton:3];
7254 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7255 [buttonbar_ setBadgeAnimated:NO forButton:3];
7256 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7257 [self removeApplicationBadge];
7258 else // XXX: maybe use setApplicationBadgeString also?
7259 [self setApplicationIconBadgeNumber:0];
7263 [buttonbar_ setBadgeValue:nil forButton:4];
7267 // XXX: what is this line of code for?
7268 if ([packages count] == 0);
7269 else if (Loaded_ || ManualRefresh) loaded:
7274 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7275 NSTimeInterval interval([update timeIntervalSinceNow]);
7276 if (interval <= 0 && interval > -600)
7284 - (void) _saveConfig {
7287 NSString *error(nil);
7288 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7290 NSError *error(nil);
7291 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7292 NSLog(@"failure to save metadata data: %@", error);
7295 NSLog(@"failure to serialize metadata: %@", error);
7303 - (void) updateData {
7306 /* XXX: this is just stupid */
7307 if (tag_ != 2 && sections_ != nil)
7308 [sections_ reloadData];
7309 if (tag_ != 3 && changes_ != nil)
7310 [changes_ reloadData];
7311 if (tag_ != 5 && search_ != nil)
7312 [search_ reloadData];
7322 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7323 _assert(file != NULL);
7325 NSArray *keys = [Sources_ allKeys];
7327 for (NSString *key in keys) {
7328 NSDictionary *source = [Sources_ objectForKey:key];
7330 fprintf(file, "%s %s %s\n",
7331 [[source objectForKey:@"Type"] UTF8String],
7332 [[source objectForKey:@"URI"] UTF8String],
7333 [[source objectForKey:@"Distribution"] UTF8String]
7342 detachNewThreadSelector:@selector(update_)
7345 title:CYLocalize("UPDATING_SOURCES")
7349 - (void) reloadData {
7350 @synchronized (self) {
7351 if (confirm_ == nil)
7357 pkgProblemResolver *resolver = [database_ resolver];
7359 resolver->InstallProtect();
7360 if (!resolver->Resolve(true))
7364 - (void) popUpBook:(RVBook *)book {
7365 [underlay_ popSubview:book];
7368 - (CGRect) popUpBounds {
7369 return [underlay_ bounds];
7373 [database_ prepare];
7375 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7376 [confirm_ setDelegate:self];
7378 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7379 [page setDelegate:self];
7381 [confirm_ setPage:page];
7382 [self popUpBook:confirm_];
7386 @synchronized (self) {
7391 - (void) clearPackage:(Package *)package {
7392 @synchronized (self) {
7399 - (void) installPackage:(Package *)package {
7400 @synchronized (self) {
7407 - (void) removePackage:(Package *)package {
7408 @synchronized (self) {
7415 - (void) distUpgrade {
7416 @synchronized (self) {
7417 [database_ upgrade];
7423 [self slideUp:[[[UIActionSheet alloc]
7425 buttons:[NSArray arrayWithObjects:CYLocalize("CONTINUE_QUEUING"), CYLocalize("CANCEL_CLEAR"), nil]
7426 defaultButtonIndex:1
7433 @synchronized (self) {
7436 if (confirm_ != nil) {
7444 [overlay_ removeFromSuperview];
7448 detachNewThreadSelector:@selector(perform)
7451 title:CYLocalize("RUNNING")
7455 - (void) bootstrap_ {
7457 [database_ upgrade];
7458 [database_ prepare];
7459 [database_ perform];
7462 /* XXX: replace and localize */
7463 - (void) bootstrap {
7465 detachNewThreadSelector:@selector(bootstrap_)
7468 title:@"Bootstrap Install"
7472 - (void) progressViewIsComplete:(ProgressView *)progress {
7473 if (confirm_ != nil) {
7474 [underlay_ addSubview:overlay_];
7475 [confirm_ popFromSuperviewAnimated:NO];
7481 - (void) setPage:(RVPage *)page {
7482 [page resetViewAnimated:NO];
7483 [page setDelegate:self];
7484 [book_ setPage:page];
7487 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7488 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7489 [browser loadURL:url];
7493 - (void) _setHomePage {
7494 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7497 - (SectionsView *) sectionsView {
7498 if (sections_ == nil)
7499 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7503 - (void) buttonBarItemTapped:(id)sender {
7504 unsigned tag = [sender tag];
7506 [book_ resetViewAnimated:YES];
7508 } else if (tag_ == 2 && tag != 2)
7509 [[self sectionsView] resetView];
7512 case 1: [self _setHomePage]; break;
7514 case 2: [self setPage:[self sectionsView]]; break;
7515 case 3: [self setPage:changes_]; break;
7516 case 4: [self setPage:manage_]; break;
7517 case 5: [self setPage:search_]; break;
7519 default: _assert(false);
7525 - (void) applicationWillSuspend {
7527 [super applicationWillSuspend];
7530 - (void) askForSettings {
7531 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
7533 UIActionSheet *role = [[[UIActionSheet alloc]
7534 initWithTitle:CYLocalize("WHO_ARE_YOU")
7535 buttons:[NSArray arrayWithObjects:
7536 [NSString stringWithFormat:parenthetical, CYLocalize("USER"), CYLocalize("USER_EX")],
7537 [NSString stringWithFormat:parenthetical, CYLocalize("HACKER"), CYLocalize("HACKER_EX")],
7538 [NSString stringWithFormat:parenthetical, CYLocalize("DEVELOPER"), CYLocalize("DEVELOPER_EX")],
7540 defaultButtonIndex:-1
7545 [role setBodyText:CYLocalize("ROLE_EX")];
7546 [role popupAlertAnimated:YES];
7549 - (void) setPackageView:(PackageView *)view {
7550 if (package_ == nil)
7551 package_ = [view retain];
7554 - (PackageView *) packageView {
7557 if (package_ == nil)
7558 view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7561 view = [package_ autorelease];
7570 [self setStatusBarShowsProgress:NO];
7571 [self removeProgressHUD:hud_];
7576 pid_t pid = ExecFork();
7578 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7579 perror("launchctl stop");
7586 [self askForSettings];
7591 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7593 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7594 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7595 0, 0, screenrect.size.width, screenrect.size.height - 48
7596 ) database:database_];
7598 [book_ setDelegate:self];
7600 [overlay_ addSubview:book_];
7602 NSArray *buttonitems = [NSArray arrayWithObjects:
7603 [NSDictionary dictionaryWithObjectsAndKeys:
7604 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7605 @"home-up.png", kUIButtonBarButtonInfo,
7606 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7607 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7608 self, kUIButtonBarButtonTarget,
7609 @"Cydia", kUIButtonBarButtonTitle,
7610 @"0", kUIButtonBarButtonType,
7613 [NSDictionary dictionaryWithObjectsAndKeys:
7614 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7615 @"install-up.png", kUIButtonBarButtonInfo,
7616 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7617 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7618 self, kUIButtonBarButtonTarget,
7619 CYLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7620 @"0", kUIButtonBarButtonType,
7623 [NSDictionary dictionaryWithObjectsAndKeys:
7624 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7625 @"changes-up.png", kUIButtonBarButtonInfo,
7626 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7627 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7628 self, kUIButtonBarButtonTarget,
7629 CYLocalize("CHANGES"), kUIButtonBarButtonTitle,
7630 @"0", kUIButtonBarButtonType,
7633 [NSDictionary dictionaryWithObjectsAndKeys:
7634 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7635 @"manage-up.png", kUIButtonBarButtonInfo,
7636 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7637 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7638 self, kUIButtonBarButtonTarget,
7639 CYLocalize("MANAGE"), kUIButtonBarButtonTitle,
7640 @"0", kUIButtonBarButtonType,
7643 [NSDictionary dictionaryWithObjectsAndKeys:
7644 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7645 @"search-up.png", kUIButtonBarButtonInfo,
7646 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7647 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7648 self, kUIButtonBarButtonTarget,
7649 CYLocalize("SEARCH"), kUIButtonBarButtonTitle,
7650 @"0", kUIButtonBarButtonType,
7654 buttonbar_ = [[UIToolbar alloc]
7656 withFrame:CGRectMake(
7657 0, screenrect.size.height - ButtonBarHeight_,
7658 screenrect.size.width, ButtonBarHeight_
7660 withItemList:buttonitems
7663 [buttonbar_ setDelegate:self];
7664 [buttonbar_ setBarStyle:1];
7665 [buttonbar_ setButtonBarTrackingMode:2];
7667 int buttons[5] = {1, 2, 3, 4, 5};
7668 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7669 [buttonbar_ showButtonGroup:0 withDuration:0];
7671 for (int i = 0; i != 5; ++i)
7672 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7673 i * 64 + 2, 1, 60, ButtonBarHeight_
7676 [buttonbar_ showSelectionForButton:1];
7677 [overlay_ addSubview:buttonbar_];
7679 [UIKeyboard initImplementationNow];
7680 CGSize keysize = [UIKeyboard defaultSize];
7681 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7682 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7683 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
7684 [overlay_ addSubview:keyboard_];
7687 [underlay_ addSubview:overlay_];
7691 [self sectionsView];
7692 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7693 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7695 manage_ = (ManageView *) [[self
7696 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7697 withClass:[ManageView class]
7700 [self setPackageView:[self packageView]];
7707 [self _setHomePage];
7710 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7711 NSString *context([sheet context]);
7713 if ([context isEqualToString:@"missing"])
7715 else if ([context isEqualToString:@"cancel"]) {
7733 @synchronized (self) {
7738 [buttonbar_ setBadgeValue:CYLocalize("Q_D") forButton:4];
7742 if (confirm_ != nil) {
7747 } else if ([context isEqualToString:@"fixhalf"]) {
7750 @synchronized (self) {
7751 for (Package *broken in broken_) {
7754 NSString *id = [broken id];
7755 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7756 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7757 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7758 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7767 [broken_ removeAllObjects];
7776 } else if ([context isEqualToString:@"role"]) {
7778 case 1: Role_ = @"User"; break;
7779 case 2: Role_ = @"Hacker"; break;
7780 case 3: Role_ = @"Developer"; break;
7787 bool reset = Settings_ != nil;
7789 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7793 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7803 } else if ([context isEqualToString:@"upgrade"]) {
7806 @synchronized (self) {
7807 for (Package *essential in essential_)
7808 [essential install];
7831 - (void) reorganize { _pooled
7832 system("/usr/libexec/cydia/free.sh");
7833 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
7836 - (void) applicationSuspend:(__GSEvent *)event {
7837 if (hud_ == nil && ![progress_ isRunning])
7838 [super applicationSuspend:event];
7841 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7843 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7846 - (void) _setSuspended:(BOOL)value {
7848 [super _setSuspended:value];
7851 - (UIProgressHUD *) addProgressHUD {
7852 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
7853 [window_ setUserInteractionEnabled:NO];
7855 [progress_ addSubview:hud];
7859 - (void) removeProgressHUD:(UIProgressHUD *)hud {
7861 [hud removeFromSuperview];
7862 [window_ setUserInteractionEnabled:YES];
7865 - (void) openMailToURL:(NSURL *)url {
7866 // XXX: this makes me sad
7868 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
7870 [UIApp openURL:url];// asPanel:YES];
7874 - (void) clearFirstResponder {
7875 if (id responder = [window_ firstResponder])
7876 [responder resignFirstResponder];
7879 - (RVPage *) pageForPackage:(NSString *)name {
7880 if (Package *package = [database_ packageWithName:name]) {
7881 PackageView *view([self packageView]);
7882 [view setPackage:package];
7885 UIActionSheet *sheet = [[[UIActionSheet alloc]
7886 initWithTitle:CYLocalize("CANNOT_LOCATE_PACKAGE")
7887 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
7888 defaultButtonIndex:0
7893 [sheet setBodyText:[NSString stringWithFormat:CYLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
7895 [sheet popupAlertAnimated:YES];
7900 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
7904 NSString *scheme([[url scheme] lowercaseString]);
7905 if (![scheme isEqualToString:@"cydia"])
7907 NSString *path([url absoluteString]);
7908 if ([path length] < 8)
7910 path = [path substringFromIndex:8];
7911 if (![path hasPrefix:@"/"])
7912 path = [@"/" stringByAppendingString:path];
7914 if ([path isEqualToString:@"/add-source"])
7915 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
7916 else if ([path isEqualToString:@"/storage"])
7917 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[BrowserView class]];
7918 else if ([path isEqualToString:@"/sources"])
7919 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
7920 else if ([path isEqualToString:@"/packages"])
7921 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
7922 else if ([path hasPrefix:@"/url/"])
7923 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[BrowserView class]];
7924 else if ([path hasPrefix:@"/launch/"])
7925 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
7926 else if ([path hasPrefix:@"/package-settings/"])
7927 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
7928 else if ([path hasPrefix:@"/package-signature/"])
7929 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
7930 else if ([path hasPrefix:@"/package/"])
7931 return [self pageForPackage:[path substringFromIndex:9]];
7932 else if ([path hasPrefix:@"/files/"]) {
7933 NSString *name = [path substringFromIndex:7];
7935 if (Package *package = [database_ packageWithName:name]) {
7936 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
7937 [files setPackage:package];
7945 - (void) applicationOpenURL:(NSURL *)url {
7946 [super applicationOpenURL:url];
7948 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
7949 [self setPage:page];
7950 [buttonbar_ showSelectionForButton:tag];
7955 - (void) applicationDidFinishLaunching:(id)unused {
7957 Font12_ = [[UIFont systemFontOfSize:12] retain];
7958 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
7959 Font14_ = [[UIFont systemFontOfSize:14] retain];
7960 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
7961 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
7965 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
7966 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
7968 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
7970 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7971 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
7973 [window_ orderFront:self];
7974 [window_ makeKey:self];
7975 [window_ setHidden:NO];
7977 database_ = [Database sharedInstance];
7978 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
7979 [database_ setDelegate:progress_];
7980 [window_ setContentView:progress_];
7982 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
7983 [progress_ setContentView:underlay_];
7985 [progress_ resetView];
7988 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
7989 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
7990 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
7991 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
7992 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
7993 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
7994 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
7996 [self setIdleTimerDisabled:YES];
7998 hud_ = [[self addProgressHUD] retain];
7999 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8001 [self setStatusBarShowsProgress:YES];
8004 detachNewThreadSelector:@selector(reorganize)
8012 - (void) showKeyboard:(BOOL)show {
8013 CGSize keysize = [UIKeyboard defaultSize];
8014 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8015 CGRect keyup = keydown;
8016 keyup.origin.y -= keysize.height;
8018 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
8019 [animation setSignificantRectFields:2];
8022 [animation setStartFrame:keydown];
8023 [animation setEndFrame:keyup];
8024 [keyboard_ activate];
8026 [animation setStartFrame:keyup];
8027 [animation setEndFrame:keydown];
8028 [keyboard_ deactivate];
8031 [[UIAnimator sharedAnimator]
8032 addAnimations:[NSArray arrayWithObjects:animation, nil]
8033 withDuration:KeyboardTime_
8038 - (void) slideUp:(UIActionSheet *)alert {
8040 [alert presentSheetFromButtonBar:buttonbar_];
8042 [alert presentSheetInView:overlay_];
8047 void AddPreferences(NSString *plist) { _pooled
8048 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
8049 _assert(settings != NULL);
8050 NSMutableArray *items = [settings objectForKey:@"items"];
8054 for (NSMutableDictionary *item in items) {
8055 NSString *label = [item objectForKey:@"label"];
8056 if (label != nil && [label isEqualToString:@"Cydia"]) {
8063 for (size_t i(0); i != [items count]; ++i) {
8064 NSDictionary *item([items objectAtIndex:i]);
8065 NSString *label = [item objectForKey:@"label"];
8066 if (label != nil && [label isEqualToString:@"General"]) {
8067 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
8068 @"CydiaSettings", @"bundle",
8069 @"PSLinkCell", @"cell",
8070 [NSNumber numberWithBool:YES], @"hasIcon",
8071 [NSNumber numberWithBool:YES], @"isController",
8073 nil] atIndex:(i + 1)];
8079 _assert([settings writeToFile:plist atomically:YES] == YES);
8084 id Alloc_(id self, SEL selector) {
8085 id object = alloc_(self, selector);
8086 lprintf("[%s]A-%p\n", self->isa->name, object);
8091 id Dealloc_(id self, SEL selector) {
8092 id object = dealloc_(self, selector);
8093 lprintf("[%s]D-%p\n", self->isa->name, object);
8097 Class $WebDefaultUIKitDelegate;
8099 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
8101 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
8102 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8103 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8104 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
8107 int main(int argc, char *argv[]) { _pooled
8110 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8112 /* Library Hacks {{{ */
8113 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8115 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8116 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8117 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8118 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8119 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8122 /* Set Locale {{{ */
8123 Locale_ = CFLocaleCopyCurrent();
8124 Languages_ = [NSLocale preferredLanguages];
8125 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8126 //NSLog(@"%@", [Languages_ description]);
8128 if (Languages_ == nil || [Languages_ count] == 0)
8131 lang = [[Languages_ objectAtIndex:0] UTF8String];
8132 setenv("LANG", lang, true);
8133 //std::setlocale(LC_ALL, lang);
8134 NSLog(@"Setting Language: %s", lang);
8137 // XXX: apr_app_initialize?
8140 /* Parse Arguments {{{ */
8141 bool substrate(false);
8147 for (int argi(1); argi != argc; ++argi)
8148 if (strcmp(argv[argi], "--") == 0) {
8150 argv[argi] = argv[0];
8156 for (int argi(1); argi != arge; ++argi)
8157 if (strcmp(args[argi], "--bootstrap") == 0)
8159 else if (strcmp(args[argi], "--substrate") == 0)
8162 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8167 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
8168 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
8169 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
8170 Sounds_Keyboard_ = [keyboard boolValue];
8173 App_ = [[NSBundle mainBundle] bundlePath];
8174 Home_ = NSHomeDirectory();
8179 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8180 alloc_ = alloc->method_imp;
8181 alloc->method_imp = (IMP) &Alloc_;*/
8183 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8184 dealloc_ = dealloc->method_imp;
8185 dealloc->method_imp = (IMP) &Dealloc_;*/
8190 size = sizeof(maxproc);
8191 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8192 perror("sysctlbyname(\"kern.maxproc\", ?)");
8193 else if (maxproc < 64) {
8195 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8196 perror("sysctlbyname(\"kern.maxproc\", #)");
8199 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8200 char *machine = new char[size];
8201 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8202 perror("sysctlbyname(\"hw.machine\", ?)");
8206 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8208 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8209 Build_ = [system objectForKey:@"ProductBuildVersion"];
8210 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8211 Product_ = [info objectForKey:@"SafariProductVersion"];
8212 Safari_ = [info objectForKey:@"CFBundleVersion"];
8215 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8216 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
8218 /* Load Database {{{ */
8220 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8222 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8225 if (Metadata_ == NULL)
8226 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8228 Settings_ = [Metadata_ objectForKey:@"Settings"];
8230 Packages_ = [Metadata_ objectForKey:@"Packages"];
8231 Sections_ = [Metadata_ objectForKey:@"Sections"];
8232 Sources_ = [Metadata_ objectForKey:@"Sources"];
8235 if (Settings_ != nil)
8236 Role_ = [Settings_ objectForKey:@"Role"];
8238 if (Packages_ == nil) {
8239 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8240 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8243 if (Sections_ == nil) {
8244 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8245 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8248 if (Sources_ == nil) {
8249 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8250 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8255 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8258 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8259 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8260 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8261 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8263 if (access("/User", F_OK) != 0) {
8265 system("/usr/libexec/cydia/firmware.sh");
8269 _assert([[NSFileManager defaultManager]
8270 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8271 withIntermediateDirectories:YES
8276 if (access("/tmp/cydia.chk", F_OK) == 0) {
8277 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8278 _assert(errno == ENOENT);
8279 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8280 _assert(errno == ENOENT);
8283 _assert(pkgInitConfig(*_config));
8284 _assert(pkgInitSystem(*_config, _system));
8287 _config->Set("APT::Acquire::Translation", lang);
8288 _config->Set("Acquire::http::Timeout", 15);
8289 _config->Set("Acquire::http::MaxParallel", 4);
8291 /* Color Choices {{{ */
8292 space_ = CGColorSpaceCreateDeviceRGB();
8294 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8295 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8296 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8297 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8298 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8299 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8300 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8301 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8302 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8303 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8304 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8305 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8306 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8307 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8308 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8311 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8312 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8315 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8317 /* UIKit Configuration {{{ */
8318 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8319 if ($GSFontSetUseLegacyFontMetrics != NULL)
8320 $GSFontSetUseLegacyFontMetrics(YES);
8322 UIKeyboardDisableAutomaticAppearance();
8326 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8328 CGColorSpaceRelease(space_);