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 HistogramInsertionSort (0 && !ForRelease)
402 #define ProfileTimes (0 && !ForRelease)
403 #define ForSaurik (0 && !ForRelease)
404 #define LogBrowser (0 && !ForRelease)
405 #define TrackResize (0 && !ForRelease)
406 #define ManualRefresh (1 && !ForRelease)
407 #define ShowInternals (0 && !ForRelease)
408 #define IgnoreInstall (0 && !ForRelease)
409 #define RecycleWebViews 0
410 #define AlwaysReload (1 && !ForRelease)
414 #define _trace(args...)
419 #define _profile(name) {
422 #define PrintTimes() do {} while (false)
426 typedef uint32_t (*SKRadixFunction)(id, void *);
428 @interface NSMutableArray (Radix)
429 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
430 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
438 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
439 struct RadixItem_ *lhs(swap), *rhs(swap + count);
441 static const size_t width = 32;
442 static const size_t bits = 11;
443 static const size_t slots = 1 << bits;
444 static const size_t passes = (width + (bits - 1)) / bits;
446 size_t *hist(new size_t[slots]);
448 for (size_t pass(0); pass != passes; ++pass) {
449 memset(hist, 0, sizeof(size_t) * slots);
451 for (size_t i(0); i != count; ++i) {
452 uint32_t key(lhs[i].key);
454 key &= _not(uint32_t) >> width - bits;
459 for (size_t i(0); i != slots; ++i) {
460 size_t local(offset);
465 for (size_t i(0); i != count; ++i) {
466 uint32_t key(lhs[i].key);
468 key &= _not(uint32_t) >> width - bits;
469 rhs[hist[key]++] = lhs[i];
472 RadixItem_ *tmp(lhs);
479 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
480 for (size_t i(0); i != count; ++i)
481 [values addObject:[self objectAtIndex:lhs[i].index]];
482 [self setArray:values];
487 @implementation NSMutableArray (Radix)
489 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
490 size_t count([self count]);
495 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
496 [invocation setSelector:selector];
497 [invocation setArgument:&object atIndex:2];
499 /* XXX: this is an unsafe optimization of doomy hell */
500 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
501 _assert(method != NULL);
502 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
503 _assert(imp != NULL);
506 struct RadixItem_ *swap(new RadixItem_[count * 2]);
508 for (size_t i(0); i != count; ++i) {
509 RadixItem_ &item(swap[i]);
512 id object([self objectAtIndex:i]);
515 [invocation setTarget:object];
517 [invocation getReturnValue:&item.key];
519 item.key = imp(object, selector, object);
523 RadixSort_(self, count, swap);
526 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
527 size_t count([self count]);
528 struct RadixItem_ *swap(new RadixItem_[count * 2]);
530 for (size_t i(0); i != count; ++i) {
531 RadixItem_ &item(swap[i]);
534 id object([self objectAtIndex:i]);
535 item.key = function(object, argument);
538 RadixSort_(self, count, swap);
543 /* Insertion Sort {{{ */
545 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
546 const char *ptr = (const char *)list;
548 CFIndex half = count / 2;
549 const char *probe = ptr + elementSize * half;
550 CFComparisonResult cr = comparator(element, probe, context);
551 if (0 == cr) return (probe - (const char *)list) / elementSize;
552 ptr = (cr < 0) ? ptr : probe + elementSize;
553 count = (cr < 0) ? half : (half + (count & 1) - 1);
555 return (ptr - (const char *)list) / elementSize;
558 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
559 const char *ptr = (const char *)list;
561 CFIndex half = count / 2;
562 const char *probe = ptr + elementSize * half;
563 CFComparisonResult cr = comparator(element, probe, context);
564 if (0 == cr) return (probe - (const char *)list) / elementSize;
565 ptr = (cr < 0) ? ptr : probe + elementSize;
566 count = (cr < 0) ? half : (half + (count & 1) - 1);
568 return (ptr - (const char *)list) / elementSize;
571 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
572 if (range.length == 0)
574 const void **values(new const void *[range.length]);
575 CFArrayGetValues(array, range, values);
577 #if HistogramInsertionSort
578 uint32_t total(0), *offsets(new uint32_t[range.length]);
581 for (CFIndex index(1); index != range.length; ++index) {
582 const void *value(values[index]);
583 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
584 CFIndex correct(index);
585 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
588 if (correct != index) {
589 size_t offset(index - correct);
590 #if HistogramInsertionSort
594 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
596 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
597 values[correct] = value;
601 CFArrayReplaceValues(array, range, values, range.length);
604 #if HistogramInsertionSort
605 for (CFIndex index(0); index != range.length; ++index)
606 if (offsets[index] != 0)
607 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
608 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
615 /* Apple Bug Fixes {{{ */
616 @implementation UIWebDocumentView (Cydia)
618 - (void) _setScrollerOffset:(CGPoint)offset {
619 UIScroller *scroller([self _scroller]);
621 CGSize size([scroller contentSize]);
622 CGSize bounds([scroller bounds].size);
625 max.x = size.width - bounds.width;
626 max.y = size.height - bounds.height;
634 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
635 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
637 [scroller setOffset:offset];
644 kUIControlEventMouseDown = 1 << 0,
645 kUIControlEventMouseMovedInside = 1 << 2, // mouse moved inside control target
646 kUIControlEventMouseMovedOutside = 1 << 3, // mouse moved outside control target
647 kUIControlEventMouseUpInside = 1 << 6, // mouse up inside control target
648 kUIControlEventMouseUpOutside = 1 << 7, // mouse up outside control target
649 kUIControlAllEvents = (kUIControlEventMouseDown | kUIControlEventMouseMovedInside | kUIControlEventMouseMovedOutside | kUIControlEventMouseUpInside | kUIControlEventMouseUpOutside)
650 } UIControlEventMasks;
652 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
653 size_t length([self length] - state->state);
656 else if (length > count)
658 for (size_t i(0); i != length; ++i)
659 objects[i] = [self item:state->state++];
660 state->itemsPtr = objects;
661 state->mutationsPtr = (unsigned long *) self;
665 @interface NSString (UIKit)
666 - (NSString *) stringByAddingPercentEscapes;
667 - (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
670 @interface NSString (Cydia)
671 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
672 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
673 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
674 - (NSComparisonResult) compareByPath:(NSString *)other;
675 - (NSString *) stringByCachingURLWithCurrentCDN;
676 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
679 @implementation NSString (Cydia)
681 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
682 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
685 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
686 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
687 memcpy(data, bytes, length);
688 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
691 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
692 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
695 - (NSComparisonResult) compareByPath:(NSString *)other {
696 NSString *prefix = [self commonPrefixWithString:other options:0];
697 size_t length = [prefix length];
699 NSRange lrange = NSMakeRange(length, [self length] - length);
700 NSRange rrange = NSMakeRange(length, [other length] - length);
702 lrange = [self rangeOfString:@"/" options:0 range:lrange];
703 rrange = [other rangeOfString:@"/" options:0 range:rrange];
705 NSComparisonResult value;
707 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
708 value = NSOrderedSame;
709 else if (lrange.location == NSNotFound)
710 value = NSOrderedAscending;
711 else if (rrange.location == NSNotFound)
712 value = NSOrderedDescending;
714 value = NSOrderedSame;
716 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
717 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
718 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
719 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
721 NSComparisonResult result = [lpath compare:rpath];
722 return result == NSOrderedSame ? value : result;
725 - (NSString *) stringByCachingURLWithCurrentCDN {
727 stringByReplacingOccurrencesOfString:@"://"
728 withString:@"://ne.edgecastcdn.net/8003A4/"
730 /* XXX: this is somewhat inaccurate */
731 range:NSMakeRange(0, 10)
735 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
736 return [(id)CFURLCreateStringByAddingPercentEscapes(
741 kCFStringEncodingUTF8
747 static inline NSString *CYLocalizeEx(NSString *key, NSString *value = nil) {
748 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:nil];
751 #define CYLocalize(key) CYLocalizeEx(@ key)
759 _finline void clear_() {
765 _finline bool empty() const {
769 _finline size_t size() const {
773 _finline char *data() const {
777 _finline void clear() {
782 _finline CYString() :
789 _finline ~CYString() {
793 void operator =(const CYString &rhs) {
797 if (rhs.cache_ == nil)
800 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
803 void set(apr_pool_t *pool, const char *data, size_t size) {
809 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
810 memcpy(temp, data, size);
817 _finline void set(apr_pool_t *pool, const char *data) {
818 set(pool, data, data == NULL ? 0 : strlen(data));
821 _finline void set(apr_pool_t *pool, const std::string &rhs) {
822 set(pool, rhs.data(), rhs.size());
825 bool operator ==(const CYString &rhs) const {
826 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
829 operator CFStringRef() {
830 if (cache_ == NULL) {
833 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
837 _finline operator id() {
838 return (NSString *) static_cast<CFStringRef>(*this);
843 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
846 struct NSStringMapHash :
847 std::unary_function<NSString *, size_t>
849 _finline size_t operator ()(NSString *value) const {
850 return CFStringHashNSString((CFStringRef) value);
854 struct NSStringMapLess :
855 std::binary_function<NSString *, NSString *, bool>
857 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
858 return [lhs compare:rhs] == NSOrderedAscending;
862 struct NSStringMapEqual :
863 std::binary_function<NSString *, NSString *, bool>
865 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
866 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
867 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
868 //[lhs isEqualToString:rhs];
872 /* Perl-Compatible RegEx {{{ */
882 Pcre(const char *regex) :
887 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
890 lprintf("%d:%s\n", offset, error);
894 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
895 matches_ = new int[(capture_ + 1) * 3];
903 NSString *operator [](size_t match) {
904 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
907 bool operator ()(NSString *data) {
908 // XXX: length is for characters, not for bytes
909 return operator ()([data UTF8String], [data length]);
912 bool operator ()(const char *data, size_t size) {
914 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
918 /* Mime Addresses {{{ */
919 @interface Address : NSObject {
925 - (NSString *) address;
927 - (void) setAddress:(NSString *)address;
929 + (Address *) addressWithString:(NSString *)string;
930 - (Address *) initWithString:(NSString *)string;
933 @implementation Address
942 - (NSString *) name {
946 - (NSString *) address {
950 - (void) setAddress:(NSString *)address {
952 [address_ autorelease];
956 address_ = [address retain];
959 + (Address *) addressWithString:(NSString *)string {
960 return [[[Address alloc] initWithString:string] autorelease];
963 + (NSArray *) _attributeKeys {
964 return [NSArray arrayWithObjects:@"address", @"name", nil];
967 - (NSArray *) attributeKeys {
968 return [[self class] _attributeKeys];
971 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
972 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
975 - (Address *) initWithString:(NSString *)string {
976 if ((self = [super init]) != nil) {
977 const char *data = [string UTF8String];
978 size_t size = [string length];
980 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
982 if (address_r(data, size)) {
983 name_ = [address_r[1] retain];
984 address_ = [address_r[2] retain];
986 name_ = [string retain];
994 /* CoreGraphics Primitives {{{ */
1005 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
1008 Set(space, red, green, blue, alpha);
1013 CGColorRelease(color_);
1020 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1022 float color[] = {red, green, blue, alpha};
1023 color_ = CGColorCreate(space, color);
1026 operator CGColorRef() {
1032 extern "C" void UISetColor(CGColorRef color);
1034 /* Random Global Variables {{{ */
1035 static const int PulseInterval_ = 50000;
1036 static const int ButtonBarHeight_ = 48;
1037 static const float KeyboardTime_ = 0.3f;
1039 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1040 #define SandboxTemplate_ "/usr/share/sandbox/SandboxTemplate.sb"
1041 #define NotifyConfig_ "/etc/notify.conf"
1043 static bool Queuing_;
1045 static CGColor Blue_;
1046 static CGColor Blueish_;
1047 static CGColor Black_;
1048 static CGColor Off_;
1049 static CGColor White_;
1050 static CGColor Gray_;
1051 static CGColor Green_;
1052 static CGColor Purple_;
1053 static CGColor Purplish_;
1055 static UIColor *InstallingColor_;
1056 static UIColor *RemovingColor_;
1058 static NSString *App_;
1059 static NSString *Home_;
1060 static BOOL Sounds_Keyboard_;
1062 static BOOL Advanced_;
1063 static BOOL Loaded_;
1064 static BOOL Ignored_;
1066 static UIFont *Font12_;
1067 static UIFont *Font12Bold_;
1068 static UIFont *Font14_;
1069 static UIFont *Font18Bold_;
1070 static UIFont *Font22Bold_;
1072 static const char *Machine_ = NULL;
1073 static const NSString *UniqueID_ = nil;
1074 static const NSString *Build_ = nil;
1075 static const NSString *Product_ = nil;
1076 static const NSString *Safari_ = nil;
1078 CFLocaleRef Locale_;
1079 NSArray *Languages_;
1080 CGColorSpaceRef space_;
1085 static NSDictionary *SectionMap_;
1086 static NSMutableDictionary *Metadata_;
1087 static _transient NSMutableDictionary *Settings_;
1088 static _transient NSString *Role_;
1089 static _transient NSMutableDictionary *Packages_;
1090 static _transient NSMutableDictionary *Sections_;
1091 static _transient NSMutableDictionary *Sources_;
1092 static bool Changed_;
1093 static NSDate *now_;
1096 static NSMutableArray *Documents_;
1099 NSString *GetLastUpdate() {
1100 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1103 return CYLocalize("NEVER_OR_UNKNOWN");
1105 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1106 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1108 CFRelease(formatter);
1110 return [(NSString *) formatted autorelease];
1113 /* Display Helpers {{{ */
1114 inline float Interpolate(float begin, float end, float fraction) {
1115 return (end - begin) * fraction + begin;
1118 /* XXX: localize this! */
1119 NSString *SizeString(double size) {
1120 bool negative = size < 0;
1125 while (size > 1024) {
1130 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1132 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1135 NSString *StripVersion(const char *version) {
1136 const char *colon(strchr(version, ':'));
1138 version = colon + 1;
1139 return [NSString stringWithUTF8String:version];
1142 NSString *StripVersion(NSString *version) {
1143 NSRange colon = [version rangeOfString:@":"];
1144 if (colon.location != NSNotFound)
1145 version = [version substringFromIndex:(colon.location + 1)];
1149 NSString *LocalizeSection(NSString *section) {
1150 static Pcre title_r("^(.*?) \\((.*)\\)$");
1151 if (title_r(section)) {
1152 NSString *parent(title_r[1]);
1153 NSString *child(title_r[2]);
1155 return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"),
1156 LocalizeSection(parent),
1157 LocalizeSection(child)
1161 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1164 NSString *Simplify(NSString *title) {
1165 const char *data = [title UTF8String];
1166 size_t size = [title length];
1168 static Pcre square_r("^\\[(.*)\\]$");
1169 if (square_r(data, size))
1170 return Simplify(square_r[1]);
1172 static Pcre paren_r("^\\((.*)\\)$");
1173 if (paren_r(data, size))
1174 return Simplify(paren_r[1]);
1176 static Pcre title_r("^(.*?) \\((.*)\\)$");
1177 if (title_r(data, size))
1178 return Simplify(title_r[1]);
1184 bool isSectionVisible(NSString *section) {
1185 NSDictionary *metadata([Sections_ objectForKey:section]);
1186 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1187 return hidden == nil || ![hidden boolValue];
1190 /* Delegate Prototypes {{{ */
1194 @interface NSObject (ProgressDelegate)
1197 @implementation NSObject(ProgressDelegate)
1199 - (void) _setProgressError:(NSArray *)args {
1200 [self performSelector:@selector(setProgressError:forPackage:)
1201 withObject:[args objectAtIndex:0]
1202 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1208 @protocol ProgressDelegate
1209 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1210 - (void) setProgressTitle:(NSString *)title;
1211 - (void) setProgressPercent:(float)percent;
1212 - (void) startProgress;
1213 - (void) addProgressOutput:(NSString *)output;
1214 - (bool) isCancelling:(size_t)received;
1217 @protocol ConfigurationDelegate
1218 - (void) repairWithSelector:(SEL)selector;
1219 - (void) setConfigurationData:(NSString *)data;
1224 @protocol CydiaDelegate
1225 - (void) setPackageView:(PackageView *)view;
1226 - (void) clearPackage:(Package *)package;
1227 - (void) installPackage:(Package *)package;
1228 - (void) removePackage:(Package *)package;
1229 - (void) slideUp:(UIActionSheet *)alert;
1230 - (void) distUpgrade;
1231 - (void) updateData;
1233 - (void) askForSettings;
1234 - (UIProgressHUD *) addProgressHUD;
1235 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1236 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag;
1237 - (RVPage *) pageForPackage:(NSString *)name;
1238 - (void) openMailToURL:(NSURL *)url;
1239 - (void) clearFirstResponder;
1240 - (PackageView *) packageView;
1244 /* Status Delegation {{{ */
1246 public pkgAcquireStatus
1249 _transient NSObject<ProgressDelegate> *delegate_;
1257 void setDelegate(id delegate) {
1258 delegate_ = delegate;
1261 virtual bool MediaChange(std::string media, std::string drive) {
1265 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1268 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1269 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1270 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
1273 virtual void Done(pkgAcquire::ItemDesc &item) {
1276 virtual void Fail(pkgAcquire::ItemDesc &item) {
1278 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1279 item.Owner->Status == pkgAcquire::Item::StatDone
1283 std::string &error(item.Owner->ErrorText);
1287 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1288 NSArray *fields([description componentsSeparatedByString:@" "]);
1289 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1291 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1292 withObject:[NSArray arrayWithObjects:
1293 [NSString stringWithUTF8String:error.c_str()],
1300 virtual bool Pulse(pkgAcquire *Owner) {
1301 bool value = pkgAcquireStatus::Pulse(Owner);
1304 double(CurrentBytes + CurrentItems) /
1305 double(TotalBytes + TotalItems)
1308 [delegate_ setProgressPercent:percent];
1309 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1312 virtual void Start() {
1313 [delegate_ startProgress];
1316 virtual void Stop() {
1320 /* Progress Delegation {{{ */
1325 _transient id<ProgressDelegate> delegate_;
1328 virtual void Update() {
1329 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1330 [delegate_ setProgressPercent:(Percent / 100)];*/
1339 void setDelegate(id delegate) {
1340 delegate_ = delegate;
1343 virtual void Done() {
1344 //[delegate_ setProgressPercent:1];
1349 /* Database Interface {{{ */
1350 @interface Database : NSObject {
1356 pkgCacheFile cache_;
1357 pkgDepCache::Policy *policy_;
1358 pkgRecords *records_;
1359 pkgProblemResolver *resolver_;
1360 pkgAcquire *fetcher_;
1362 SPtr<pkgPackageManager> manager_;
1363 pkgSourceList *list_;
1365 NSMutableDictionary *sources_;
1366 NSMutableArray *packages_;
1368 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1377 + (Database *) sharedInstance;
1380 - (void) _readCydia:(NSNumber *)fd;
1381 - (void) _readStatus:(NSNumber *)fd;
1382 - (void) _readOutput:(NSNumber *)fd;
1386 - (Package *) packageWithName:(NSString *)name;
1388 - (pkgCacheFile &) cache;
1389 - (pkgDepCache::Policy *) policy;
1390 - (pkgRecords *) records;
1391 - (pkgProblemResolver *) resolver;
1392 - (pkgAcquire &) fetcher;
1393 - (pkgSourceList &) list;
1394 - (NSArray *) packages;
1395 - (NSArray *) sources;
1396 - (void) reloadData;
1404 - (void) updateWithStatus:(Status &)status;
1406 - (void) setDelegate:(id)delegate;
1407 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1411 /* Source Class {{{ */
1412 @interface Source : NSObject {
1413 NSString *description_;
1419 NSString *distribution_;
1423 NSString *defaultIcon_;
1425 NSDictionary *record_;
1429 - (Source *) initWithMetaIndex:(metaIndex *)index;
1431 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1433 - (NSString *) supportForPackage:(NSString *)package;
1435 - (NSDictionary *) record;
1439 - (NSString *) distribution;
1440 - (NSString *) type;
1442 - (NSString *) host;
1444 - (NSString *) name;
1445 - (NSString *) description;
1446 - (NSString *) label;
1447 - (NSString *) origin;
1448 - (NSString *) version;
1450 - (NSString *) defaultIcon;
1454 @implementation Source
1456 #define _clear(field) \
1463 _clear(distribution_)
1466 _clear(description_)
1471 _clear(defaultIcon_)
1480 + (NSArray *) _attributeKeys {
1481 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1484 - (NSArray *) attributeKeys {
1485 return [[self class] _attributeKeys];
1488 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1489 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1492 - (void) setMetaIndex:(metaIndex *)index {
1495 trusted_ = index->IsTrusted();
1497 uri_ = [[NSString stringWithUTF8String:index->GetURI().c_str()] retain];
1498 distribution_ = [[NSString stringWithUTF8String:index->GetDist().c_str()] retain];
1499 type_ = [[NSString stringWithUTF8String:index->GetType()] retain];
1501 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1502 if (dindex != NULL) {
1503 std::ifstream release(dindex->MetaIndexFile("Release").c_str());
1505 while (std::getline(release, line)) {
1506 std::string::size_type colon(line.find(':'));
1507 if (colon == std::string::npos)
1510 std::string name(line.substr(0, colon));
1511 std::string value(line.substr(colon + 1));
1512 while (!value.empty() && value[0] == ' ')
1513 value = value.substr(1);
1515 if (name == "Default-Icon")
1516 defaultIcon_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1517 else if (name == "Description")
1518 description_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1519 else if (name == "Label")
1520 label_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1521 else if (name == "Origin")
1522 origin_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1523 else if (name == "Support")
1524 support_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1525 else if (name == "Version")
1526 version_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1530 record_ = [Sources_ objectForKey:[self key]];
1532 record_ = [record_ retain];
1535 - (Source *) initWithMetaIndex:(metaIndex *)index {
1536 if ((self = [super init]) != nil) {
1537 [self setMetaIndex:index];
1541 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1542 NSDictionary *lhr = [self record];
1543 NSDictionary *rhr = [source record];
1546 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1548 NSString *lhs = [self name];
1549 NSString *rhs = [source name];
1551 if ([lhs length] != 0 && [rhs length] != 0) {
1552 unichar lhc = [lhs characterAtIndex:0];
1553 unichar rhc = [rhs characterAtIndex:0];
1555 if (isalpha(lhc) && !isalpha(rhc))
1556 return NSOrderedAscending;
1557 else if (!isalpha(lhc) && isalpha(rhc))
1558 return NSOrderedDescending;
1561 return [lhs compare:rhs options:LaxCompareOptions_];
1564 - (NSString *) supportForPackage:(NSString *)package {
1565 return support_ == nil ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1568 - (NSDictionary *) record {
1576 - (NSString *) uri {
1580 - (NSString *) distribution {
1581 return distribution_;
1584 - (NSString *) type {
1588 - (NSString *) key {
1589 return [NSString stringWithFormat:@"%@:%@:%@", type_, uri_, distribution_];
1592 - (NSString *) host {
1593 return [[[NSURL URLWithString:[self uri]] host] lowercaseString];
1596 - (NSString *) name {
1597 return origin_ == nil ? [self host] : origin_;
1600 - (NSString *) description {
1601 return description_;
1604 - (NSString *) label {
1605 return label_ == nil ? [self host] : label_;
1608 - (NSString *) origin {
1612 - (NSString *) version {
1616 - (NSString *) defaultIcon {
1617 return defaultIcon_;
1622 /* Relationship Class {{{ */
1623 @interface Relationship : NSObject {
1628 - (NSString *) type;
1630 - (NSString *) name;
1634 @implementation Relationship
1642 - (NSString *) type {
1650 - (NSString *) name {
1657 /* Package Class {{{ */
1658 @interface Package : NSObject {
1661 pkgCache::VerIterator version_;
1662 pkgCache::PkgIterator iterator_;
1663 _transient Database *database_;
1664 pkgCache::VerFileIterator file_;
1670 NSString *section$_;
1675 NSString *installed_;
1681 CYString depiction_;
1694 NSArray *relationships_;
1696 NSMutableDictionary *metadata_;
1697 _transient NSDate *firstSeen_;
1698 _transient NSDate *lastSeen_;
1702 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1703 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1705 - (pkgCache::PkgIterator) iterator;
1707 - (NSString *) section;
1708 - (NSString *) simpleSection;
1710 - (NSString *) longSection;
1711 - (NSString *) shortSection;
1715 - (Address *) maintainer;
1717 - (NSString *) longDescription;
1718 - (NSString *) shortDescription;
1721 - (NSMutableDictionary *) metadata;
1723 - (BOOL) subscribed;
1726 - (NSString *) latest;
1727 - (NSString *) installed;
1730 - (BOOL) upgradableAndEssential:(BOOL)essential;
1733 - (BOOL) unfiltered;
1737 - (BOOL) halfConfigured;
1738 - (BOOL) halfInstalled;
1740 - (NSString *) mode;
1743 - (NSString *) name;
1745 - (NSString *) homepage;
1746 - (NSString *) depiction;
1747 - (Address *) author;
1749 - (NSString *) support;
1751 - (NSArray *) files;
1752 - (NSArray *) relationships;
1753 - (NSArray *) warnings;
1754 - (NSArray *) applications;
1756 - (Source *) source;
1757 - (NSString *) role;
1759 - (BOOL) matches:(NSString *)text;
1761 - (bool) hasSupportingRole;
1762 - (BOOL) hasTag:(NSString *)tag;
1763 - (NSString *) primaryPurpose;
1764 - (NSArray *) purposes;
1765 - (bool) isCommercial;
1767 - (CYString &) cyname;
1769 - (uint32_t) compareBySection:(NSArray *)sections;
1771 - (uint32_t) compareForChanges;
1776 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1777 - (bool) isInstalledAndVisible:(NSNumber *)number;
1778 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1779 - (bool) isVisibleInSource:(Source *)source;
1783 uint32_t PackageChangesRadix(Package *self, void *) {
1788 uint32_t timestamp : 30;
1789 uint32_t ignored : 1;
1790 uint32_t upgradable : 1;
1794 bool upgradable([self upgradableAndEssential:YES]);
1795 value.bits.upgradable = upgradable ? 1 : 0;
1798 value.bits.timestamp = 0;
1799 value.bits.ignored = [self ignored] ? 0 : 1;
1800 value.bits.upgradable = 1;
1802 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1803 value.bits.ignored = 0;
1804 value.bits.upgradable = 0;
1807 return _not(uint32_t) - value.key;
1810 _finline static void Stifle(uint8_t &value) {
1813 uint32_t PackagePrefixRadix(Package *self, void *context) {
1814 size_t offset(reinterpret_cast<size_t>(context));
1815 CYString &name([self cyname]);
1817 size_t size(name.size());
1820 char *text(name.data());
1823 if (!isdigit(text[0]))
1827 while (size != digits && isdigit(text[digits]))
1837 if (offset == 0 && zeros != 0) {
1838 memset(data, '0', zeros);
1839 memcpy(data + zeros, text, 4 - zeros);
1841 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1842 if (size <= offset - zeros)
1845 text += offset - zeros;
1846 size -= offset - zeros;
1849 memcpy(data, text, 4);
1851 memcpy(data, text, size);
1852 memset(data + size, 0, 4 - size);
1855 for (size_t i(0); i != 4; ++i)
1856 if (isalpha(data[i]))
1861 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1863 /* XXX: ntohl may be more honest */
1864 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1867 CYString &(*PackageName)(Package *self, SEL sel);
1869 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1870 _profile(PackageNameCompare)
1871 CYString &lhi(PackageName(lhs, @selector(cyname)));
1872 CYString &rhi(PackageName(rhs, @selector(cyname)));
1873 CFStringRef lhn(lhi), rhn(rhi);
1875 _profile(PackageNameCompare$NumbersLast)
1876 if (!lhi.empty() && !rhi.empty()) {
1877 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1878 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1879 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1880 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1881 return lha ? NSOrderedAscending : NSOrderedDescending;
1885 CFIndex length = CFStringGetLength(lhn);
1887 _profile(PackageNameCompare$Compare)
1888 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1893 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1894 return PackageNameCompare(*lhs, *rhs, context);
1897 struct PackageNameOrdering :
1898 std::binary_function<Package *, Package *, bool>
1900 _finline bool operator ()(Package *lhs, Package *rhs) const {
1901 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1905 @implementation Package
1907 - (NSString *) description {
1908 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1914 if (section$_ != nil)
1915 [section$_ release];
1919 if (installed_ != nil)
1920 [installed_ release];
1922 if (sponsor$_ != nil)
1923 [sponsor$_ release];
1924 if (author$_ != nil)
1931 if (relationships_ != nil)
1932 [relationships_ release];
1933 if (metadata_ != nil)
1934 [metadata_ release];
1939 + (NSString *) webScriptNameForSelector:(SEL)selector {
1940 if (selector == @selector(hasTag:))
1946 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1947 return [self webScriptNameForSelector:selector] == nil;
1950 + (NSArray *) _attributeKeys {
1951 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];
1954 - (NSArray *) attributeKeys {
1955 return [[self class] _attributeKeys];
1958 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1959 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1962 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
1963 if ((self = [super init]) != nil) {
1964 _profile(Package$initWithVersion)
1965 @synchronized (database) {
1966 era_ = [database era];
1969 iterator_ = version.ParentPkg();
1970 database_ = database;
1972 _profile(Package$initWithVersion$Latest)
1973 latest_ = [StripVersion(version_.VerStr()) retain];
1976 pkgCache::VerIterator current(iterator_.CurrentVer());
1978 installed_ = [StripVersion(current.VerStr()) retain];
1980 if (!version_.end())
1981 file_ = version_.FileList();
1983 pkgCache &cache([database_ cache]);
1984 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
1987 _profile(Package$initWithVersion$Name)
1988 id_.set(pool, iterator_.Name());
1992 source_ = [database_ getSource:file_.File()];
1997 _profile(Package$initWithVersion$Parse)
1998 pkgRecords::Parser *parser;
2000 _profile(Package$initWithVersion$Parse$Lookup)
2001 parser = &[database_ records]->Lookup(file_);
2007 _profile(Package$initWithVersion$Parse$Find)
2014 {"depiction", &depiction_},
2015 {"homepage", &homepage_},
2016 {"website", &website},
2017 {"support", &support_},
2018 {"sponsor", &sponsor_},
2019 {"author", &author_},
2023 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2024 const char *start, *end;
2026 if (parser->Find(names[i].name_, start, end)) {
2027 CYString &value(*names[i].value_);
2028 _profile(Package$initWithVersion$Parse$Value)
2029 value.set(pool, start, end - start);
2035 _profile(Package$initWithVersion$Parse$Tagline)
2036 tagline_.set(pool, parser->ShortDesc());
2039 _profile(Package$initWithVersion$Parse$Retain)
2040 if (!homepage_.empty())
2041 homepage_ = website;
2042 if (homepage_ == depiction_)
2045 tags_ = [[tag componentsSeparatedByString:@", "] retain];
2049 _profile(Package$initWithVersion$Tags)
2051 for (NSString *tag in tags_)
2052 if ([tag hasPrefix:@"role::"]) {
2053 role_ = [[tag substringFromIndex:6] retain];
2058 bool changed(false);
2059 NSString *key([id_ lowercaseString]);
2061 _profile(Package$initWithVersion$Metadata)
2062 metadata_ = [Packages_ objectForKey:key];
2064 if (metadata_ == nil) {
2065 firstSeen_ = [now_ retain];
2067 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2068 firstSeen_, @"FirstSeen",
2069 latest_, @"LastVersion",
2074 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2075 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2077 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2078 subscribed_ = [subscribed boolValue];
2080 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2082 if (firstSeen_ == nil) {
2083 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2084 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2088 if (version == nil) {
2089 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2091 } else if (![version isEqualToString:latest_]) {
2092 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2094 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2099 metadata_ = [metadata_ retain];
2102 [Packages_ setObject:metadata_ forKey:key];
2107 _profile(Package$initWithVersion$Section)
2108 section_.set(pool, iterator_.Section());
2111 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2112 visible_ = [self hasSupportingRole] && [self unfiltered];
2113 } _end } return self;
2116 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2117 pkgCache::VerIterator version;
2119 _profile(Package$packageWithIterator$GetCandidateVer)
2120 version = [database policy]->GetCandidateVer(iterator);
2126 return [[[Package alloc]
2127 initWithVersion:version
2134 - (pkgCache::PkgIterator) iterator {
2138 - (NSString *) section {
2139 if (section$_ == nil) {
2140 if (section_.empty())
2143 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2144 NSString *name(section_);
2147 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2148 if (NSString *rename = [value objectForKey:@"Rename"]) {
2153 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2157 - (NSString *) simpleSection {
2158 if (NSString *section = [self section])
2159 return Simplify(section);
2164 - (NSString *) longSection {
2165 return LocalizeSection(section_);
2168 - (NSString *) shortSection {
2169 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2172 - (NSString *) uri {
2175 pkgIndexFile *index;
2176 pkgCache::PkgFileIterator file(file_.File());
2177 if (![database_ list].FindIndex(file, index))
2179 return [NSString stringWithUTF8String:iterator_->Path];
2180 //return [NSString stringWithUTF8String:file.Site()];
2181 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2185 - (Address *) maintainer {
2188 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2189 const std::string &maintainer(parser->Maintainer());
2190 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2194 return version_.end() ? 0 : version_->InstalledSize;
2197 - (NSString *) longDescription {
2200 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2201 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2203 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2204 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2205 if ([lines count] < 2)
2208 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2209 for (size_t i(1), e([lines count]); i != e; ++i) {
2210 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2211 [trimmed addObject:trim];
2214 return [trimmed componentsJoinedByString:@"\n"];
2217 - (NSString *) shortDescription {
2222 _profile(Package$index)
2223 CFStringRef name((CFStringRef) [self name]);
2224 if (CFStringGetLength(name) == 0)
2226 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2227 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2229 return toupper(character);
2233 - (NSMutableDictionary *) metadata {
2238 if (subscribed_ && lastSeen_ != nil)
2243 - (BOOL) subscribed {
2248 NSDictionary *metadata([self metadata]);
2249 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2250 return [ignored boolValue];
2255 - (NSString *) latest {
2259 - (NSString *) installed {
2264 return !version_.end();
2267 - (BOOL) upgradableAndEssential:(BOOL)essential {
2268 _profile(Package$upgradableAndEssential)
2269 pkgCache::VerIterator current(iterator_.CurrentVer());
2271 return essential && essential_ && visible_;
2273 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2277 - (BOOL) essential {
2282 return [database_ cache][iterator_].InstBroken();
2285 - (BOOL) unfiltered {
2286 NSString *section([self section]);
2287 return section == nil || isSectionVisible(section);
2295 unsigned char current(iterator_->CurrentState);
2296 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2299 - (BOOL) halfConfigured {
2300 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2303 - (BOOL) halfInstalled {
2304 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2308 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2309 return state.Mode != pkgDepCache::ModeKeep;
2312 - (NSString *) mode {
2313 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2315 switch (state.Mode) {
2316 case pkgDepCache::ModeDelete:
2317 if ((state.iFlags & pkgDepCache::Purge) != 0)
2321 case pkgDepCache::ModeKeep:
2322 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2323 return @"REINSTALL";
2324 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2328 case pkgDepCache::ModeInstall:
2329 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2330 return @"REINSTALL";
2331 else*/ switch (state.Status) {
2333 return @"DOWNGRADE";
2339 return @"NEW_INSTALL";
2352 - (NSString *) name {
2353 return name_.empty() ? id_ : name_;
2356 - (UIImage *) icon {
2357 NSString *section = [self simpleSection];
2361 if ([icon_ hasPrefix:@"file:///"])
2362 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2363 if (icon == nil) if (section != nil)
2364 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2365 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2366 if ([dicon hasPrefix:@"file:///"])
2367 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2369 icon = [UIImage applicationImageNamed:@"unknown.png"];
2373 - (NSString *) homepage {
2377 - (NSString *) depiction {
2381 - (Address *) sponsor {
2382 if (sponsor$_ == nil) {
2383 if (sponsor_.empty())
2385 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2389 - (Address *) author {
2390 if (author$_ == nil) {
2391 if (author_.empty())
2393 author$_ = [[Address addressWithString:author_] retain];
2397 - (NSString *) support {
2398 return !support_.empty() ? support_ : [[self source] supportForPackage:id_];
2401 - (NSArray *) files {
2402 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2403 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2406 fin.open([path UTF8String]);
2411 while (std::getline(fin, line))
2412 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2417 - (NSArray *) relationships {
2418 return relationships_;
2421 - (NSArray *) warnings {
2422 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2423 const char *name(iterator_.Name());
2425 size_t length(strlen(name));
2426 if (length < 2) invalid:
2427 [warnings addObject:CYLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2428 else for (size_t i(0); i != length; ++i)
2430 /* XXX: technically this is not allowed */
2431 (name[i] < 'A' || name[i] > 'Z') &&
2432 (name[i] < 'a' || name[i] > 'z') &&
2433 (name[i] < '0' || name[i] > '9') &&
2434 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2437 if (strcmp(name, "cydia") != 0) {
2439 bool _private = false;
2442 bool repository = [[self section] isEqualToString:@"Repositories"];
2444 if (NSArray *files = [self files])
2445 for (NSString *file in files)
2446 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2448 else if (!_private && [file isEqualToString:@"/private"])
2450 else if (!stash && [file isEqualToString:@"/var/stash"])
2453 /* XXX: this is not sensitive enough. only some folders are valid. */
2454 if (cydia && !repository)
2455 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2457 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/private"]];
2459 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2462 return [warnings count] == 0 ? nil : warnings;
2465 - (NSArray *) applications {
2466 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2468 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2470 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2471 if (NSArray *files = [self files])
2472 for (NSString *file in files)
2473 if (application_r(file)) {
2474 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2475 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2476 if ([id isEqualToString:me])
2479 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2481 display = application_r[1];
2483 NSString *bundle([file stringByDeletingLastPathComponent]);
2484 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2485 if (icon == nil || [icon length] == 0)
2487 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2489 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2490 [applications addObject:application];
2492 [application addObject:id];
2493 [application addObject:display];
2494 [application addObject:url];
2497 return [applications count] == 0 ? nil : applications;
2500 - (Source *) source {
2502 @synchronized (database_) {
2503 if ([database_ era] != era_ || file_.end())
2506 source_ = [database_ getSource:file_.File()];
2518 - (NSString *) role {
2522 - (BOOL) matches:(NSString *)text {
2528 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2529 if (range.location != NSNotFound)
2532 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2533 if (range.location != NSNotFound)
2536 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2537 if (range.location != NSNotFound)
2543 - (bool) hasSupportingRole {
2546 if ([role_ isEqualToString:@"enduser"])
2548 if ([Role_ isEqualToString:@"User"])
2550 if ([role_ isEqualToString:@"hacker"])
2552 if ([Role_ isEqualToString:@"Hacker"])
2554 if ([role_ isEqualToString:@"developer"])
2556 if ([Role_ isEqualToString:@"Developer"])
2561 - (BOOL) hasTag:(NSString *)tag {
2562 return tags_ == nil ? NO : [tags_ containsObject:tag];
2565 - (NSString *) primaryPurpose {
2566 for (NSString *tag in tags_)
2567 if ([tag hasPrefix:@"purpose::"])
2568 return [tag substringFromIndex:9];
2572 - (NSArray *) purposes {
2573 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2574 for (NSString *tag in tags_)
2575 if ([tag hasPrefix:@"purpose::"])
2576 [purposes addObject:[tag substringFromIndex:9]];
2577 return [purposes count] == 0 ? nil : purposes;
2580 - (bool) isCommercial {
2581 return [self hasTag:@"cydia::commercial"];
2584 - (CYString &) cyname {
2585 return name_.empty() ? id_ : name_;
2588 - (uint32_t) compareBySection:(NSArray *)sections {
2589 NSString *section([self section]);
2590 for (size_t i(0), e([sections count]); i != e; ++i) {
2591 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2595 return _not(uint32_t);
2598 - (uint32_t) compareForChanges {
2603 uint32_t timestamp : 30;
2604 uint32_t ignored : 1;
2605 uint32_t upgradable : 1;
2609 bool upgradable([self upgradableAndEssential:YES]);
2610 value.bits.upgradable = upgradable ? 1 : 0;
2613 value.bits.timestamp = 0;
2614 value.bits.ignored = [self ignored] ? 0 : 1;
2615 value.bits.upgradable = 1;
2617 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2618 value.bits.ignored = 0;
2619 value.bits.upgradable = 0;
2622 return _not(uint32_t) - value.key;
2626 pkgProblemResolver *resolver = [database_ resolver];
2627 resolver->Clear(iterator_);
2628 resolver->Protect(iterator_);
2632 pkgProblemResolver *resolver = [database_ resolver];
2633 resolver->Clear(iterator_);
2634 resolver->Protect(iterator_);
2635 pkgCacheFile &cache([database_ cache]);
2636 cache->MarkInstall(iterator_, false);
2637 pkgDepCache::StateCache &state((*cache)[iterator_]);
2638 if (!state.Install())
2639 cache->SetReInstall(iterator_, true);
2643 pkgProblemResolver *resolver = [database_ resolver];
2644 resolver->Clear(iterator_);
2645 resolver->Protect(iterator_);
2646 resolver->Remove(iterator_);
2647 [database_ cache]->MarkDelete(iterator_, true);
2650 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2651 _profile(Package$isUnfilteredAndSearchedForBy)
2654 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2655 value &= [self unfiltered];
2658 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2659 value &= [self matches:search];
2666 - (bool) isInstalledAndVisible:(NSNumber *)number {
2667 return (![number boolValue] || [self visible]) && [self installed] != nil;
2670 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2671 NSString *section = [self section];
2675 [self installed] == nil && (
2677 section == nil && [name length] == 0 ||
2678 [name isEqualToString:section]
2682 - (bool) isVisibleInSource:(Source *)source {
2683 return [self source] == source && [self visible];
2688 /* Section Class {{{ */
2689 @interface Section : NSObject {
2694 NSString *localized_;
2697 - (NSComparisonResult) compareByLocalized:(Section *)section;
2698 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2699 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2700 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2701 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2702 - (NSString *) name;
2709 - (void) addToCount;
2711 - (void) setCount:(size_t)count;
2712 - (NSString *) localized;
2716 @implementation Section
2720 if (localized_ != nil)
2721 [localized_ release];
2725 - (NSComparisonResult) compareByLocalized:(Section *)section {
2726 NSString *lhs(localized_);
2727 NSString *rhs([section localized]);
2729 /*if ([lhs length] != 0 && [rhs length] != 0) {
2730 unichar lhc = [lhs characterAtIndex:0];
2731 unichar rhc = [rhs characterAtIndex:0];
2733 if (isalpha(lhc) && !isalpha(rhc))
2734 return NSOrderedAscending;
2735 else if (!isalpha(lhc) && isalpha(rhc))
2736 return NSOrderedDescending;
2739 return [lhs compare:rhs options:LaxCompareOptions_];
2742 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2743 if ((self = [self initWithName:name localize:NO]) != nil) {
2744 if (localized != nil)
2745 localized_ = [localized retain];
2749 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2750 return [self initWithName:name row:0 localize:localize];
2753 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2754 if ((self = [super init]) != nil) {
2755 name_ = [name retain];
2759 localized_ = [LocalizeSection(name_) retain];
2763 /* XXX: localize the index thingees */
2764 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2765 if ((self = [super init]) != nil) {
2766 name_ = [(index == '#' ? @"123" : [NSString stringWithCharacters:&index length:1]) retain];
2772 - (NSString *) name {
2792 - (void) addToCount {
2796 - (void) setCount:(size_t)count {
2800 - (NSString *) localized {
2808 static NSArray *Finishes_;
2810 /* Database Implementation {{{ */
2811 @implementation Database
2813 + (Database *) sharedInstance {
2814 static Database *instance;
2815 if (instance == nil)
2816 instance = [[Database alloc] init];
2826 NSRecycleZone(zone_);
2827 // XXX: malloc_destroy_zone(zone_);
2828 apr_pool_destroy(pool_);
2832 - (void) _readCydia:(NSNumber *)fd { _pooled
2833 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2834 std::istream is(&ib);
2837 static Pcre finish_r("^finish:([^:]*)$");
2839 while (std::getline(is, line)) {
2840 const char *data(line.c_str());
2841 size_t size = line.size();
2842 lprintf("C:%s\n", data);
2844 if (finish_r(data, size)) {
2845 NSString *finish = finish_r[1];
2846 int index = [Finishes_ indexOfObject:finish];
2847 if (index != INT_MAX && index > Finish_)
2855 - (void) _readStatus:(NSNumber *)fd { _pooled
2856 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2857 std::istream is(&ib);
2860 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2861 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2863 while (std::getline(is, line)) {
2864 const char *data(line.c_str());
2865 size_t size = line.size();
2866 lprintf("S:%s\n", data);
2868 if (conffile_r(data, size)) {
2869 [delegate_ setConfigurationData:conffile_r[1]];
2870 } else if (strncmp(data, "status: ", 8) == 0) {
2871 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2872 [delegate_ setProgressTitle:string];
2873 } else if (pmstatus_r(data, size)) {
2874 std::string type([pmstatus_r[1] UTF8String]);
2875 NSString *id = pmstatus_r[2];
2877 float percent([pmstatus_r[3] floatValue]);
2878 [delegate_ setProgressPercent:(percent / 100)];
2880 NSString *string = pmstatus_r[4];
2882 if (type == "pmerror")
2883 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2884 withObject:[NSArray arrayWithObjects:string, id, nil]
2887 else if (type == "pmstatus") {
2888 [delegate_ setProgressTitle:string];
2889 } else if (type == "pmconffile")
2890 [delegate_ setConfigurationData:string];
2891 else _assert(false);
2892 } else _assert(false);
2898 - (void) _readOutput:(NSNumber *)fd { _pooled
2899 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2900 std::istream is(&ib);
2903 while (std::getline(is, line)) {
2904 lprintf("O:%s\n", line.c_str());
2905 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2915 - (Package *) packageWithName:(NSString *)name {
2916 if (static_cast<pkgDepCache *>(cache_) == NULL)
2918 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
2919 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
2922 - (Database *) init {
2923 if ((self = [super init]) != nil) {
2930 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
2931 apr_pool_create(&pool_, NULL);
2933 sources_ = [[NSMutableDictionary dictionaryWithCapacity:16] retain];
2934 packages_ = [[NSMutableArray alloc] init];
2938 _assert(pipe(fds) != -1);
2941 _config->Set("APT::Keep-Fds::", cydiafd_);
2942 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
2945 detachNewThreadSelector:@selector(_readCydia:)
2947 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2950 _assert(pipe(fds) != -1);
2954 detachNewThreadSelector:@selector(_readStatus:)
2956 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2959 _assert(pipe(fds) != -1);
2960 _assert(dup2(fds[0], 0) != -1);
2961 _assert(close(fds[0]) != -1);
2963 input_ = fdopen(fds[1], "a");
2965 _assert(pipe(fds) != -1);
2966 _assert(dup2(fds[1], 1) != -1);
2967 _assert(close(fds[1]) != -1);
2970 detachNewThreadSelector:@selector(_readOutput:)
2972 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2977 - (pkgCacheFile &) cache {
2981 - (pkgDepCache::Policy *) policy {
2985 - (pkgRecords *) records {
2989 - (pkgProblemResolver *) resolver {
2993 - (pkgAcquire &) fetcher {
2997 - (pkgSourceList &) list {
3001 - (NSArray *) packages {
3005 - (NSArray *) sources {
3006 return [sources_ allValues];
3009 - (NSArray *) issues {
3010 if (cache_->BrokenCount() == 0)
3013 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3015 for (Package *package in packages_) {
3016 if (![package broken])
3018 pkgCache::PkgIterator pkg([package iterator]);
3020 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3021 [entry addObject:[package name]];
3022 [issues addObject:entry];
3024 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3028 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3029 pkgCache::DepIterator start;
3030 pkgCache::DepIterator end;
3031 dep.GlobOr(start, end); // ++dep
3033 if (!cache_->IsImportantDep(end))
3035 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3038 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3039 [entry addObject:failure];
3040 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3042 Package *package([self packageWithName:[NSString stringWithUTF8String:start.TargetPkg().Name()]]);
3043 [failure addObject:[package name]];
3045 pkgCache::PkgIterator target(start.TargetPkg());
3046 if (target->ProvidesList != 0)
3047 [failure addObject:@"?"];
3049 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3051 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3052 else if (!cache_[target].CandidateVerIter(cache_).end())
3053 [failure addObject:@"-"];
3054 else if (target->ProvidesList == 0)
3055 [failure addObject:@"!"];
3057 [failure addObject:@"%"];
3061 if (start.TargetVer() != 0)
3062 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3073 - (void) reloadData { _pooled
3074 @synchronized (self) {
3096 apr_pool_clear(pool_);
3097 NSRecycleZone(zone_);
3099 int chk(creat("/tmp/cydia.chk", 0644));
3104 if (!cache_.Open(progress_, true)) {
3106 if (!_error->PopMessage(error))
3109 lprintf("cache_.Open():[%s]\n", error.c_str());
3111 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3112 [delegate_ repairWithSelector:@selector(configure)];
3113 else if (error == "The package lists or status file could not be parsed or opened.")
3114 [delegate_ repairWithSelector:@selector(update)];
3115 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3116 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3117 // else if (error == "The list of sources could not be read.")
3118 else _assert(false);
3124 unlink("/tmp/cydia.chk");
3126 now_ = [[NSDate date] retain];
3128 policy_ = new pkgDepCache::Policy();
3129 records_ = new pkgRecords(cache_);
3130 resolver_ = new pkgProblemResolver(cache_);
3131 fetcher_ = new pkgAcquire(&status_);
3134 list_ = new pkgSourceList();
3135 _assert(list_->ReadMainList());
3137 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3138 _assert(pkgApplyStatus(cache_));
3140 if (cache_->BrokenCount() != 0) {
3141 _assert(pkgFixBroken(cache_));
3142 _assert(cache_->BrokenCount() == 0);
3143 _assert(pkgMinimizeUpgrade(cache_));
3148 std::string lists(_config->FindDir("Dir::State::lists"));
3150 [sources_ removeAllObjects];
3151 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3152 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3153 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3154 if (debPackagesIndex *packages = dynamic_cast<debPackagesIndex *>(*index))
3156 setObject:[[[Source alloc] initWithMetaIndex:*source] autorelease]
3157 forKey:[NSString stringWithFormat:@"%s%s",
3159 URItoFileName(packages->IndexURI("Packages")).c_str()
3167 /*std::vector<Package *> packages;
3168 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3169 [packages_ release];
3172 [packages_ removeAllObjects];
3176 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3177 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3178 //packages.push_back(package);
3179 [packages_ addObject:package];
3183 /*if (packages.empty())
3184 packages_ = [[NSArray alloc] init];
3186 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3189 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3190 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3191 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3199 /*if (!packages.empty())
3200 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3201 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3203 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3205 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3207 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3213 - (void) configure {
3214 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3215 system([dpkg UTF8String]);
3223 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3224 _assert(!_error->PendingError());
3227 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3230 public pkgArchiveCleaner
3233 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3238 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3240 while (_error->PopMessage(error))
3241 lprintf("ArchiveCleaner: %s\n", error.c_str());
3246 pkgRecords records(cache_);
3248 lock_ = new FileFd();
3249 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3250 _assert(!_error->PendingError());
3253 // XXX: explain this with an error message
3254 _assert(list.ReadMainList());
3256 manager_ = (_system->CreatePM(cache_));
3257 _assert(manager_->GetArchives(fetcher_, &list, &records));
3258 _assert(!_error->PendingError());
3262 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3264 _assert(list.ReadMainList());
3265 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3266 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3269 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3274 bool failed = false;
3275 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3276 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3279 std::string uri = (*item)->DescURI();
3280 std::string error = (*item)->ErrorText;
3282 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3285 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3286 withObject:[NSArray arrayWithObjects:
3287 [NSString stringWithUTF8String:error.c_str()],
3299 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3301 if (_error->PendingError()) {
3306 if (result == pkgPackageManager::Failed) {
3311 if (result != pkgPackageManager::Completed) {
3316 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3318 _assert(list.ReadMainList());
3319 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3320 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3323 if (![before isEqualToArray:after])
3328 _assert(pkgDistUpgrade(cache_));
3332 [self updateWithStatus:status_];
3335 - (void) updateWithStatus:(Status &)status {
3337 _assert(list.ReadMainList());
3340 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3341 _assert(!_error->PendingError());
3343 pkgAcquire fetcher(&status);
3344 _assert(list.GetIndexes(&fetcher));
3346 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3347 bool failed = false;
3348 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3349 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3350 (*item)->Finished();
3354 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3355 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3356 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3359 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3364 - (void) setDelegate:(id)delegate {
3365 delegate_ = delegate;
3366 status_.setDelegate(delegate);
3367 progress_.setDelegate(delegate);
3370 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3371 if (const char *name = file.FileName())
3372 if (Source *source = [sources_ objectForKey:[NSString stringWithUTF8String:name]])
3380 /* PopUp Windows {{{ */
3381 @interface PopUpView : UIView {
3382 _transient id delegate_;
3383 UITransitionView *transition_;
3388 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3392 @implementation PopUpView
3395 [transition_ setDelegate:nil];
3396 [transition_ release];
3402 [transition_ transition:UITransitionPushFromTop toView:nil];
3405 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3406 if (from != nil && to == nil)
3407 [self removeFromSuperview];
3410 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3411 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3412 delegate_ = delegate;
3414 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3415 [self addSubview:transition_];
3417 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3419 [view addSubview:self];
3421 [transition_ setDelegate:self];
3423 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3424 [transition_ transition:UITransitionNone toView:blank];
3425 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3433 /* Mail Composition {{{ */
3434 @interface MailToView : PopUpView {
3435 MailComposeController *controller_;
3438 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
3442 @implementation MailToView
3445 [controller_ release];
3449 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
3453 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
3454 NSLog(@"did:%@", delivery);
3455 // [UIApp setStatusBarShowsProgress:NO];
3456 if ([controller error]){
3457 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3458 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3459 [mailAlertSheet setBodyText:[controller error]];
3460 [mailAlertSheet popupAlertAnimated:YES];
3464 - (void) showError {
3465 NSLog(@"%@", [controller_ error]);
3466 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3467 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3468 [mailAlertSheet setBodyText:[controller_ error]];
3469 [mailAlertSheet popupAlertAnimated:YES];
3472 - (void) deliverMessage { _pooled
3476 if (![controller_ deliverMessage])
3477 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
3480 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
3481 if ([controller_ needsDelivery])
3482 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
3487 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
3488 if ((self = [super initWithView:view delegate:delegate]) != nil) {
3489 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
3490 [controller_ setDelegate:self];
3491 [controller_ initializeUI];
3492 [controller_ setupForURL:url];
3494 UIView *view([controller_ view]);
3495 [overlay_ addSubview:view];
3503 /* Confirmation View {{{ */
3504 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3505 if (!iterator.end())
3506 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3507 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3509 pkgCache::PkgIterator package(dep.TargetPkg());
3512 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3519 @protocol ConfirmationViewDelegate
3525 @interface ConfirmationView : BrowserView {
3526 _transient Database *database_;
3527 UIActionSheet *essential_;
3534 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3538 @implementation ConfirmationView
3545 if (essential_ != nil)
3546 [essential_ release];
3552 [book_ popFromSuperviewAnimated:YES];
3555 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3556 NSString *context([sheet context]);
3558 if ([context isEqualToString:@"remove"]) {
3566 [delegate_ confirm];
3573 } else if ([context isEqualToString:@"unable"]) {
3577 [super alertSheet:sheet buttonClicked:button];
3580 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3581 [super webView:sender didClearWindowObject:window forFrame:frame];
3582 [window setValue:changes_ forKey:@"changes"];
3583 [window setValue:issues_ forKey:@"issues"];
3584 [window setValue:sizes_ forKey:@"sizes"];
3587 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3588 if ((self = [super initWithBook:book]) != nil) {
3589 database_ = database;
3591 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3592 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3593 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3594 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3595 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3599 pkgDepCache::Policy *policy([database_ policy]);
3601 pkgCacheFile &cache([database_ cache]);
3602 NSArray *packages = [database_ packages];
3603 for (Package *package in packages) {
3604 pkgCache::PkgIterator iterator = [package iterator];
3605 pkgDepCache::StateCache &state(cache[iterator]);
3607 NSString *name([package name]);
3609 if (state.NewInstall())
3610 [installing addObject:name];
3611 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3612 [reinstalling addObject:name];
3613 else if (state.Upgrade())
3614 [upgrading addObject:name];
3615 else if (state.Downgrade())
3616 [downgrading addObject:name];
3617 else if (state.Delete()) {
3618 if ([package essential])
3620 [removing addObject:name];
3623 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3624 substrate_ |= DepSubstrate(iterator.CurrentVer());
3629 else if (Advanced_ || true) {
3630 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
3632 essential_ = [[UIActionSheet alloc]
3633 initWithTitle:CYLocalize("REMOVING_ESSENTIALS")
3634 buttons:[NSArray arrayWithObjects:
3635 [NSString stringWithFormat:parenthetical, CYLocalize("CANCEL_OPERATION"), CYLocalize("SAFE")],
3636 [NSString stringWithFormat:parenthetical, CYLocalize("FORCE_REMOVAL"), CYLocalize("UNSAFE")],
3638 defaultButtonIndex:0
3644 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3646 [essential_ setBodyText:CYLocalize("REMOVING_ESSENTIALS_EX")];
3648 essential_ = [[UIActionSheet alloc]
3649 initWithTitle:CYLocalize("UNABLE_TO_COMPLY")
3650 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3651 defaultButtonIndex:0
3656 [essential_ setBodyText:CYLocalize("UNABLE_TO_COMPLY_EX")];
3659 changes_ = [[NSArray alloc] initWithObjects:
3667 issues_ = [database_ issues];
3669 issues_ = [issues_ retain];
3671 sizes_ = [[NSArray alloc] initWithObjects:
3672 SizeString([database_ fetcher].FetchNeeded()),
3673 SizeString([database_ fetcher].PartialPresent()),
3674 SizeString([database_ cache]->UsrSize()),
3677 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3681 - (NSString *) backButtonTitle {
3682 return CYLocalize("CONFIRM");
3685 - (NSString *) leftButtonTitle {
3686 return [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("CANCEL"), CYLocalize("QUEUE")];
3689 - (id) rightButtonTitle {
3690 return issues_ != nil ? nil : [super rightButtonTitle];
3693 - (id) _rightButtonTitle {
3694 #if AlwaysReload || IgnoreInstall
3695 return [super _rightButtonTitle];
3697 return CYLocalize("CONFIRM");
3701 - (void) _leftButtonClicked {
3706 - (void) _rightButtonClicked {
3708 return [super _rightButtonClicked];
3710 if (essential_ != nil)
3711 [essential_ popupAlertAnimated:YES];
3715 [delegate_ confirm];
3723 /* Progress Data {{{ */
3724 @interface ProgressData : NSObject {
3730 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3737 @implementation ProgressData
3739 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3740 if ((self = [super init]) != nil) {
3741 selector_ = selector;
3761 /* Progress View {{{ */
3762 @interface ProgressView : UIView <
3763 ConfigurationDelegate,
3766 _transient Database *database_;
3768 UIView *background_;
3769 UITransitionView *transition_;
3771 UINavigationBar *navbar_;
3772 UIProgressBar *progress_;
3773 UITextView *output_;
3774 UITextLabel *status_;
3775 UIPushButton *close_;
3778 SHA1SumValue springlist_;
3779 SHA1SumValue notifyconf_;
3780 SHA1SumValue sandplate_;
3783 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
3785 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
3786 - (void) setContentView:(UIView *)view;
3789 - (void) _retachThread;
3790 - (void) _detachNewThreadData:(ProgressData *)data;
3791 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
3797 @protocol ProgressViewDelegate
3798 - (void) progressViewIsComplete:(ProgressView *)sender;
3801 @implementation ProgressView
3804 [transition_ setDelegate:nil];
3805 [navbar_ setDelegate:nil];
3808 if (background_ != nil)
3809 [background_ release];
3810 [transition_ release];
3813 [progress_ release];
3820 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3821 if (bootstrap_ && from == overlay_ && to == view_)
3825 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
3826 if ((self = [super initWithFrame:frame]) != nil) {
3827 database_ = database;
3828 delegate_ = delegate;
3830 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3831 [transition_ setDelegate:self];
3833 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3836 [overlay_ setBackgroundColor:[UIColor blackColor]];
3838 background_ = [[UIView alloc] initWithFrame:[self bounds]];
3839 [background_ setBackgroundColor:[UIColor blackColor]];
3840 [self addSubview:background_];
3843 [self addSubview:transition_];
3845 CGSize navsize = [UINavigationBar defaultSize];
3846 CGRect navrect = {{0, 0}, navsize};
3848 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
3849 [overlay_ addSubview:navbar_];
3851 [navbar_ setBarStyle:1];
3852 [navbar_ setDelegate:self];
3854 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
3855 [navbar_ pushNavigationItem:navitem];
3857 CGRect bounds = [overlay_ bounds];
3858 CGSize prgsize = [UIProgressBar defaultSize];
3861 (bounds.size.width - prgsize.width) / 2,
3862 bounds.size.height - prgsize.height - 20
3865 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3866 [progress_ setStyle:0];
3868 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3870 bounds.size.height - prgsize.height - 50,
3871 bounds.size.width - 20,
3875 [status_ setColor:[UIColor whiteColor]];
3876 [status_ setBackgroundColor:[UIColor clearColor]];
3878 [status_ setCentersHorizontally:YES];
3879 //[status_ setFont:font];
3882 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3884 navrect.size.height + 20,
3885 bounds.size.width - 20,
3886 bounds.size.height - navsize.height - 62 - navrect.size.height
3890 //[output_ setTextFont:@"Courier New"];
3891 [output_ setTextSize:12];
3893 [output_ setTextColor:[UIColor whiteColor]];
3894 [output_ setBackgroundColor:[UIColor clearColor]];
3896 [output_ setMarginTop:0];
3897 [output_ setAllowsRubberBanding:YES];
3898 [output_ setEditable:NO];
3900 [overlay_ addSubview:output_];
3902 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3904 bounds.size.height - prgsize.height - 50,
3905 bounds.size.width - 20,
3909 [close_ setAutosizesToFit:NO];
3910 [close_ setDrawsShadow:YES];
3911 [close_ setStretchBackground:YES];
3912 [close_ setEnabled:YES];
3914 UIFont *bold = [UIFont boldSystemFontOfSize:22];
3915 [close_ setTitleFont:bold];
3917 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
3918 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
3919 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
3923 - (void) setContentView:(UIView *)view {
3924 view_ = [view retain];
3927 - (void) resetView {
3928 [transition_ transition:6 toView:view_];
3931 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3932 NSString *context([sheet context]);
3934 if ([context isEqualToString:@"error"])
3936 else if ([context isEqualToString:@"conffile"]) {
3937 FILE *input = [database_ input];
3941 fprintf(input, "N\n");
3945 fprintf(input, "Y\n");
3956 - (void) closeButtonPushed {
3965 [delegate_ suspendWithAnimation:YES];
3969 system("launchctl stop com.apple.SpringBoard");
3973 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
3982 - (void) _retachThread {
3983 UINavigationItem *item = [navbar_ topItem];
3984 [item setTitle:CYLocalize("COMPLETE")];
3986 [overlay_ addSubview:close_];
3987 [progress_ removeFromSuperview];
3988 [status_ removeFromSuperview];
3990 [delegate_ progressViewIsComplete:self];
3993 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
3994 MMap mmap(file, MMap::ReadOnly);
3996 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3997 if (!(sandplate_ == sha1.Result()))
4002 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4003 MMap mmap(file, MMap::ReadOnly);
4005 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4006 if (!(notifyconf_ == sha1.Result()))
4011 FileFd file(SpringBoard_, FileFd::ReadOnly);
4012 MMap mmap(file, MMap::ReadOnly);
4014 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4015 if (!(springlist_ == sha1.Result()))
4020 case 0: [close_ setTitle:CYLocalize("RETURN_TO_CYDIA")]; break;
4021 case 1: [close_ setTitle:CYLocalize("CLOSE_CYDIA")]; break;
4022 case 2: [close_ setTitle:CYLocalize("RESTART_SPRINGBOARD")]; break;
4023 case 3: [close_ setTitle:CYLocalize("RELOAD_SPRINGBOARD")]; break;
4024 case 4: [close_ setTitle:CYLocalize("REBOOT_DEVICE")]; break;
4027 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4029 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
4030 [cache autorelease];
4032 NSFileManager *manager = [NSFileManager defaultManager];
4033 NSError *error = nil;
4035 id system = [cache objectForKey:@"System"];
4040 if (stat(Cache_, &info) == -1)
4043 [system removeAllObjects];
4045 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4046 for (NSString *app in apps)
4047 if ([app hasSuffix:@".app"]) {
4048 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4049 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4050 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4052 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4053 [info setObject:path forKey:@"Path"];
4054 [info setObject:@"System" forKey:@"ApplicationType"];
4055 [system addInfoDictionary:info];
4061 [cache writeToFile:@Cache_ atomically:YES];
4063 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
4065 if (chmod(Cache_, info.st_mode) == -1)
4069 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4072 notify_post("com.apple.mobile.application_installed");
4074 [delegate_ setStatusBarShowsProgress:NO];
4077 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4078 [[data target] performSelector:[data selector] withObject:[data object]];
4081 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4084 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4085 UINavigationItem *item = [navbar_ topItem];
4086 [item setTitle:title];
4088 [status_ setText:nil];
4089 [output_ setText:@""];
4090 [progress_ setProgress:0];
4092 [close_ removeFromSuperview];
4093 [overlay_ addSubview:progress_];
4094 [overlay_ addSubview:status_];
4096 [delegate_ setStatusBarShowsProgress:YES];
4100 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4101 MMap mmap(file, MMap::ReadOnly);
4103 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4104 sandplate_ = sha1.Result();
4108 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4109 MMap mmap(file, MMap::ReadOnly);
4111 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4112 notifyconf_ = sha1.Result();
4116 FileFd file(SpringBoard_, FileFd::ReadOnly);
4117 MMap mmap(file, MMap::ReadOnly);
4119 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4120 springlist_ = sha1.Result();
4123 [transition_ transition:6 toView:overlay_];
4126 detachNewThreadSelector:@selector(_detachNewThreadData:)
4128 withObject:[[ProgressData alloc]
4129 initWithSelector:selector
4136 - (void) repairWithSelector:(SEL)selector {
4138 detachNewThreadSelector:selector
4141 title:CYLocalize("REPAIRING")
4145 - (void) setConfigurationData:(NSString *)data {
4147 performSelectorOnMainThread:@selector(_setConfigurationData:)
4153 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4154 Package *package = id == nil ? nil : [database_ packageWithName:id];
4156 UIActionSheet *sheet = [[[UIActionSheet alloc]
4157 initWithTitle:(package == nil ? id : [package name])
4158 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
4159 defaultButtonIndex:0
4164 [sheet setBodyText:error];
4165 [sheet popupAlertAnimated:YES];
4168 - (void) setProgressTitle:(NSString *)title {
4170 performSelectorOnMainThread:@selector(_setProgressTitle:)
4176 - (void) setProgressPercent:(float)percent {
4178 performSelectorOnMainThread:@selector(_setProgressPercent:)
4179 withObject:[NSNumber numberWithFloat:percent]
4184 - (void) startProgress {
4187 - (void) addProgressOutput:(NSString *)output {
4189 performSelectorOnMainThread:@selector(_addProgressOutput:)
4195 - (bool) isCancelling:(size_t)received {
4199 - (void) _setConfigurationData:(NSString *)data {
4200 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4202 _assert(conffile_r(data));
4204 NSString *ofile = conffile_r[1];
4205 //NSString *nfile = conffile_r[2];
4207 UIActionSheet *sheet = [[[UIActionSheet alloc]
4208 initWithTitle:CYLocalize("CONFIGURATION_UPGRADE")
4209 buttons:[NSArray arrayWithObjects:
4210 CYLocalize("KEEP_OLD_COPY"),
4211 CYLocalize("ACCEPT_NEW_COPY"),
4212 // XXX: CYLocalize("SEE_WHAT_CHANGED"),
4214 defaultButtonIndex:0
4219 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", CYLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4220 [sheet popupAlertAnimated:YES];
4223 - (void) _setProgressTitle:(NSString *)title {
4224 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4225 for (size_t i(0), e([words count]); i != e; ++i) {
4226 NSString *word([words objectAtIndex:i]);
4227 if (Package *package = [database_ packageWithName:word])
4228 [words replaceObjectAtIndex:i withObject:[package name]];
4231 [status_ setText:[words componentsJoinedByString:@" "]];
4234 - (void) _setProgressPercent:(NSNumber *)percent {
4235 [progress_ setProgress:[percent floatValue]];
4238 - (void) _addProgressOutput:(NSString *)output {
4239 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4240 CGSize size = [output_ contentSize];
4241 CGRect rect = {{0, size.height}, {size.width, 0}};
4242 [output_ scrollRectToVisible:rect animated:YES];
4245 - (BOOL) isRunning {
4252 /* Package Cell {{{ */
4253 @interface PackageCell : UITableCell {
4256 NSString *description_;
4263 UITextLabel *status_;
4267 - (PackageCell *) init;
4268 - (void) setPackage:(Package *)package;
4270 + (int) heightForPackage:(Package *)package;
4274 @implementation PackageCell
4276 - (void) clearPackage {
4287 if (description_ != nil) {
4288 [description_ release];
4292 if (source_ != nil) {
4297 if (badge_ != nil) {
4307 [self clearPackage];
4314 - (PackageCell *) init {
4315 if ((self = [super init]) != nil) {
4317 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4318 [status_ setBackgroundColor:[UIColor clearColor]];
4319 [status_ setFont:small];
4324 - (void) setPackage:(Package *)package {
4325 [self clearPackage];
4327 Source *source = [package source];
4329 icon_ = [[package icon] retain];
4330 name_ = [[package name] retain];
4331 description_ = [[package shortDescription] retain];
4332 commercial_ = [package isCommercial];
4334 package_ = [package retain];
4336 NSString *label = nil;
4337 bool trusted = false;
4339 if (source != nil) {
4340 label = [source label];
4341 trusted = [source trusted];
4342 } else if ([[package id] isEqualToString:@"firmware"])
4343 label = CYLocalize("APPLE");
4345 label = [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("UNKNOWN"), CYLocalize("LOCAL")];
4347 NSString *from(label);
4349 NSString *section = [package simpleSection];
4350 if (section != nil && ![section isEqualToString:label]) {
4351 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4352 from = [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), from, section];
4355 from = [NSString stringWithFormat:CYLocalize("FROM"), from];
4356 source_ = [from retain];
4358 if (NSString *purpose = [package primaryPurpose])
4359 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4360 badge_ = [badge_ retain];
4363 if (NSString *mode = [package mode]) {
4364 [badge_ setImage:[UIImage applicationImageNamed:
4365 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4368 [status_ setText:[NSString stringWithFormat:CYLocalize("QUEUED_FOR"), CYLocalize(mode)]];
4369 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4370 } else if ([package half]) {
4371 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4372 [status_ setText:CYLocalize("PACKAGE_DAMAGED")];
4373 [status_ setColor:[UIColor redColor]];
4375 [badge_ setImage:nil];
4376 [status_ setText:nil];
4383 - (void) drawRect:(CGRect)rect {
4387 if (NSString *mode = [package_ mode]) {
4388 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4389 color = remove ? RemovingColor_ : InstallingColor_;
4391 color = [UIColor whiteColor];
4393 [self setBackgroundColor:color];
4397 [super drawRect:rect];
4400 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4402 CGContextRef context(UIGraphicsGetCurrentContext());
4403 [[self backgroundColor] set];
4405 back.size.height -= 1;
4406 CGContextFillRect(context, back);
4409 [super drawBackgroundInRect:rect withFade:fade];
4412 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4415 rect.size = [icon_ size];
4417 rect.size.width /= 2;
4418 rect.size.height /= 2;
4420 rect.origin.x = 25 - rect.size.width / 2;
4421 rect.origin.y = 25 - rect.size.height / 2;
4423 [icon_ drawInRect:rect];
4426 if (badge_ != nil) {
4427 CGSize size = [badge_ size];
4429 [badge_ drawAtPoint:CGPointMake(
4430 36 - size.width / 2,
4431 36 - size.height / 2
4439 UISetColor(commercial_ ? Purple_ : Black_);
4440 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4441 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4444 UISetColor(commercial_ ? Purplish_ : Gray_);
4445 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4447 [super drawContentInRect:rect selected:selected];
4450 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4452 [super setSelected:selected withFade:fade];
4455 + (int) heightForPackage:(Package *)package {
4456 NSString *tagline([package shortDescription]);
4457 int height = tagline == nil || [tagline length] == 0 ? -17 : 0;
4459 if ([package hasMode] || [package half])
4468 /* Section Cell {{{ */
4469 @interface SectionCell : UISimpleTableCell {
4474 _UISwitchSlider *switch_;
4479 - (void) setSection:(Section *)section editing:(BOOL)editing;
4483 @implementation SectionCell
4485 - (void) clearSection {
4486 if (section_ != nil) {
4496 if (count_ != nil) {
4503 [self clearSection];
4510 if ((self = [super init]) != nil) {
4511 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4513 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4514 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4518 - (void) onSwitch:(id)sender {
4519 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4520 if (metadata == nil) {
4521 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4522 [Sections_ setObject:metadata forKey:section_];
4526 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4529 - (void) setSection:(Section *)section editing:(BOOL)editing {
4530 if (editing != editing_) {
4532 [switch_ removeFromSuperview];
4534 [self addSubview:switch_];
4538 [self clearSection];
4540 if (section == nil) {
4541 name_ = [CYLocalize("ALL_PACKAGES") retain];
4544 section_ = [section localized];
4545 if (section_ != nil)
4546 section_ = [section_ retain];
4547 name_ = [(section_ == nil ? CYLocalize("NO_SECTION") : section_) retain];
4548 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4551 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4555 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4556 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4563 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4565 CGSize size = [count_ sizeWithFont:Font14_];
4569 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4571 [super drawContentInRect:rect selected:selected];
4577 /* File Table {{{ */
4578 @interface FileTable : RVPage {
4579 _transient Database *database_;
4582 NSMutableArray *files_;
4586 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4587 - (void) setPackage:(Package *)package;
4591 @implementation FileTable
4594 if (package_ != nil)
4603 - (int) numberOfRowsInTable:(UITable *)table {
4604 return files_ == nil ? 0 : [files_ count];
4607 - (float) table:(UITable *)table heightForRow:(int)row {
4611 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4612 if (reusing == nil) {
4613 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4614 UIFont *font = [UIFont systemFontOfSize:16];
4615 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4617 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4621 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4625 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4626 if ((self = [super initWithBook:book]) != nil) {
4627 database_ = database;
4629 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4631 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4632 [self addSubview:list_];
4634 UITableColumn *column = [[[UITableColumn alloc]
4635 initWithTitle:CYLocalize("NAME")
4637 width:[self frame].size.width
4640 [list_ setDataSource:self];
4641 [list_ setSeparatorStyle:1];
4642 [list_ addTableColumn:column];
4643 [list_ setDelegate:self];
4644 [list_ setReusesTableCells:YES];
4648 - (void) setPackage:(Package *)package {
4649 if (package_ != nil) {
4650 [package_ autorelease];
4659 [files_ removeAllObjects];
4661 if (package != nil) {
4662 package_ = [package retain];
4663 name_ = [[package id] retain];
4665 if (NSArray *files = [package files])
4666 [files_ addObjectsFromArray:files];
4668 if ([files_ count] != 0) {
4669 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4670 [files_ removeObjectAtIndex:0];
4671 [files_ sortUsingSelector:@selector(compareByPath:)];
4673 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4674 [stack addObject:@"/"];
4676 for (int i(0), e([files_ count]); i != e; ++i) {
4677 NSString *file = [files_ objectAtIndex:i];
4678 while (![file hasPrefix:[stack lastObject]])
4679 [stack removeLastObject];
4680 NSString *directory = [stack lastObject];
4681 [stack addObject:[file stringByAppendingString:@"/"]];
4682 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4683 ([stack count] - 2) * 3, "",
4684 [file substringFromIndex:[directory length]]
4693 - (void) resetViewAnimated:(BOOL)animated {
4694 [list_ resetViewAnimated:animated];
4697 - (void) reloadData {
4698 [self setPackage:[database_ packageWithName:name_]];
4699 [self reloadButtons];
4702 - (NSString *) title {
4703 return CYLocalize("INSTALLED_FILES");
4706 - (NSString *) backButtonTitle {
4707 return CYLocalize("FILES");
4712 /* Package View {{{ */
4713 @interface PackageView : BrowserView {
4714 _transient Database *database_;
4718 NSMutableArray *buttons_;
4721 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4722 - (void) setPackage:(Package *)package;
4726 @implementation PackageView
4729 if (package_ != nil)
4738 if ([self retainCount] == 1)
4739 [delegate_ setPackageView:self];
4743 /* XXX: this is not safe at all... localization of /fail/ */
4744 - (void) _clickButtonWithName:(NSString *)name {
4745 if ([name isEqualToString:CYLocalize("CLEAR")])
4746 [delegate_ clearPackage:package_];
4747 else if ([name isEqualToString:CYLocalize("INSTALL")])
4748 [delegate_ installPackage:package_];
4749 else if ([name isEqualToString:CYLocalize("REINSTALL")])
4750 [delegate_ installPackage:package_];
4751 else if ([name isEqualToString:CYLocalize("REMOVE")])
4752 [delegate_ removePackage:package_];
4753 else if ([name isEqualToString:CYLocalize("UPGRADE")])
4754 [delegate_ installPackage:package_];
4755 else _assert(false);
4758 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4759 NSString *context([sheet context]);
4761 if ([context isEqualToString:@"modify"]) {
4762 int count = [buttons_ count];
4763 _assert(count != 0);
4764 _assert(button <= count + 1);
4766 if (count != button - 1)
4767 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
4771 [super alertSheet:sheet buttonClicked:button];
4774 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
4775 return [super webView:sender didFinishLoadForFrame:frame];
4778 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4779 [super webView:sender didClearWindowObject:window forFrame:frame];
4780 [window setValue:package_ forKey:@"package"];
4783 - (bool) _allowJavaScriptPanel {
4788 - (void) __rightButtonClicked {
4789 int count = [buttons_ count];
4790 _assert(count != 0);
4793 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
4795 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
4796 [buttons addObjectsFromArray:buttons_];
4797 [buttons addObject:CYLocalize("CANCEL")];
4799 [delegate_ slideUp:[[[UIActionSheet alloc]
4802 defaultButtonIndex:([buttons count] - 1)
4809 - (void) _rightButtonClicked {
4811 [super _rightButtonClicked];
4813 [self __rightButtonClicked];
4817 - (id) _rightButtonTitle {
4818 int count = [buttons_ count];
4819 return count == 0 ? nil : count != 1 ? CYLocalize("MODIFY") : [buttons_ objectAtIndex:0];
4822 - (NSString *) backButtonTitle {
4826 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4827 if ((self = [super initWithBook:book]) != nil) {
4828 database_ = database;
4829 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
4830 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
4834 - (void) setPackage:(Package *)package {
4835 if (package_ != nil) {
4836 [package_ autorelease];
4845 [buttons_ removeAllObjects];
4847 if (package != nil) {
4848 package_ = [package retain];
4849 name_ = [[package id] retain];
4850 commercial_ = [package isCommercial];
4852 if ([package_ mode] != nil)
4853 [buttons_ addObject:CYLocalize("CLEAR")];
4854 if ([package_ source] == nil);
4855 else if ([package_ upgradableAndEssential:NO])
4856 [buttons_ addObject:CYLocalize("UPGRADE")];
4857 else if ([package_ installed] == nil)
4858 [buttons_ addObject:CYLocalize("INSTALL")];
4860 [buttons_ addObject:CYLocalize("REINSTALL")];
4861 if ([package_ installed] != nil)
4862 [buttons_ addObject:CYLocalize("REMOVE")];
4864 if (special_ != NULL) {
4865 CGRect frame([webview_ frame]);
4866 frame.size.width = 320;
4867 frame.size.height = 0;
4868 [webview_ setFrame:frame];
4870 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
4873 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
4875 [self setButtonTitle:nil withStyle:nil toFunction:nil];
4877 [self setFinishHook:nil];
4878 [self setPopupHook:nil];
4881 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
4882 [super callFunction:special_];
4886 [self reloadButtons];
4889 - (bool) isLoading {
4890 return commercial_ ? [super isLoading] : false;
4893 - (void) reloadData {
4894 [self setPackage:[database_ packageWithName:name_]];
4899 /* Package Table {{{ */
4900 @interface PackageTable : RVPage {
4901 _transient Database *database_;
4903 NSMutableArray *packages_;
4904 NSMutableArray *sections_;
4905 UISectionList *list_;
4908 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
4910 - (void) setDelegate:(id)delegate;
4912 - (void) reloadData;
4913 - (void) resetCursor;
4915 - (UISectionList *) list;
4917 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
4921 @implementation PackageTable
4924 [list_ setDataSource:nil];
4927 [packages_ release];
4928 [sections_ release];
4933 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
4934 return [sections_ count];
4937 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
4938 return [[sections_ objectAtIndex:section] name];
4941 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
4942 return [[sections_ objectAtIndex:section] row];
4945 - (int) numberOfRowsInTable:(UITable *)table {
4946 return [packages_ count];
4949 - (float) table:(UITable *)table heightForRow:(int)row {
4950 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
4953 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4955 reusing = [[[PackageCell alloc] init] autorelease];
4956 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
4960 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
4964 - (void) tableRowSelected:(NSNotification *)notification {
4965 int row = [[notification object] selectedRow];
4969 Package *package = [packages_ objectAtIndex:row];
4970 package = [database_ packageWithName:[package id]];
4971 PackageView *view([delegate_ packageView]);
4972 [view setPackage:package];
4973 [view setDelegate:delegate_];
4974 [book_ pushPage:view];
4977 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
4978 if ((self = [super initWithBook:book]) != nil) {
4979 database_ = database;
4980 title_ = [title retain];
4982 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
4983 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
4985 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
4986 [list_ setDataSource:self];
4988 UITableColumn *column = [[[UITableColumn alloc]
4989 initWithTitle:CYLocalize("NAME")
4991 width:[self frame].size.width
4994 UITable *table = [list_ table];
4995 [table setSeparatorStyle:1];
4996 [table addTableColumn:column];
4997 [table setDelegate:self];
4998 [table setReusesTableCells:YES];
5000 [self addSubview:list_];
5002 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5003 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5007 - (void) setDelegate:(id)delegate {
5008 delegate_ = delegate;
5011 - (bool) hasPackage:(Package *)package {
5015 - (void) reloadData {
5016 NSArray *packages = [database_ packages];
5018 [packages_ removeAllObjects];
5019 [sections_ removeAllObjects];
5021 _profile(PackageTable$reloadData$Filter)
5022 for (Package *package in packages)
5023 if ([self hasPackage:package])
5024 [packages_ addObject:package];
5027 Section *section = nil;
5029 _profile(PackageTable$reloadData$Section)
5030 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5034 _profile(PackageTable$reloadData$Section$Package)
5035 package = [packages_ objectAtIndex:offset];
5036 index = [package index];
5039 if (section == nil || [section index] != index) {
5040 _profile(PackageTable$reloadData$Section$Allocate)
5041 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5044 _profile(PackageTable$reloadData$Section$Add)
5045 [sections_ addObject:section];
5049 [section addToCount];
5053 _profile(PackageTable$reloadData$List)
5058 - (NSString *) title {
5062 - (void) resetViewAnimated:(BOOL)animated {
5063 [list_ resetViewAnimated:animated];
5066 - (void) resetCursor {
5067 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
5070 - (UISectionList *) list {
5074 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5075 [list_ setShouldHideHeaderInShortLists:hide];
5080 /* Filtered Package Table {{{ */
5081 @interface FilteredPackageTable : PackageTable {
5087 - (void) setObject:(id)object;
5089 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5093 @implementation FilteredPackageTable
5101 - (void) setObject:(id)object {
5107 object_ = [object retain];
5110 - (bool) hasPackage:(Package *)package {
5111 _profile(FilteredPackageTable$hasPackage)
5112 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5116 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5117 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5119 object_ = object == nil ? nil : [object retain];
5121 /* XXX: this is an unsafe optimization of doomy hell */
5122 Method method = class_getInstanceMethod([Package class], filter);
5123 _assert(method != NULL);
5124 imp_ = method_getImplementation(method);
5125 _assert(imp_ != NULL);
5134 /* Add Source View {{{ */
5135 @interface AddSourceView : RVPage {
5136 _transient Database *database_;
5139 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5143 @implementation AddSourceView
5145 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5146 if ((self = [super initWithBook:book]) != nil) {
5147 database_ = database;
5153 /* Source Cell {{{ */
5154 @interface SourceCell : UITableCell {
5157 NSString *description_;
5163 - (SourceCell *) initWithSource:(Source *)source;
5167 @implementation SourceCell
5172 [description_ release];
5177 - (SourceCell *) initWithSource:(Source *)source {
5178 if ((self = [super init]) != nil) {
5180 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5182 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5183 icon_ = [icon_ retain];
5185 origin_ = [[source name] retain];
5186 label_ = [[source uri] retain];
5187 description_ = [[source description] retain];
5191 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5193 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5200 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5204 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5208 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5210 [super drawContentInRect:rect selected:selected];
5215 /* Source Table {{{ */
5216 @interface SourceTable : RVPage {
5217 _transient Database *database_;
5218 UISectionList *list_;
5219 NSMutableArray *sources_;
5220 UIActionSheet *alert_;
5224 UIProgressHUD *hud_;
5227 //NSURLConnection *installer_;
5228 NSURLConnection *trivial_bz2_;
5229 NSURLConnection *trivial_gz_;
5230 //NSURLConnection *automatic_;
5235 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5239 @implementation SourceTable
5241 - (void) _deallocConnection:(NSURLConnection *)connection {
5242 if (connection != nil) {
5243 [connection cancel];
5244 //[connection setDelegate:nil];
5245 [connection release];
5250 [[list_ table] setDelegate:nil];
5251 [list_ setDataSource:nil];
5260 //[self _deallocConnection:installer_];
5261 [self _deallocConnection:trivial_gz_];
5262 [self _deallocConnection:trivial_bz2_];
5263 //[self _deallocConnection:automatic_];
5270 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5271 return offset_ == 0 ? 1 : 2;
5274 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5275 switch (section + (offset_ == 0 ? 1 : 0)) {
5276 case 0: return CYLocalize("ENTERED_BY_USER");
5277 case 1: return CYLocalize("INSTALLED_BY_PACKAGE");
5285 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5286 switch (section + (offset_ == 0 ? 1 : 0)) {
5288 case 1: return offset_;
5296 - (int) numberOfRowsInTable:(UITable *)table {
5297 return [sources_ count];
5300 - (float) table:(UITable *)table heightForRow:(int)row {
5301 Source *source = [sources_ objectAtIndex:row];
5302 return [source description] == nil ? 56 : 73;
5305 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5306 Source *source = [sources_ objectAtIndex:row];
5307 // XXX: weird warning, stupid selectors ;P
5308 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5311 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5315 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5319 - (void) tableRowSelected:(NSNotification*)notification {
5320 UITable *table([list_ table]);
5321 int row([table selectedRow]);
5325 Source *source = [sources_ objectAtIndex:row];
5327 PackageTable *packages = [[[FilteredPackageTable alloc]
5330 title:[source label]
5331 filter:@selector(isVisibleInSource:)
5335 [packages setDelegate:delegate_];
5337 [book_ pushPage:packages];
5340 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5341 Source *source = [sources_ objectAtIndex:row];
5342 return [source record] != nil;
5345 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5346 [[list_ table] setDeleteConfirmationRow:row];
5349 - (void) table:(UITable *)table deleteRow:(int)row {
5350 Source *source = [sources_ objectAtIndex:row];
5351 [Sources_ removeObjectForKey:[source key]];
5352 [delegate_ syncData];
5356 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5359 @"./", @"Distribution",
5360 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5362 [delegate_ syncData];
5365 - (NSString *) getWarning {
5366 NSString *href(href_);
5367 NSRange colon([href rangeOfString:@"://"]);
5368 if (colon.location != NSNotFound)
5369 href = [href substringFromIndex:(colon.location + 3)];
5370 href = [href stringByAddingPercentEscapes];
5371 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5372 href = [href stringByCachingURLWithCurrentCDN];
5374 NSURL *url([NSURL URLWithString:href]);
5376 NSStringEncoding encoding;
5377 NSError *error(nil);
5379 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5380 return [warning length] == 0 ? nil : warning;
5384 - (void) _endConnection:(NSURLConnection *)connection {
5385 NSURLConnection **field = NULL;
5386 if (connection == trivial_bz2_)
5387 field = &trivial_bz2_;
5388 else if (connection == trivial_gz_)
5389 field = &trivial_gz_;
5390 _assert(field != NULL);
5391 [connection release];
5395 trivial_bz2_ == nil &&
5401 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5404 UIActionSheet *sheet = [[[UIActionSheet alloc]
5405 initWithTitle:CYLocalize("SOURCE_WARNING")
5406 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_ANYWAY"), CYLocalize("CANCEL"), nil]
5407 defaultButtonIndex:0
5412 [sheet setNumberOfRows:1];
5414 [sheet setBodyText:warning];
5415 [sheet popupAlertAnimated:YES];
5418 } else if (error_ != nil) {
5419 UIActionSheet *sheet = [[[UIActionSheet alloc]
5420 initWithTitle:CYLocalize("VERIFICATION_ERROR")
5421 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5422 defaultButtonIndex:0
5427 [sheet setBodyText:[error_ localizedDescription]];
5428 [sheet popupAlertAnimated:YES];
5430 UIActionSheet *sheet = [[[UIActionSheet alloc]
5431 initWithTitle:CYLocalize("NOT_REPOSITORY")
5432 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5433 defaultButtonIndex:0
5438 [sheet setBodyText:CYLocalize("NOT_REPOSITORY_EX")];
5439 [sheet popupAlertAnimated:YES];
5442 [delegate_ setStatusBarShowsProgress:NO];
5443 [delegate_ removeProgressHUD:hud_];
5453 if (error_ != nil) {
5460 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5461 switch ([response statusCode]) {
5467 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5468 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5470 error_ = [error retain];
5471 [self _endConnection:connection];
5474 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5475 [self _endConnection:connection];
5478 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5479 NSMutableURLRequest *request = [NSMutableURLRequest
5480 requestWithURL:[NSURL URLWithString:href]
5481 cachePolicy:NSURLRequestUseProtocolCachePolicy
5482 timeoutInterval:20.0
5485 [request setHTTPMethod:method];
5487 if (Machine_ != NULL)
5488 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5489 if (UniqueID_ != nil)
5490 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5493 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5495 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5498 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5499 NSString *context([sheet context]);
5501 if ([context isEqualToString:@"source"]) {
5504 NSString *href = [[sheet textField] text];
5506 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5508 if (![href hasSuffix:@"/"])
5509 href_ = [href stringByAppendingString:@"/"];
5512 href_ = [href_ retain];
5514 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5515 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5516 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5520 hud_ = [[delegate_ addProgressHUD] retain];
5521 [hud_ setText:CYLocalize("VERIFYING_URL")];
5532 } else if ([context isEqualToString:@"trivial"])
5534 else if ([context isEqualToString:@"urlerror"])
5536 else if ([context isEqualToString:@"warning"]) {
5556 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5557 if ((self = [super initWithBook:book]) != nil) {
5558 database_ = database;
5559 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5561 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5562 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5563 [list_ setShouldHideHeaderInShortLists:NO];
5565 [self addSubview:list_];
5566 [list_ setDataSource:self];
5568 UITableColumn *column = [[UITableColumn alloc]
5569 initWithTitle:CYLocalize("NAME")
5571 width:[self frame].size.width
5574 UITable *table = [list_ table];
5575 [table setSeparatorStyle:1];
5576 [table addTableColumn:column];
5577 [table setDelegate:self];
5581 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5582 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5586 - (void) reloadData {
5588 _assert(list.ReadMainList());
5590 [sources_ removeAllObjects];
5591 [sources_ addObjectsFromArray:[database_ sources]];
5593 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5596 int count = [sources_ count];
5597 for (offset_ = 0; offset_ != count; ++offset_) {
5598 Source *source = [sources_ objectAtIndex:offset_];
5599 if ([source record] == nil)
5606 - (void) resetViewAnimated:(BOOL)animated {
5607 [list_ resetViewAnimated:animated];
5610 - (void) _leftButtonClicked {
5611 /*[book_ pushPage:[[[AddSourceView alloc]
5616 UIActionSheet *sheet = [[[UIActionSheet alloc]
5617 initWithTitle:CYLocalize("ENTER_APT_URL")
5618 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_SOURCE"), CYLocalize("CANCEL"), nil]
5619 defaultButtonIndex:0
5624 [sheet setNumberOfRows:1];
5626 [sheet addTextFieldWithValue:@"http://" label:@""];
5628 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5629 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5630 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5631 [traits setKeyboardType:UIKeyboardTypeURL];
5632 // XXX: UIReturnKeyDone
5633 [traits setReturnKeyType:UIReturnKeyNext];
5635 [sheet popupAlertAnimated:YES];
5638 - (void) _rightButtonClicked {
5639 UITable *table = [list_ table];
5640 BOOL editing = [table isRowDeletionEnabled];
5641 [table enableRowDeletion:!editing animated:YES];
5642 [book_ reloadButtonsForPage:self];
5645 - (NSString *) title {
5646 return CYLocalize("SOURCES");
5649 - (NSString *) leftButtonTitle {
5650 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("ADD") : nil;
5653 - (id) rightButtonTitle {
5654 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("DONE") : CYLocalize("EDIT");
5657 - (UINavigationButtonStyle) rightButtonStyle {
5658 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5664 /* Installed View {{{ */
5665 @interface InstalledView : RVPage {
5666 _transient Database *database_;
5667 FilteredPackageTable *packages_;
5671 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5675 @implementation InstalledView
5678 [packages_ release];
5682 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5683 if ((self = [super initWithBook:book]) != nil) {
5684 database_ = database;
5686 packages_ = [[FilteredPackageTable alloc]
5690 filter:@selector(isInstalledAndVisible:)
5691 with:[NSNumber numberWithBool:YES]
5694 [self addSubview:packages_];
5696 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5697 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5701 - (void) resetViewAnimated:(BOOL)animated {
5702 [packages_ resetViewAnimated:animated];
5705 - (void) reloadData {
5706 [packages_ reloadData];
5709 - (void) _rightButtonClicked {
5710 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5711 [packages_ reloadData];
5713 [book_ reloadButtonsForPage:self];
5716 - (NSString *) title {
5717 return CYLocalize("INSTALLED");
5720 - (NSString *) backButtonTitle {
5721 return CYLocalize("PACKAGES");
5724 - (id) rightButtonTitle {
5725 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? CYLocalize("EXPERT") : CYLocalize("SIMPLE");
5728 - (UINavigationButtonStyle) rightButtonStyle {
5729 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5732 - (void) setDelegate:(id)delegate {
5733 [super setDelegate:delegate];
5734 [packages_ setDelegate:delegate];
5741 @interface HomeView : BrowserView {
5746 @implementation HomeView
5748 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5749 NSString *context([sheet context]);
5751 if ([context isEqualToString:@"about"])
5754 [super alertSheet:sheet buttonClicked:button];
5757 - (void) _leftButtonClicked {
5758 UIActionSheet *sheet = [[[UIActionSheet alloc]
5759 initWithTitle:CYLocalize("ABOUT_CYDIA")
5760 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
5761 defaultButtonIndex:0
5767 @"Copyright (C) 2008-2009\n"
5768 "Jay Freeman (saurik)\n"
5769 "saurik@saurik.com\n"
5770 "http://www.saurik.com/\n"
5773 "http://www.theokorigroup.com/\n"
5775 "College of Creative Studies,\n"
5776 "University of California,\n"
5778 "http://www.ccs.ucsb.edu/"
5781 [sheet popupAlertAnimated:YES];
5784 - (NSString *) leftButtonTitle {
5785 return CYLocalize("ABOUT");
5790 /* Manage View {{{ */
5791 @interface ManageView : BrowserView {
5796 @implementation ManageView
5798 - (NSString *) title {
5799 return CYLocalize("MANAGE");
5802 - (void) _leftButtonClicked {
5803 [delegate_ askForSettings];
5806 - (NSString *) leftButtonTitle {
5807 return CYLocalize("SETTINGS");
5811 - (id) _rightButtonTitle {
5812 return Queuing_ ? CYLocalize("QUEUE") : nil;
5815 - (UINavigationButtonStyle) rightButtonStyle {
5816 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5819 - (void) _rightButtonClicked {
5824 - (bool) isLoading {
5831 #include <BrowserView.m>
5833 /* Cydia Book {{{ */
5834 @interface CYBook : RVBook <
5837 _transient Database *database_;
5838 UINavigationBar *overlay_;
5839 UINavigationBar *underlay_;
5840 UIProgressIndicator *indicator_;
5841 UITextLabel *prompt_;
5842 UIProgressBar *progress_;
5843 UINavigationButton *cancel_;
5847 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
5853 @implementation CYBook
5857 [indicator_ release];
5859 [progress_ release];
5864 - (NSString *) getTitleForPage:(RVPage *)page {
5865 return [super getTitleForPage:page];
5873 [UIView beginAnimations:nil context:NULL];
5875 CGRect ovrframe = [overlay_ frame];
5876 ovrframe.origin.y = 0;
5877 [overlay_ setFrame:ovrframe];
5879 CGRect barframe = [navbar_ frame];
5880 barframe.origin.y += ovrframe.size.height;
5881 [navbar_ setFrame:barframe];
5883 CGRect trnframe = [transition_ frame];
5884 trnframe.origin.y += ovrframe.size.height;
5885 trnframe.size.height -= ovrframe.size.height;
5886 [transition_ setFrame:trnframe];
5888 [UIView endAnimations];
5890 [indicator_ startAnimation];
5891 [prompt_ setText:CYLocalize("UPDATING_DATABASE")];
5892 [progress_ setProgress:0];
5895 [overlay_ addSubview:cancel_];
5898 detachNewThreadSelector:@selector(_update)
5907 [indicator_ stopAnimation];
5909 [UIView beginAnimations:nil context:NULL];
5911 CGRect ovrframe = [overlay_ frame];
5912 ovrframe.origin.y = -ovrframe.size.height;
5913 [overlay_ setFrame:ovrframe];
5915 CGRect barframe = [navbar_ frame];
5916 barframe.origin.y -= ovrframe.size.height;
5917 [navbar_ setFrame:barframe];
5919 CGRect trnframe = [transition_ frame];
5920 trnframe.origin.y -= ovrframe.size.height;
5921 trnframe.size.height += ovrframe.size.height;
5922 [transition_ setFrame:trnframe];
5924 [UIView commitAnimations];
5926 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
5929 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
5930 if ((self = [super initWithFrame:frame]) != nil) {
5931 database_ = database;
5933 CGRect ovrrect = [navbar_ bounds];
5934 ovrrect.size.height = [UINavigationBar defaultSize].height;
5935 ovrrect.origin.y = -ovrrect.size.height;
5937 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5938 [self addSubview:overlay_];
5940 ovrrect.origin.y = frame.size.height;
5941 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5942 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
5943 [self addSubview:underlay_];
5945 [overlay_ setBarStyle:1];
5946 [underlay_ setBarStyle:1];
5948 int barstyle = [overlay_ _barStyle:NO];
5949 bool ugly = barstyle == 0;
5951 UIProgressIndicatorStyle style = ugly ?
5952 UIProgressIndicatorStyleMediumBrown :
5953 UIProgressIndicatorStyleMediumWhite;
5955 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
5956 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
5957 CGRect indrect = {{indoffset, indoffset}, indsize};
5959 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
5960 [indicator_ setStyle:style];
5961 [overlay_ addSubview:indicator_];
5963 CGSize prmsize = {215, indsize.height + 4};
5966 indoffset * 2 + indsize.width,
5970 unsigned(ovrrect.size.height - prmsize.height) / 2
5973 UIFont *font = [UIFont systemFontOfSize:15];
5975 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
5977 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
5978 [prompt_ setBackgroundColor:[UIColor clearColor]];
5979 [prompt_ setFont:font];
5981 [overlay_ addSubview:prompt_];
5983 CGSize prgsize = {75, 100};
5986 ovrrect.size.width - prgsize.width - 10,
5987 (ovrrect.size.height - prgsize.height) / 2
5990 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
5991 [progress_ setStyle:0];
5992 [overlay_ addSubview:progress_];
5994 cancel_ = [[UINavigationButton alloc] initWithTitle:CYLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
5995 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
5997 CGRect frame = [cancel_ frame];
5998 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
5999 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6000 [cancel_ setFrame:frame];
6002 [cancel_ setBarStyle:barstyle];
6006 - (void) _onCancel {
6008 [cancel_ removeFromSuperview];
6011 - (void) _update { _pooled
6013 status.setDelegate(self);
6015 [database_ updateWithStatus:status];
6018 performSelectorOnMainThread:@selector(_update_)
6024 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
6025 [prompt_ setText:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), error]];
6028 - (void) setProgressTitle:(NSString *)title {
6030 performSelectorOnMainThread:@selector(_setProgressTitle:)
6036 - (void) setProgressPercent:(float)percent {
6038 performSelectorOnMainThread:@selector(_setProgressPercent:)
6039 withObject:[NSNumber numberWithFloat:percent]
6044 - (void) startProgress {
6047 - (void) addProgressOutput:(NSString *)output {
6049 performSelectorOnMainThread:@selector(_addProgressOutput:)
6055 - (bool) isCancelling:(size_t)received {
6059 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
6063 - (void) _setProgressTitle:(NSString *)title {
6064 [prompt_ setText:title];
6067 - (void) _setProgressPercent:(NSNumber *)percent {
6068 [progress_ setProgress:[percent floatValue]];
6071 - (void) _addProgressOutput:(NSString *)output {
6076 /* Cydia:// Protocol {{{ */
6077 @interface CydiaURLProtocol : NSURLProtocol {
6082 @implementation CydiaURLProtocol
6084 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6085 NSURL *url([request URL]);
6088 NSString *scheme([[url scheme] lowercaseString]);
6089 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6094 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6098 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6099 id<NSURLProtocolClient> client([self client]);
6101 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6103 NSData *data(UIImagePNGRepresentation(icon));
6105 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6106 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6107 [client URLProtocol:self didLoadData:data];
6108 [client URLProtocolDidFinishLoading:self];
6112 - (void) startLoading {
6113 id<NSURLProtocolClient> client([self client]);
6114 NSURLRequest *request([self request]);
6116 NSURL *url([request URL]);
6117 NSString *href([url absoluteString]);
6119 NSString *path([href substringFromIndex:8]);
6120 NSRange slash([path rangeOfString:@"/"]);
6123 if (slash.location == NSNotFound) {
6127 command = [path substringToIndex:slash.location];
6128 path = [path substringFromIndex:(slash.location + 1)];
6131 Database *database([Database sharedInstance]);
6133 if ([command isEqualToString:@"package-icon"]) {
6136 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6137 Package *package([database packageWithName:path]);
6140 UIImage *icon([package icon]);
6141 [self _returnPNGWithImage:icon forRequest:request];
6142 } else if ([command isEqualToString:@"source-icon"]) {
6145 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6146 NSString *source(Simplify(path));
6147 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6149 icon = [UIImage applicationImageNamed:@"unknown.png"];
6150 [self _returnPNGWithImage:icon forRequest:request];
6151 } else if ([command isEqualToString:@"uikit-image"]) {
6154 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6155 UIImage *icon(_UIImageWithName(path));
6156 [self _returnPNGWithImage:icon forRequest:request];
6157 } else if ([command isEqualToString:@"section-icon"]) {
6160 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6161 NSString *section(Simplify(path));
6162 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6164 icon = [UIImage applicationImageNamed:@"unknown.png"];
6165 [self _returnPNGWithImage:icon forRequest:request];
6167 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6171 - (void) stopLoading {
6177 /* Sections View {{{ */
6178 @interface SectionsView : RVPage {
6179 _transient Database *database_;
6180 NSMutableArray *sections_;
6181 NSMutableArray *filtered_;
6182 UITransitionView *transition_;
6188 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6189 - (void) reloadData;
6194 @implementation SectionsView
6197 [list_ setDataSource:nil];
6198 [list_ setDelegate:nil];
6200 [sections_ release];
6201 [filtered_ release];
6202 [transition_ release];
6204 [accessory_ release];
6208 - (int) numberOfRowsInTable:(UITable *)table {
6209 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6212 - (float) table:(UITable *)table heightForRow:(int)row {
6216 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6218 reusing = [[[SectionCell alloc] init] autorelease];
6219 [(SectionCell *)reusing setSection:(editing_ ?
6220 [sections_ objectAtIndex:row] :
6221 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6222 ) editing:editing_];
6226 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6230 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6234 - (void) tableRowSelected:(NSNotification *)notification {
6235 int row = [[notification object] selectedRow];
6246 title = CYLocalize("ALL_PACKAGES");
6248 section = [filtered_ objectAtIndex:(row - 1)];
6249 name = [section name];
6252 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6255 title = CYLocalize("NO_SECTION");
6259 PackageTable *table = [[[FilteredPackageTable alloc]
6263 filter:@selector(isVisiblyUninstalledInSection:)
6267 [table setDelegate:delegate_];
6269 [book_ pushPage:table];
6272 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6273 if ((self = [super initWithBook:book]) != nil) {
6274 database_ = database;
6276 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6277 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6279 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6280 [self addSubview:transition_];
6282 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6283 [transition_ transition:0 toView:list_];
6285 UITableColumn *column = [[[UITableColumn alloc]
6286 initWithTitle:CYLocalize("NAME")
6288 width:[self frame].size.width
6291 [list_ setDataSource:self];
6292 [list_ setSeparatorStyle:1];
6293 [list_ addTableColumn:column];
6294 [list_ setDelegate:self];
6295 [list_ setReusesTableCells:YES];
6299 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6300 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6304 - (void) reloadData {
6305 NSArray *packages = [database_ packages];
6307 [sections_ removeAllObjects];
6308 [filtered_ removeAllObjects];
6311 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6312 SectionMap sections;
6313 sections.resize(64);
6315 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6319 for (Package *package in packages) {
6320 NSString *name([package section]);
6321 NSString *key(name == nil ? @"" : name);
6326 _profile(SectionsView$reloadData$Section)
6327 section = §ions[key];
6328 if (*section == nil) {
6329 _profile(SectionsView$reloadData$Section$Allocate)
6330 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6335 [*section addToCount];
6337 _profile(SectionsView$reloadData$Filter)
6338 if (![package valid] || [package installed] != nil || ![package visible])
6342 [*section addToRow];
6346 _profile(SectionsView$reloadData$Section)
6347 section = [sections objectForKey:key];
6348 if (section == nil) {
6349 _profile(SectionsView$reloadData$Section$Allocate)
6350 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6351 [sections setObject:section forKey:key];
6356 [section addToCount];
6358 _profile(SectionsView$reloadData$Filter)
6359 if (![package valid] || [package installed] != nil || ![package visible])
6369 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6370 [sections_ addObject:i->second];
6372 [sections_ addObjectsFromArray:[sections allValues]];
6375 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6377 for (Section *section in sections_) {
6378 size_t count([section row]);
6382 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6383 [section setCount:count];
6384 [filtered_ addObject:section];
6391 - (void) resetView {
6393 [self _rightButtonClicked];
6396 - (void) resetViewAnimated:(BOOL)animated {
6397 [list_ resetViewAnimated:animated];
6400 - (void) _rightButtonClicked {
6401 if ((editing_ = !editing_))
6404 [delegate_ updateData];
6405 [book_ reloadTitleForPage:self];
6406 [book_ reloadButtonsForPage:self];
6409 - (NSString *) title {
6410 return editing_ ? CYLocalize("SECTION_VISIBILITY") : CYLocalize("INSTALL_BY_SECTION");
6413 - (NSString *) backButtonTitle {
6414 return CYLocalize("SECTIONS");
6417 - (id) rightButtonTitle {
6418 return [sections_ count] == 0 ? nil : editing_ ? CYLocalize("DONE") : CYLocalize("EDIT");
6421 - (UINavigationButtonStyle) rightButtonStyle {
6422 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6425 - (UIView *) accessoryView {
6431 /* Changes View {{{ */
6432 @interface ChangesView : RVPage {
6433 _transient Database *database_;
6434 NSMutableArray *packages_;
6435 NSMutableArray *sections_;
6436 UISectionList *list_;
6440 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6441 - (void) reloadData;
6445 @implementation ChangesView
6448 [[list_ table] setDelegate:nil];
6449 [list_ setDataSource:nil];
6451 [packages_ release];
6452 [sections_ release];
6457 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6458 return [sections_ count];
6461 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6462 return [[sections_ objectAtIndex:section] name];
6465 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6466 return [[sections_ objectAtIndex:section] row];
6469 - (int) numberOfRowsInTable:(UITable *)table {
6470 return [packages_ count];
6473 - (float) table:(UITable *)table heightForRow:(int)row {
6474 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6477 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6479 reusing = [[[PackageCell alloc] init] autorelease];
6480 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6484 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6488 - (void) tableRowSelected:(NSNotification *)notification {
6489 int row = [[notification object] selectedRow];
6492 Package *package = [packages_ objectAtIndex:row];
6493 PackageView *view([delegate_ packageView]);
6494 [view setDelegate:delegate_];
6495 [view setPackage:package];
6496 [book_ pushPage:view];
6499 - (void) _leftButtonClicked {
6500 [(CYBook *)book_ update];
6501 [self reloadButtons];
6504 - (void) _rightButtonClicked {
6505 [delegate_ distUpgrade];
6508 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6509 if ((self = [super initWithBook:book]) != nil) {
6510 database_ = database;
6512 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6513 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6515 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6516 [self addSubview:list_];
6518 [list_ setShouldHideHeaderInShortLists:NO];
6519 [list_ setDataSource:self];
6520 //[list_ setSectionListStyle:1];
6522 UITableColumn *column = [[[UITableColumn alloc]
6523 initWithTitle:CYLocalize("NAME")
6525 width:[self frame].size.width
6528 UITable *table = [list_ table];
6529 [table setSeparatorStyle:1];
6530 [table addTableColumn:column];
6531 [table setDelegate:self];
6532 [table setReusesTableCells:YES];
6536 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6537 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6541 - (void) reloadData {
6542 NSArray *packages = [database_ packages];
6544 [packages_ removeAllObjects];
6545 [sections_ removeAllObjects];
6548 for (Package *package in packages)
6550 [package installed] == nil && [package valid] && [package visible] ||
6551 [package upgradableAndEssential:YES]
6553 [packages_ addObject:package];
6556 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6559 Section *upgradable = [[[Section alloc] initWithName:CYLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6560 Section *ignored = [[[Section alloc] initWithName:CYLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6561 Section *section = nil;
6565 bool unseens = false;
6567 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6569 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6570 Package *package = [packages_ objectAtIndex:offset];
6572 BOOL uae = [package upgradableAndEssential:YES];
6578 _profile(ChangesView$reloadData$Remember)
6579 seen = [package seen];
6582 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6587 name = CYLocalize("UNKNOWN");
6589 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6593 _profile(ChangesView$reloadData$Allocate)
6594 name = [NSString stringWithFormat:CYLocalize("NEW_AT"), name];
6595 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6596 [sections_ addObject:section];
6600 [section addToCount];
6601 } else if ([package ignored])
6602 [ignored addToCount];
6605 [upgradable addToCount];
6610 CFRelease(formatter);
6613 Section *last = [sections_ lastObject];
6614 size_t count = [last count];
6615 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6616 [sections_ removeLastObject];
6619 if ([ignored count] != 0)
6620 [sections_ insertObject:ignored atIndex:0];
6622 [sections_ insertObject:upgradable atIndex:0];
6625 [self reloadButtons];
6628 - (void) resetViewAnimated:(BOOL)animated {
6629 [list_ resetViewAnimated:animated];
6632 - (NSString *) leftButtonTitle {
6633 return [(CYBook *)book_ updating] ? nil : CYLocalize("REFRESH");
6636 - (id) rightButtonTitle {
6637 return upgrades_ == 0 ? nil : [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6640 - (NSString *) title {
6641 return CYLocalize("CHANGES");
6646 /* Search View {{{ */
6647 @protocol SearchViewDelegate
6648 - (void) showKeyboard:(BOOL)show;
6651 @interface SearchView : RVPage {
6653 UISearchField *field_;
6654 UITransitionView *transition_;
6655 FilteredPackageTable *table_;
6656 UIPreferencesTable *advanced_;
6662 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6663 - (void) reloadData;
6667 @implementation SearchView
6670 [field_ setDelegate:nil];
6672 [accessory_ release];
6674 [transition_ release];
6676 [advanced_ release];
6681 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6685 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6687 case 0: return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("ADVANCED_SEARCH"), CYLocalize("COMING_SOON")];
6689 default: _assert(false);
6693 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6697 default: _assert(false);
6701 - (void) _showKeyboard:(BOOL)show {
6702 CGSize keysize = [UIKeyboard defaultSize];
6703 CGRect keydown = [book_ pageBounds];
6704 CGRect keyup = keydown;
6705 keyup.size.height -= keysize.height - ButtonBarHeight_;
6707 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6709 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6710 [animation setSignificantRectFields:8];
6713 [animation setStartFrame:keydown];
6714 [animation setEndFrame:keyup];
6716 [animation setStartFrame:keyup];
6717 [animation setEndFrame:keydown];
6720 UIAnimator *animator = [UIAnimator sharedAnimator];
6723 addAnimations:[NSArray arrayWithObjects:animation, nil]
6724 withDuration:(KeyboardTime_ - delay)
6729 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6731 [delegate_ showKeyboard:show];
6734 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6735 [self _showKeyboard:YES];
6738 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
6739 [self _showKeyboard:NO];
6742 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
6744 NSString *text([field_ text]);
6745 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6751 - (void) textFieldClearButtonPressed:(UITextField *)field {
6755 - (void) keyboardInputShouldDelete:(id)input {
6759 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
6760 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6764 [field_ resignFirstResponder];
6769 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6770 if ((self = [super initWithBook:book]) != nil) {
6771 CGRect pageBounds = [book_ pageBounds];
6773 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6774 [self addSubview:transition_];
6776 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6778 [advanced_ setReusesTableCells:YES];
6779 [advanced_ setDataSource:self];
6780 [advanced_ reloadData];
6782 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6783 CGColor dimmed(space_, 0, 0, 0, 0.5);
6784 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
6786 table_ = [[FilteredPackageTable alloc]
6790 filter:@selector(isUnfilteredAndSearchedForBy:)
6794 [table_ setShouldHideHeaderInShortLists:NO];
6795 [transition_ transition:0 toView:table_];
6804 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
6811 [self bounds].size.width - area.origin.x - 18;
6813 area.size.height = [UISearchField defaultHeight];
6815 field_ = [[UISearchField alloc] initWithFrame:area];
6817 UIFont *font = [UIFont systemFontOfSize:16];
6818 [field_ setFont:font];
6820 [field_ setPlaceholder:CYLocalize("SEARCH_EX")];
6821 [field_ setDelegate:self];
6823 [field_ setPaddingTop:5];
6825 UITextInputTraits *traits([field_ textInputTraits]);
6826 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6827 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6828 [traits setReturnKeyType:UIReturnKeySearch];
6830 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
6832 accessory_ = [[UIView alloc] initWithFrame:accrect];
6833 [accessory_ addSubview:field_];
6835 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
6836 [configure setShowPressFeedback:YES];
6837 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
6838 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
6839 [accessory_ addSubview:configure];*/
6841 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6842 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6848 LKAnimation *animation = [LKTransition animation];
6849 [animation setType:@"oglFlip"];
6850 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
6851 [animation setFillMode:@"extended"];
6852 [animation setTransitionFlags:3];
6853 [animation setDuration:10];
6854 [animation setSpeed:0.35];
6855 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
6856 [[transition_ _layer] addAnimation:animation forKey:0];
6857 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
6858 flipped_ = !flipped_;
6862 - (void) configurePushed {
6863 [field_ resignFirstResponder];
6867 - (void) resetViewAnimated:(BOOL)animated {
6870 [table_ resetViewAnimated:animated];
6873 - (void) _reloadData {
6876 - (void) reloadData {
6879 [table_ setObject:[field_ text]];
6880 _profile(SearchView$reloadData)
6881 [table_ reloadData];
6884 [table_ resetCursor];
6887 - (UIView *) accessoryView {
6891 - (NSString *) title {
6895 - (NSString *) backButtonTitle {
6896 return CYLocalize("SEARCH");
6899 - (void) setDelegate:(id)delegate {
6900 [table_ setDelegate:delegate];
6901 [super setDelegate:delegate];
6907 @interface SettingsView : RVPage {
6908 _transient Database *database_;
6911 UIPreferencesTable *table_;
6912 _UISwitchSlider *subscribedSwitch_;
6913 _UISwitchSlider *ignoredSwitch_;
6914 UIPreferencesControlTableCell *subscribedCell_;
6915 UIPreferencesControlTableCell *ignoredCell_;
6918 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6922 @implementation SettingsView
6925 [table_ setDataSource:nil];
6928 if (package_ != nil)
6931 [subscribedSwitch_ release];
6932 [ignoredSwitch_ release];
6933 [subscribedCell_ release];
6934 [ignoredCell_ release];
6938 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6939 if (package_ == nil)
6945 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6946 if (package_ == nil)
6953 default: _assert(false);
6959 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
6960 if (package_ == nil)
6967 default: _assert(false);
6973 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6974 if (package_ == nil)
6981 default: _assert(false);
6987 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
6988 if (package_ == nil)
6991 _UISwitchSlider *slider([cell control]);
6992 BOOL value([slider value] != 0);
6993 NSMutableDictionary *metadata([package_ metadata]);
6996 if (NSNumber *number = [metadata objectForKey:key])
6997 before = [number boolValue];
7001 if (value != before) {
7002 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7004 [delegate_ updateData];
7008 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7009 [self onSomething:cell withKey:@"IsSubscribed"];
7012 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7013 [self onSomething:cell withKey:@"IsIgnored"];
7016 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7017 if (package_ == nil)
7021 case 0: switch (row) {
7023 return subscribedCell_;
7025 return ignoredCell_;
7026 default: _assert(false);
7029 case 1: switch (row) {
7031 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7032 [cell setShowSelection:NO];
7033 [cell setTitle:CYLocalize("SHOW_ALL_CHANGES_EX")];
7037 default: _assert(false);
7040 default: _assert(false);
7046 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7047 if ((self = [super initWithBook:book])) {
7048 database_ = database;
7049 name_ = [package retain];
7051 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7052 [self addSubview:table_];
7054 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7055 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
7057 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7058 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
7060 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7061 [subscribedCell_ setShowSelection:NO];
7062 [subscribedCell_ setTitle:CYLocalize("SHOW_ALL_CHANGES")];
7063 [subscribedCell_ setControl:subscribedSwitch_];
7065 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7066 [ignoredCell_ setShowSelection:NO];
7067 [ignoredCell_ setTitle:CYLocalize("IGNORE_UPGRADES")];
7068 [ignoredCell_ setControl:ignoredSwitch_];
7070 [table_ setDataSource:self];
7075 - (void) resetViewAnimated:(BOOL)animated {
7076 [table_ resetViewAnimated:animated];
7079 - (void) reloadData {
7080 if (package_ != nil)
7081 [package_ autorelease];
7082 package_ = [database_ packageWithName:name_];
7083 if (package_ != nil) {
7085 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7086 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7089 [table_ reloadData];
7092 - (NSString *) title {
7093 return CYLocalize("SETTINGS");
7098 /* Signature View {{{ */
7099 @interface SignatureView : BrowserView {
7100 _transient Database *database_;
7104 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7108 @implementation SignatureView
7115 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7117 [super webView:sender didClearWindowObject:window forFrame:frame];
7120 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7121 if ((self = [super initWithBook:book]) != nil) {
7122 database_ = database;
7123 package_ = [package retain];
7128 - (void) resetViewAnimated:(BOOL)animated {
7131 - (void) reloadData {
7132 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7138 @interface Cydia : UIApplication <
7139 ConfirmationViewDelegate,
7140 ProgressViewDelegate,
7149 UIToolbar *buttonbar_;
7153 NSMutableArray *essential_;
7154 NSMutableArray *broken_;
7156 Database *database_;
7157 ProgressView *progress_;
7161 UIKeyboard *keyboard_;
7162 UIProgressHUD *hud_;
7164 SectionsView *sections_;
7165 ChangesView *changes_;
7166 ManageView *manage_;
7167 SearchView *search_;
7169 PackageView *package_;
7174 @implementation Cydia
7177 if ([broken_ count] != 0) {
7178 int count = [broken_ count];
7180 UIActionSheet *sheet = [[[UIActionSheet alloc]
7181 initWithTitle:(count == 1 ? CYLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:CYLocalize("HALFINSTALLED_PACKAGES"), count])
7182 buttons:[NSArray arrayWithObjects:
7183 CYLocalize("FORCIBLY_CLEAR"),
7184 CYLocalize("TEMPORARY_IGNORE"),
7186 defaultButtonIndex:0
7191 [sheet setBodyText:CYLocalize("HALFINSTALLED_PACKAGE_EX")];
7192 [sheet popupAlertAnimated:YES];
7193 } else if (!Ignored_ && [essential_ count] != 0) {
7194 int count = [essential_ count];
7196 UIActionSheet *sheet = [[[UIActionSheet alloc]
7197 initWithTitle:(count == 1 ? CYLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:CYLocalize("ESSENTIAL_UPGRADES"), count])
7198 buttons:[NSArray arrayWithObjects:
7199 CYLocalize("UPGRADE_ESSENTIAL"),
7200 CYLocalize("COMPLETE_UPGRADE"),
7201 CYLocalize("TEMPORARY_IGNORE"),
7203 defaultButtonIndex:0
7208 [sheet setBodyText:CYLocalize("ESSENTIAL_UPGRADE_EX")];
7209 [sheet popupAlertAnimated:YES];
7213 - (void) _reloadData {
7216 static bool loaded(false);
7217 UIProgressHUD *hud([self addProgressHUD]);
7218 [hud setText:(loaded ? CYLocalize("RELOADING_DATA") : CYLocalize("LOADING_DATA"))];
7221 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7224 [self removeProgressHUD:hud];
7228 [essential_ removeAllObjects];
7229 [broken_ removeAllObjects];
7231 NSArray *packages = [database_ packages];
7232 for (Package *package in packages) {
7234 [broken_ addObject:package];
7235 if ([package upgradableAndEssential:NO]) {
7236 if ([package essential])
7237 [essential_ addObject:package];
7243 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7244 [buttonbar_ setBadgeValue:badge forButton:3];
7245 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7246 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7247 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7248 [self setApplicationBadge:badge];
7250 [self setApplicationBadgeString:badge];
7252 [buttonbar_ setBadgeValue:nil forButton:3];
7253 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7254 [buttonbar_ setBadgeAnimated:NO forButton:3];
7255 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7256 [self removeApplicationBadge];
7257 else // XXX: maybe use setApplicationBadgeString also?
7258 [self setApplicationIconBadgeNumber:0];
7262 [buttonbar_ setBadgeValue:nil forButton:4];
7266 // XXX: what is this line of code for?
7267 if ([packages count] == 0);
7268 else if (Loaded_ || ManualRefresh) loaded:
7273 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7274 NSTimeInterval interval([update timeIntervalSinceNow]);
7275 if (interval <= 0 && interval > -600)
7283 - (void) _saveConfig {
7286 NSString *error(nil);
7287 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7289 NSError *error(nil);
7290 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7291 NSLog(@"failure to save metadata data: %@", error);
7294 NSLog(@"failure to serialize metadata: %@", error);
7302 - (void) updateData {
7305 /* XXX: this is just stupid */
7306 if (tag_ != 2 && sections_ != nil)
7307 [sections_ reloadData];
7308 if (tag_ != 3 && changes_ != nil)
7309 [changes_ reloadData];
7310 if (tag_ != 5 && search_ != nil)
7311 [search_ reloadData];
7321 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7322 _assert(file != NULL);
7324 NSArray *keys = [Sources_ allKeys];
7326 for (NSString *key in keys) {
7327 NSDictionary *source = [Sources_ objectForKey:key];
7329 fprintf(file, "%s %s %s\n",
7330 [[source objectForKey:@"Type"] UTF8String],
7331 [[source objectForKey:@"URI"] UTF8String],
7332 [[source objectForKey:@"Distribution"] UTF8String]
7341 detachNewThreadSelector:@selector(update_)
7344 title:CYLocalize("UPDATING_SOURCES")
7348 - (void) reloadData {
7349 @synchronized (self) {
7350 if (confirm_ == nil)
7356 pkgProblemResolver *resolver = [database_ resolver];
7358 resolver->InstallProtect();
7359 if (!resolver->Resolve(true))
7363 - (void) popUpBook:(RVBook *)book {
7364 [underlay_ popSubview:book];
7367 - (CGRect) popUpBounds {
7368 return [underlay_ bounds];
7372 [database_ prepare];
7374 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7375 [confirm_ setDelegate:self];
7377 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7378 [page setDelegate:self];
7380 [confirm_ setPage:page];
7381 [self popUpBook:confirm_];
7385 @synchronized (self) {
7390 - (void) clearPackage:(Package *)package {
7391 @synchronized (self) {
7398 - (void) installPackage:(Package *)package {
7399 @synchronized (self) {
7406 - (void) removePackage:(Package *)package {
7407 @synchronized (self) {
7414 - (void) distUpgrade {
7415 @synchronized (self) {
7416 [database_ upgrade];
7422 [self slideUp:[[[UIActionSheet alloc]
7424 buttons:[NSArray arrayWithObjects:CYLocalize("CONTINUE_QUEUING"), CYLocalize("CANCEL_CLEAR"), nil]
7425 defaultButtonIndex:1
7432 @synchronized (self) {
7435 if (confirm_ != nil) {
7443 [overlay_ removeFromSuperview];
7447 detachNewThreadSelector:@selector(perform)
7450 title:CYLocalize("RUNNING")
7454 - (void) bootstrap_ {
7456 [database_ upgrade];
7457 [database_ prepare];
7458 [database_ perform];
7461 /* XXX: replace and localize */
7462 - (void) bootstrap {
7464 detachNewThreadSelector:@selector(bootstrap_)
7467 title:@"Bootstrap Install"
7471 - (void) progressViewIsComplete:(ProgressView *)progress {
7472 if (confirm_ != nil) {
7473 [underlay_ addSubview:overlay_];
7474 [confirm_ popFromSuperviewAnimated:NO];
7480 - (void) setPage:(RVPage *)page {
7481 [page resetViewAnimated:NO];
7482 [page setDelegate:self];
7483 [book_ setPage:page];
7486 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7487 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7488 [browser loadURL:url];
7492 - (void) _setHomePage {
7493 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7496 - (SectionsView *) sectionsView {
7497 if (sections_ == nil)
7498 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7502 - (void) buttonBarItemTapped:(id)sender {
7503 unsigned tag = [sender tag];
7505 [book_ resetViewAnimated:YES];
7507 } else if (tag_ == 2 && tag != 2)
7508 [[self sectionsView] resetView];
7511 case 1: [self _setHomePage]; break;
7513 case 2: [self setPage:[self sectionsView]]; break;
7514 case 3: [self setPage:changes_]; break;
7515 case 4: [self setPage:manage_]; break;
7516 case 5: [self setPage:search_]; break;
7518 default: _assert(false);
7524 - (void) applicationWillSuspend {
7526 [super applicationWillSuspend];
7529 - (void) askForSettings {
7530 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
7532 UIActionSheet *role = [[[UIActionSheet alloc]
7533 initWithTitle:CYLocalize("WHO_ARE_YOU")
7534 buttons:[NSArray arrayWithObjects:
7535 [NSString stringWithFormat:parenthetical, CYLocalize("USER"), CYLocalize("USER_EX")],
7536 [NSString stringWithFormat:parenthetical, CYLocalize("HACKER"), CYLocalize("HACKER_EX")],
7537 [NSString stringWithFormat:parenthetical, CYLocalize("DEVELOPER"), CYLocalize("DEVELOPER_EX")],
7539 defaultButtonIndex:-1
7544 [role setBodyText:CYLocalize("ROLE_EX")];
7545 [role popupAlertAnimated:YES];
7548 - (void) setPackageView:(PackageView *)view {
7549 if (package_ == nil)
7550 package_ = [view retain];
7553 - (PackageView *) packageView {
7556 if (package_ == nil)
7557 view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7560 view = [package_ autorelease];
7569 [self setStatusBarShowsProgress:NO];
7570 [self removeProgressHUD:hud_];
7575 pid_t pid = ExecFork();
7577 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7578 perror("launchctl stop");
7585 [self askForSettings];
7590 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7592 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7593 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7594 0, 0, screenrect.size.width, screenrect.size.height - 48
7595 ) database:database_];
7597 [book_ setDelegate:self];
7599 [overlay_ addSubview:book_];
7601 NSArray *buttonitems = [NSArray arrayWithObjects:
7602 [NSDictionary dictionaryWithObjectsAndKeys:
7603 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7604 @"home-up.png", kUIButtonBarButtonInfo,
7605 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7606 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7607 self, kUIButtonBarButtonTarget,
7608 @"Cydia", kUIButtonBarButtonTitle,
7609 @"0", kUIButtonBarButtonType,
7612 [NSDictionary dictionaryWithObjectsAndKeys:
7613 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7614 @"install-up.png", kUIButtonBarButtonInfo,
7615 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7616 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7617 self, kUIButtonBarButtonTarget,
7618 CYLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7619 @"0", kUIButtonBarButtonType,
7622 [NSDictionary dictionaryWithObjectsAndKeys:
7623 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7624 @"changes-up.png", kUIButtonBarButtonInfo,
7625 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7626 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7627 self, kUIButtonBarButtonTarget,
7628 CYLocalize("CHANGES"), kUIButtonBarButtonTitle,
7629 @"0", kUIButtonBarButtonType,
7632 [NSDictionary dictionaryWithObjectsAndKeys:
7633 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7634 @"manage-up.png", kUIButtonBarButtonInfo,
7635 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7636 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7637 self, kUIButtonBarButtonTarget,
7638 CYLocalize("MANAGE"), kUIButtonBarButtonTitle,
7639 @"0", kUIButtonBarButtonType,
7642 [NSDictionary dictionaryWithObjectsAndKeys:
7643 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7644 @"search-up.png", kUIButtonBarButtonInfo,
7645 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7646 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7647 self, kUIButtonBarButtonTarget,
7648 CYLocalize("SEARCH"), kUIButtonBarButtonTitle,
7649 @"0", kUIButtonBarButtonType,
7653 buttonbar_ = [[UIToolbar alloc]
7655 withFrame:CGRectMake(
7656 0, screenrect.size.height - ButtonBarHeight_,
7657 screenrect.size.width, ButtonBarHeight_
7659 withItemList:buttonitems
7662 [buttonbar_ setDelegate:self];
7663 [buttonbar_ setBarStyle:1];
7664 [buttonbar_ setButtonBarTrackingMode:2];
7666 int buttons[5] = {1, 2, 3, 4, 5};
7667 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7668 [buttonbar_ showButtonGroup:0 withDuration:0];
7670 for (int i = 0; i != 5; ++i)
7671 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7672 i * 64 + 2, 1, 60, ButtonBarHeight_
7675 [buttonbar_ showSelectionForButton:1];
7676 [overlay_ addSubview:buttonbar_];
7678 [UIKeyboard initImplementationNow];
7679 CGSize keysize = [UIKeyboard defaultSize];
7680 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7681 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7682 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
7683 [overlay_ addSubview:keyboard_];
7686 [underlay_ addSubview:overlay_];
7690 [self sectionsView];
7691 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7692 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7694 manage_ = (ManageView *) [[self
7695 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7696 withClass:[ManageView class]
7699 [self setPackageView:[self packageView]];
7706 [self _setHomePage];
7709 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7710 NSString *context([sheet context]);
7712 if ([context isEqualToString:@"missing"])
7714 else if ([context isEqualToString:@"cancel"]) {
7732 @synchronized (self) {
7737 [buttonbar_ setBadgeValue:CYLocalize("Q_D") forButton:4];
7741 if (confirm_ != nil) {
7746 } else if ([context isEqualToString:@"fixhalf"]) {
7749 @synchronized (self) {
7750 for (Package *broken in broken_) {
7753 NSString *id = [broken id];
7754 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7755 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7756 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7757 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7766 [broken_ removeAllObjects];
7775 } else if ([context isEqualToString:@"role"]) {
7777 case 1: Role_ = @"User"; break;
7778 case 2: Role_ = @"Hacker"; break;
7779 case 3: Role_ = @"Developer"; break;
7786 bool reset = Settings_ != nil;
7788 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7792 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7802 } else if ([context isEqualToString:@"upgrade"]) {
7805 @synchronized (self) {
7806 for (Package *essential in essential_)
7807 [essential install];
7830 - (void) reorganize { _pooled
7831 system("/usr/libexec/cydia/free.sh");
7832 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
7835 - (void) applicationSuspend:(__GSEvent *)event {
7836 if (hud_ == nil && ![progress_ isRunning])
7837 [super applicationSuspend:event];
7840 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7842 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7845 - (void) _setSuspended:(BOOL)value {
7847 [super _setSuspended:value];
7850 - (UIProgressHUD *) addProgressHUD {
7851 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
7852 [window_ setUserInteractionEnabled:NO];
7854 [progress_ addSubview:hud];
7858 - (void) removeProgressHUD:(UIProgressHUD *)hud {
7860 [hud removeFromSuperview];
7861 [window_ setUserInteractionEnabled:YES];
7864 - (void) openMailToURL:(NSURL *)url {
7865 // XXX: this makes me sad
7867 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
7869 [UIApp openURL:url];// asPanel:YES];
7873 - (void) clearFirstResponder {
7874 if (id responder = [window_ firstResponder])
7875 [responder resignFirstResponder];
7878 - (RVPage *) pageForPackage:(NSString *)name {
7879 if (Package *package = [database_ packageWithName:name]) {
7880 PackageView *view([self packageView]);
7881 [view setPackage:package];
7884 UIActionSheet *sheet = [[[UIActionSheet alloc]
7885 initWithTitle:CYLocalize("CANNOT_LOCATE_PACKAGE")
7886 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
7887 defaultButtonIndex:0
7892 [sheet setBodyText:[NSString stringWithFormat:CYLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
7894 [sheet popupAlertAnimated:YES];
7899 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
7903 NSString *scheme([[url scheme] lowercaseString]);
7904 if (![scheme isEqualToString:@"cydia"])
7906 NSString *path([url absoluteString]);
7907 if ([path length] < 8)
7909 path = [path substringFromIndex:8];
7910 if (![path hasPrefix:@"/"])
7911 path = [@"/" stringByAppendingString:path];
7913 if ([path isEqualToString:@"/add-source"])
7914 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
7915 else if ([path isEqualToString:@"/storage"])
7916 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[BrowserView class]];
7917 else if ([path isEqualToString:@"/sources"])
7918 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
7919 else if ([path isEqualToString:@"/packages"])
7920 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
7921 else if ([path hasPrefix:@"/url/"])
7922 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[BrowserView class]];
7923 else if ([path hasPrefix:@"/launch/"])
7924 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
7925 else if ([path hasPrefix:@"/package-settings/"])
7926 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
7927 else if ([path hasPrefix:@"/package-signature/"])
7928 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
7929 else if ([path hasPrefix:@"/package/"])
7930 return [self pageForPackage:[path substringFromIndex:9]];
7931 else if ([path hasPrefix:@"/files/"]) {
7932 NSString *name = [path substringFromIndex:7];
7934 if (Package *package = [database_ packageWithName:name]) {
7935 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
7936 [files setPackage:package];
7944 - (void) applicationOpenURL:(NSURL *)url {
7945 [super applicationOpenURL:url];
7947 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
7948 [self setPage:page];
7949 [buttonbar_ showSelectionForButton:tag];
7954 - (void) applicationDidFinishLaunching:(id)unused {
7956 Font12_ = [[UIFont systemFontOfSize:12] retain];
7957 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
7958 Font14_ = [[UIFont systemFontOfSize:14] retain];
7959 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
7960 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
7964 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
7965 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
7967 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
7969 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7970 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
7972 [window_ orderFront:self];
7973 [window_ makeKey:self];
7974 [window_ setHidden:NO];
7976 database_ = [Database sharedInstance];
7977 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
7978 [database_ setDelegate:progress_];
7979 [window_ setContentView:progress_];
7981 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
7982 [progress_ setContentView:underlay_];
7984 [progress_ resetView];
7987 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
7988 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
7989 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
7990 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
7991 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
7992 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
7993 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
7995 [self setIdleTimerDisabled:YES];
7997 hud_ = [[self addProgressHUD] retain];
7998 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8000 [self setStatusBarShowsProgress:YES];
8003 detachNewThreadSelector:@selector(reorganize)
8011 - (void) showKeyboard:(BOOL)show {
8012 CGSize keysize = [UIKeyboard defaultSize];
8013 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8014 CGRect keyup = keydown;
8015 keyup.origin.y -= keysize.height;
8017 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
8018 [animation setSignificantRectFields:2];
8021 [animation setStartFrame:keydown];
8022 [animation setEndFrame:keyup];
8023 [keyboard_ activate];
8025 [animation setStartFrame:keyup];
8026 [animation setEndFrame:keydown];
8027 [keyboard_ deactivate];
8030 [[UIAnimator sharedAnimator]
8031 addAnimations:[NSArray arrayWithObjects:animation, nil]
8032 withDuration:KeyboardTime_
8037 - (void) slideUp:(UIActionSheet *)alert {
8039 [alert presentSheetFromButtonBar:buttonbar_];
8041 [alert presentSheetInView:overlay_];
8046 void AddPreferences(NSString *plist) { _pooled
8047 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
8048 _assert(settings != NULL);
8049 NSMutableArray *items = [settings objectForKey:@"items"];
8053 for (NSMutableDictionary *item in items) {
8054 NSString *label = [item objectForKey:@"label"];
8055 if (label != nil && [label isEqualToString:@"Cydia"]) {
8062 for (size_t i(0); i != [items count]; ++i) {
8063 NSDictionary *item([items objectAtIndex:i]);
8064 NSString *label = [item objectForKey:@"label"];
8065 if (label != nil && [label isEqualToString:@"General"]) {
8066 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
8067 @"CydiaSettings", @"bundle",
8068 @"PSLinkCell", @"cell",
8069 [NSNumber numberWithBool:YES], @"hasIcon",
8070 [NSNumber numberWithBool:YES], @"isController",
8072 nil] atIndex:(i + 1)];
8078 _assert([settings writeToFile:plist atomically:YES] == YES);
8083 id Alloc_(id self, SEL selector) {
8084 id object = alloc_(self, selector);
8085 lprintf("[%s]A-%p\n", self->isa->name, object);
8090 id Dealloc_(id self, SEL selector) {
8091 id object = dealloc_(self, selector);
8092 lprintf("[%s]D-%p\n", self->isa->name, object);
8096 Class $WebDefaultUIKitDelegate;
8098 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
8100 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
8101 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8102 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8103 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
8106 int main(int argc, char *argv[]) { _pooled
8109 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8111 /* Library Hacks {{{ */
8112 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8114 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8115 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8116 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8117 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8118 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8121 /* Set Locale {{{ */
8122 Locale_ = CFLocaleCopyCurrent();
8123 Languages_ = [NSLocale preferredLanguages];
8124 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8125 //NSLog(@"%@", [Languages_ description]);
8127 if (Languages_ == nil || [Languages_ count] == 0)
8130 lang = [[Languages_ objectAtIndex:0] UTF8String];
8131 setenv("LANG", lang, true);
8132 //std::setlocale(LC_ALL, lang);
8133 NSLog(@"Setting Language: %s", lang);
8136 // XXX: apr_app_initialize?
8139 /* Parse Arguments {{{ */
8140 bool substrate(false);
8146 for (int argi(1); argi != argc; ++argi)
8147 if (strcmp(argv[argi], "--") == 0) {
8149 argv[argi] = argv[0];
8155 for (int argi(1); argi != arge; ++argi)
8156 if (strcmp(args[argi], "--bootstrap") == 0)
8158 else if (strcmp(args[argi], "--substrate") == 0)
8161 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8166 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
8167 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
8168 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
8169 Sounds_Keyboard_ = [keyboard boolValue];
8172 App_ = [[NSBundle mainBundle] bundlePath];
8173 Home_ = NSHomeDirectory();
8178 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8179 alloc_ = alloc->method_imp;
8180 alloc->method_imp = (IMP) &Alloc_;*/
8182 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8183 dealloc_ = dealloc->method_imp;
8184 dealloc->method_imp = (IMP) &Dealloc_;*/
8189 size = sizeof(maxproc);
8190 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8191 perror("sysctlbyname(\"kern.maxproc\", ?)");
8192 else if (maxproc < 64) {
8194 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8195 perror("sysctlbyname(\"kern.maxproc\", #)");
8198 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8199 char *machine = new char[size];
8200 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8201 perror("sysctlbyname(\"hw.machine\", ?)");
8205 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8207 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8208 Build_ = [system objectForKey:@"ProductBuildVersion"];
8209 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8210 Product_ = [info objectForKey:@"SafariProductVersion"];
8211 Safari_ = [info objectForKey:@"CFBundleVersion"];
8214 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8215 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
8217 /* Load Database {{{ */
8219 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8221 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8224 if (Metadata_ == NULL)
8225 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8227 Settings_ = [Metadata_ objectForKey:@"Settings"];
8229 Packages_ = [Metadata_ objectForKey:@"Packages"];
8230 Sections_ = [Metadata_ objectForKey:@"Sections"];
8231 Sources_ = [Metadata_ objectForKey:@"Sources"];
8234 if (Settings_ != nil)
8235 Role_ = [Settings_ objectForKey:@"Role"];
8237 if (Packages_ == nil) {
8238 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8239 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8242 if (Sections_ == nil) {
8243 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8244 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8247 if (Sources_ == nil) {
8248 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8249 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8254 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8257 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8258 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8259 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8260 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8262 if (access("/User", F_OK) != 0) {
8264 system("/usr/libexec/cydia/firmware.sh");
8268 _assert([[NSFileManager defaultManager]
8269 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8270 withIntermediateDirectories:YES
8275 if (access("/tmp/cydia.chk", F_OK) == 0) {
8276 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8277 _assert(errno == ENOENT);
8278 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8279 _assert(errno == ENOENT);
8282 _assert(pkgInitConfig(*_config));
8283 _assert(pkgInitSystem(*_config, _system));
8286 _config->Set("APT::Acquire::Translation", lang);
8287 _config->Set("Acquire::http::Timeout", 15);
8288 _config->Set("Acquire::http::MaxParallel", 4);
8290 /* Color Choices {{{ */
8291 space_ = CGColorSpaceCreateDeviceRGB();
8293 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8294 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8295 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8296 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8297 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8298 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8299 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8300 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8301 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8302 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8303 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8304 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8305 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8306 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8307 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8310 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8311 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8314 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8316 /* UIKit Configuration {{{ */
8317 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8318 if ($GSFontSetUseLegacyFontMetrics != NULL)
8319 $GSFontSetUseLegacyFontMetrics(YES);
8321 UIKeyboardDisableAutomaticAppearance();
8325 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8327 CGColorSpaceRelease(space_);