1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008 Jay Freeman (saurik)
6 * Redistribution and use in source and binary
7 * forms, with or without modification, are permitted
8 * provided that the following conditions are met:
10 * 1. Redistributions of source code must retain the
11 * above copyright notice, this list of conditions
12 * and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the
14 * above copyright notice, this list of conditions
15 * and the following disclaimer in the documentation
16 * and/or other materials provided with the
18 * 3. The name of the author may not be used to endorse
19 * or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
23 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
24 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
28 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
30 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
33 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
35 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 // XXX: wtf/FastMalloc.h... wtf?
39 #define USE_SYSTEM_MALLOC 1
41 /* #include Directives {{{ */
42 #import "UICaboodle.h"
44 #include <objc/message.h>
45 #include <objc/objc.h>
46 #include <objc/runtime.h>
48 #include <CoreGraphics/CoreGraphics.h>
49 #include <GraphicsServices/GraphicsServices.h>
50 #include <Foundation/Foundation.h>
53 #define DEPLOYMENT_TARGET_MACOSX 1
54 #define CF_BUILDING_CF 1
55 #include <CoreFoundation/CFInternal.h>
58 #include <CoreFoundation/CFPriv.h>
59 #include <CoreFoundation/CFUniChar.h>
61 #import <QuartzCore/CALayer.h>
62 #import <UIKit/UIKit.h>
64 #include <WebCore/WebCoreThread.h>
65 #import <WebKit/WebDefaultUIKitDelegate.h>
72 #include <ext/stdio_filebuf.h>
74 #include <apt-pkg/acquire.h>
75 #include <apt-pkg/acquire-item.h>
76 #include <apt-pkg/algorithms.h>
77 #include <apt-pkg/cachefile.h>
78 #include <apt-pkg/clean.h>
79 #include <apt-pkg/configuration.h>
80 #include <apt-pkg/debindexfile.h>
81 #include <apt-pkg/debmetaindex.h>
82 #include <apt-pkg/error.h>
83 #include <apt-pkg/init.h>
84 #include <apt-pkg/mmap.h>
85 #include <apt-pkg/pkgrecords.h>
86 #include <apt-pkg/sha1.h>
87 #include <apt-pkg/sourcelist.h>
88 #include <apt-pkg/sptr.h>
89 #include <apt-pkg/strutl.h>
90 #include <apt-pkg/tagfile.h>
92 #include <apr-1/apr_pools.h>
94 #include <sys/types.h>
96 #include <sys/sysctl.h>
97 #include <sys/param.h>
98 #include <sys/mount.h>
104 #include <mach-o/nlist.h>
114 #include <ext/hash_map>
116 #import "BrowserView.h"
117 #import "ResetView.h"
119 #import "substrate.h"
122 //#define _finline __attribute__((force_inline))
123 #define _finline inline
128 #define _limit(count) do { \
129 static size_t _count(0); \
130 if (++_count == count) \
135 #define _timestamp ({ \
137 gettimeofday(&tv, NULL); \
138 tv.tv_sec * 1000000 + tv.tv_usec; \
141 typedef std::vector<class ProfileTime *> TimeList;
151 ProfileTime(const char *name) :
155 times_.push_back(this);
158 void AddTime(uint64_t time) {
165 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
177 ProfileTimer(ProfileTime &time) :
184 time_.AddTime(_timestamp - start_);
189 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
191 std::cerr << "========" << std::endl;
194 #define _profile(name) { \
195 static ProfileTime name(#name); \
196 ProfileTimer _ ## name(name);
200 /* Objective-C Handle<> {{{ */
201 template <typename Type_>
203 typedef _H<Type_> This_;
208 _finline void Retain_() {
213 _finline void Clear_() {
219 _finline _H(Type_ *value = NULL, bool mended = false) :
230 _finline operator Type_ *() const {
234 _finline This_ &operator =(Type_ *value) {
235 if (value_ != value) {
246 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
248 void NSLogPoint(const char *fix, const CGPoint &point) {
249 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
252 void NSLogRect(const char *fix, const CGRect &rect) {
253 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
256 @interface NSObject (Cydia)
257 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
258 - (id) yieldToSelector:(SEL)selector;
261 @implementation NSObject (Cydia)
266 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
267 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
268 id object([[context objectAtIndex:1] nonretainedObjectValue]);
269 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
271 /* XXX: deal with exceptions */
272 id value([self performSelector:selector withObject:object]);
274 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
275 [context removeAllObjects];
276 if ([signature methodReturnLength] != 0 && value != nil)
277 [context addObject:value];
282 performSelectorOnMainThread:@selector(doNothing)
288 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
289 /*return [self performSelector:selector withObject:object];*/
291 volatile bool stopped(false);
293 NSMutableArray *context([NSMutableArray arrayWithObjects:
294 [NSValue valueWithPointer:selector],
295 [NSValue valueWithNonretainedObject:object],
296 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
299 NSThread *thread([[[NSThread alloc]
301 selector:@selector(_yieldToContext:)
307 NSRunLoop *loop([NSRunLoop currentRunLoop]);
308 NSDate *future([NSDate distantFuture]);
310 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
312 return [context count] == 0 ? nil : [context objectAtIndex:0];
315 - (id) yieldToSelector:(SEL)selector {
316 return [self yieldToSelector:selector withObject:nil];
321 /* NSForcedOrderingSearch doesn't work on the iPhone */
322 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
323 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
324 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
326 /* iPhoneOS 2.0 Compatibility {{{ */
328 @interface UITextView (iPhoneOS)
329 - (void) setTextSize:(float)size;
332 @implementation UITextView (iPhoneOS)
334 - (void) setTextSize:(float)size {
335 [self setFont:[[self font] fontWithSize:size]];
342 extern NSString * const kCAFilterNearest;
344 /* Information Dictionaries {{{ */
345 @interface NSMutableArray (Cydia)
346 - (void) addInfoDictionary:(NSDictionary *)info;
349 @implementation NSMutableArray (Cydia)
351 - (void) addInfoDictionary:(NSDictionary *)info {
352 [self addObject:info];
357 @interface NSMutableDictionary (Cydia)
358 - (void) addInfoDictionary:(NSDictionary *)info;
361 @implementation NSMutableDictionary (Cydia)
363 - (void) addInfoDictionary:(NSDictionary *)info {
364 NSString *bundle = [info objectForKey:@"CFBundleIdentifier"];
365 [self setObject:info forKey:bundle];
370 /* Pop Transitions {{{ */
371 @interface PopTransitionView : UITransitionView {
376 @implementation PopTransitionView
378 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
379 if (from != nil && to == nil)
380 [self removeFromSuperview];
385 @implementation UIView (PopUpView)
387 - (void) popFromSuperviewAnimated:(BOOL)animated {
388 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
391 - (void) popSubview:(UIView *)view {
392 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
393 [transition setDelegate:transition];
394 [self addSubview:transition];
396 UIView *blank = [[[UIView alloc] initWithFrame:[transition bounds]] autorelease];
397 [transition transition:UITransitionNone toView:blank];
398 [transition transition:UITransitionPushFromBottom toView:view];
404 #define lprintf(args...) fprintf(stderr, args)
407 #define TraceLogging (1 && !ForRelease)
408 #define HistogramInsertionSort (0 && !ForRelease)
409 #define ProfileTimes (0 && !ForRelease)
410 #define ForSaurik (0 && !ForRelease)
411 #define LogBrowser (1 && !ForRelease)
412 #define TrackResize (0 && !ForRelease)
413 #define ManualRefresh (1 && !ForRelease)
414 #define ShowInternals (0 && !ForRelease)
415 #define IgnoreInstall (0 && !ForRelease)
416 #define RecycleWebViews 0
417 #define AlwaysReload (1 && !ForRelease)
421 #define _trace(args...)
426 #define _profile(name) {
429 #define PrintTimes() do {} while (false)
433 typedef uint32_t (*SKRadixFunction)(id, void *);
435 @interface NSMutableArray (Radix)
436 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
437 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
445 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
446 struct RadixItem_ *lhs(swap), *rhs(swap + count);
448 static const size_t width = 32;
449 static const size_t bits = 11;
450 static const size_t slots = 1 << bits;
451 static const size_t passes = (width + (bits - 1)) / bits;
453 size_t *hist(new size_t[slots]);
455 for (size_t pass(0); pass != passes; ++pass) {
456 memset(hist, 0, sizeof(size_t) * slots);
458 for (size_t i(0); i != count; ++i) {
459 uint32_t key(lhs[i].key);
461 key &= _not(uint32_t) >> width - bits;
466 for (size_t i(0); i != slots; ++i) {
467 size_t local(offset);
472 for (size_t i(0); i != count; ++i) {
473 uint32_t key(lhs[i].key);
475 key &= _not(uint32_t) >> width - bits;
476 rhs[hist[key]++] = lhs[i];
479 RadixItem_ *tmp(lhs);
486 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
487 for (size_t i(0); i != count; ++i)
488 [values addObject:[self objectAtIndex:lhs[i].index]];
489 [self setArray:values];
494 @implementation NSMutableArray (Radix)
496 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
497 size_t count([self count]);
502 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
503 [invocation setSelector:selector];
504 [invocation setArgument:&object atIndex:2];
506 /* XXX: this is an unsafe optimization of doomy hell */
507 Method method(class_getInstanceMethod([[self objectAtIndex:0] class], selector));
508 _assert(method != NULL);
509 uint32_t (*imp)(id, SEL, id) = reinterpret_cast<uint32_t (*)(id, SEL, id)>(method_getImplementation(method));
510 _assert(imp != NULL);
513 struct RadixItem_ *swap(new RadixItem_[count * 2]);
515 for (size_t i(0); i != count; ++i) {
516 RadixItem_ &item(swap[i]);
519 id object([self objectAtIndex:i]);
522 [invocation setTarget:object];
524 [invocation getReturnValue:&item.key];
526 item.key = imp(object, selector, object);
530 RadixSort_(self, count, swap);
533 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
534 size_t count([self count]);
535 struct RadixItem_ *swap(new RadixItem_[count * 2]);
537 for (size_t i(0); i != count; ++i) {
538 RadixItem_ &item(swap[i]);
541 id object([self objectAtIndex:i]);
542 item.key = function(object, argument);
545 RadixSort_(self, count, swap);
550 /* Insertion Sort {{{ */
552 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
553 const char *ptr = (const char *)list;
555 CFIndex half = count / 2;
556 const char *probe = ptr + elementSize * half;
557 CFComparisonResult cr = comparator(element, probe, context);
558 if (0 == cr) return (probe - (const char *)list) / elementSize;
559 ptr = (cr < 0) ? ptr : probe + elementSize;
560 count = (cr < 0) ? half : (half + (count & 1) - 1);
562 return (ptr - (const char *)list) / elementSize;
565 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
566 const char *ptr = (const char *)list;
568 CFIndex half = count / 2;
569 const char *probe = ptr + elementSize * half;
570 CFComparisonResult cr = comparator(element, probe, context);
571 if (0 == cr) return (probe - (const char *)list) / elementSize;
572 ptr = (cr < 0) ? ptr : probe + elementSize;
573 count = (cr < 0) ? half : (half + (count & 1) - 1);
575 return (ptr - (const char *)list) / elementSize;
578 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
579 if (range.length == 0)
581 const void **values(new const void *[range.length]);
582 CFArrayGetValues(array, range, values);
584 #if HistogramInsertionSort
585 uint32_t total(0), *offsets(new uint32_t[range.length]);
588 for (CFIndex index(1); index != range.length; ++index) {
589 const void *value(values[index]);
590 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
591 CFIndex correct(index);
592 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan)
595 if (correct != index) {
596 size_t offset(index - correct);
597 #if HistogramInsertionSort
601 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
603 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
604 values[correct] = value;
608 CFArrayReplaceValues(array, range, values, range.length);
611 #if HistogramInsertionSort
612 for (CFIndex index(0); index != range.length; ++index)
613 if (offsets[index] != 0)
614 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
615 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
622 /* Apple Bug Fixes {{{ */
623 @implementation UIWebDocumentView (Cydia)
625 - (void) _setScrollerOffset:(CGPoint)offset {
626 UIScroller *scroller([self _scroller]);
628 CGSize size([scroller contentSize]);
629 CGSize bounds([scroller bounds].size);
632 max.x = size.width - bounds.width;
633 max.y = size.height - bounds.height;
641 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
642 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
644 [scroller setOffset:offset];
651 kUIControlEventMouseDown = 1 << 0,
652 kUIControlEventMouseMovedInside = 1 << 2, // mouse moved inside control target
653 kUIControlEventMouseMovedOutside = 1 << 3, // mouse moved outside control target
654 kUIControlEventMouseUpInside = 1 << 6, // mouse up inside control target
655 kUIControlEventMouseUpOutside = 1 << 7, // mouse up outside control target
656 kUIControlAllEvents = (kUIControlEventMouseDown | kUIControlEventMouseMovedInside | kUIControlEventMouseMovedOutside | kUIControlEventMouseUpInside | kUIControlEventMouseUpOutside)
657 } UIControlEventMasks;
659 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
660 size_t length([self length] - state->state);
663 else if (length > count)
665 for (size_t i(0); i != length; ++i)
666 objects[i] = [self item:state->state++];
667 state->itemsPtr = objects;
668 state->mutationsPtr = (unsigned long *) self;
672 @interface NSString (UIKit)
673 - (NSString *) stringByAddingPercentEscapes;
674 - (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
677 @interface NSString (Cydia)
678 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
679 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
680 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
681 - (NSComparisonResult) compareByPath:(NSString *)other;
682 - (NSString *) stringByCachingURLWithCurrentCDN;
683 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
686 @implementation NSString (Cydia)
688 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
689 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
692 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
693 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
694 memcpy(data, bytes, length);
695 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
698 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
699 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
702 - (NSComparisonResult) compareByPath:(NSString *)other {
703 NSString *prefix = [self commonPrefixWithString:other options:0];
704 size_t length = [prefix length];
706 NSRange lrange = NSMakeRange(length, [self length] - length);
707 NSRange rrange = NSMakeRange(length, [other length] - length);
709 lrange = [self rangeOfString:@"/" options:0 range:lrange];
710 rrange = [other rangeOfString:@"/" options:0 range:rrange];
712 NSComparisonResult value;
714 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
715 value = NSOrderedSame;
716 else if (lrange.location == NSNotFound)
717 value = NSOrderedAscending;
718 else if (rrange.location == NSNotFound)
719 value = NSOrderedDescending;
721 value = NSOrderedSame;
723 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
724 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
725 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
726 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
728 NSComparisonResult result = [lpath compare:rpath];
729 return result == NSOrderedSame ? value : result;
732 - (NSString *) stringByCachingURLWithCurrentCDN {
734 stringByReplacingOccurrencesOfString:@"://"
735 withString:@"://ne.edgecastcdn.net/8003A4/"
737 /* XXX: this is somewhat inaccurate */
738 range:NSMakeRange(0, 10)
742 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
743 return [(id)CFURLCreateStringByAddingPercentEscapes(
748 kCFStringEncodingUTF8
754 static inline NSString *CYLocalizeEx(NSString *key, NSString *value = nil) {
755 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:nil];
758 #define CYLocalize(key) CYLocalizeEx(@ key)
766 _finline void clear_() {
767 if (cache_ != NULL) {
774 _finline bool empty() const {
778 _finline size_t size() const {
782 _finline char *data() const {
786 _finline void clear() {
791 _finline CYString() :
798 _finline ~CYString() {
802 void operator =(const CYString &rhs) {
806 if (rhs.cache_ == nil)
809 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
812 void set(apr_pool_t *pool, const char *data, size_t size) {
818 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
819 memcpy(temp, data, size);
826 _finline void set(apr_pool_t *pool, const char *data) {
827 set(pool, data, data == NULL ? 0 : strlen(data));
830 _finline void set(apr_pool_t *pool, const std::string &rhs) {
831 set(pool, rhs.data(), rhs.size());
834 bool operator ==(const CYString &rhs) const {
835 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
838 operator CFStringRef() {
839 if (cache_ == NULL) {
842 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
846 _finline operator id() {
847 return (NSString *) static_cast<CFStringRef>(*this);
852 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
855 struct NSStringMapHash :
856 std::unary_function<NSString *, size_t>
858 _finline size_t operator ()(NSString *value) const {
859 return CFStringHashNSString((CFStringRef) value);
863 struct NSStringMapLess :
864 std::binary_function<NSString *, NSString *, bool>
866 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
867 return [lhs compare:rhs] == NSOrderedAscending;
871 struct NSStringMapEqual :
872 std::binary_function<NSString *, NSString *, bool>
874 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
875 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
876 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
877 //[lhs isEqualToString:rhs];
881 /* Perl-Compatible RegEx {{{ */
891 Pcre(const char *regex) :
896 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
899 lprintf("%d:%s\n", offset, error);
903 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
904 matches_ = new int[(capture_ + 1) * 3];
912 NSString *operator [](size_t match) {
913 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
916 bool operator ()(NSString *data) {
917 // XXX: length is for characters, not for bytes
918 return operator ()([data UTF8String], [data length]);
921 bool operator ()(const char *data, size_t size) {
923 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
927 /* Mime Addresses {{{ */
928 @interface Address : NSObject {
934 - (NSString *) address;
936 - (void) setAddress:(NSString *)address;
938 + (Address *) addressWithString:(NSString *)string;
939 - (Address *) initWithString:(NSString *)string;
942 @implementation Address
951 - (NSString *) name {
955 - (NSString *) address {
959 - (void) setAddress:(NSString *)address {
961 [address_ autorelease];
965 address_ = [address retain];
968 + (Address *) addressWithString:(NSString *)string {
969 return [[[Address alloc] initWithString:string] autorelease];
972 + (NSArray *) _attributeKeys {
973 return [NSArray arrayWithObjects:@"address", @"name", nil];
976 - (NSArray *) attributeKeys {
977 return [[self class] _attributeKeys];
980 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
981 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
984 - (Address *) initWithString:(NSString *)string {
985 if ((self = [super init]) != nil) {
986 const char *data = [string UTF8String];
987 size_t size = [string length];
989 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
991 if (address_r(data, size)) {
992 name_ = [address_r[1] retain];
993 address_ = [address_r[2] retain];
995 name_ = [string retain];
1003 /* CoreGraphics Primitives {{{ */
1014 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
1017 Set(space, red, green, blue, alpha);
1022 CGColorRelease(color_);
1029 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1031 float color[] = {red, green, blue, alpha};
1032 color_ = CGColorCreate(space, color);
1035 operator CGColorRef() {
1041 extern "C" void UISetColor(CGColorRef color);
1043 /* Random Global Variables {{{ */
1044 static const int PulseInterval_ = 50000;
1045 static const int ButtonBarHeight_ = 48;
1046 static const float KeyboardTime_ = 0.3f;
1048 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1049 #define SandboxTemplate_ "/usr/share/sandbox/SandboxTemplate.sb"
1050 #define NotifyConfig_ "/etc/notify.conf"
1052 static bool Queuing_;
1054 static CGColor Blue_;
1055 static CGColor Blueish_;
1056 static CGColor Black_;
1057 static CGColor Off_;
1058 static CGColor White_;
1059 static CGColor Gray_;
1060 static CGColor Green_;
1061 static CGColor Purple_;
1062 static CGColor Purplish_;
1064 static UIColor *InstallingColor_;
1065 static UIColor *RemovingColor_;
1067 static NSString *App_;
1068 static NSString *Home_;
1069 static BOOL Sounds_Keyboard_;
1071 static BOOL Advanced_;
1072 static BOOL Loaded_;
1073 static BOOL Ignored_;
1075 static UIFont *Font12_;
1076 static UIFont *Font12Bold_;
1077 static UIFont *Font14_;
1078 static UIFont *Font18Bold_;
1079 static UIFont *Font22Bold_;
1081 static const char *Machine_ = NULL;
1082 static const NSString *UniqueID_ = nil;
1083 static const NSString *Build_ = nil;
1084 static const NSString *Product_ = nil;
1085 static const NSString *Safari_ = nil;
1087 CFLocaleRef Locale_;
1088 NSArray *Languages_;
1089 CGColorSpaceRef space_;
1094 static NSDictionary *SectionMap_;
1095 static NSMutableDictionary *Metadata_;
1096 static _transient NSMutableDictionary *Settings_;
1097 static _transient NSString *Role_;
1098 static _transient NSMutableDictionary *Packages_;
1099 static _transient NSMutableDictionary *Sections_;
1100 static _transient NSMutableDictionary *Sources_;
1101 static bool Changed_;
1102 static NSDate *now_;
1105 static NSMutableArray *Documents_;
1108 NSString *GetLastUpdate() {
1109 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1112 return CYLocalize("NEVER_OR_UNKNOWN");
1114 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1115 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1117 CFRelease(formatter);
1119 return [(NSString *) formatted autorelease];
1122 /* Display Helpers {{{ */
1123 inline float Interpolate(float begin, float end, float fraction) {
1124 return (end - begin) * fraction + begin;
1127 /* XXX: localize this! */
1128 NSString *SizeString(double size) {
1129 bool negative = size < 0;
1134 while (size > 1024) {
1139 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1141 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1144 static _finline CFStringRef CFCString(const char *value) {
1145 return CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(value), strlen(value), kCFStringEncodingUTF8, NO, kCFAllocatorNull);
1148 CFStringRef StripVersion(const char *version) {
1149 const char *colon(strchr(version, ':'));
1151 version = colon + 1;
1152 return CFCString(version);
1155 NSString *LocalizeSection(NSString *section) {
1156 static Pcre title_r("^(.*?) \\((.*)\\)$");
1157 if (title_r(section)) {
1158 NSString *parent(title_r[1]);
1159 NSString *child(title_r[2]);
1161 return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"),
1162 LocalizeSection(parent),
1163 LocalizeSection(child)
1167 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1170 NSString *Simplify(NSString *title) {
1171 const char *data = [title UTF8String];
1172 size_t size = [title length];
1174 static Pcre square_r("^\\[(.*)\\]$");
1175 if (square_r(data, size))
1176 return Simplify(square_r[1]);
1178 static Pcre paren_r("^\\((.*)\\)$");
1179 if (paren_r(data, size))
1180 return Simplify(paren_r[1]);
1182 static Pcre title_r("^(.*?) \\((.*)\\)$");
1183 if (title_r(data, size))
1184 return Simplify(title_r[1]);
1190 bool isSectionVisible(NSString *section) {
1191 NSDictionary *metadata([Sections_ objectForKey:section]);
1192 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1193 return hidden == nil || ![hidden boolValue];
1196 /* Delegate Prototypes {{{ */
1200 @interface NSObject (ProgressDelegate)
1203 @implementation NSObject(ProgressDelegate)
1205 - (void) _setProgressError:(NSArray *)args {
1206 [self performSelector:@selector(setProgressError:forPackage:)
1207 withObject:[args objectAtIndex:0]
1208 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1214 @protocol ProgressDelegate
1215 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1216 - (void) setProgressTitle:(NSString *)title;
1217 - (void) setProgressPercent:(float)percent;
1218 - (void) startProgress;
1219 - (void) addProgressOutput:(NSString *)output;
1220 - (bool) isCancelling:(size_t)received;
1223 @protocol ConfigurationDelegate
1224 - (void) repairWithSelector:(SEL)selector;
1225 - (void) setConfigurationData:(NSString *)data;
1230 @protocol CydiaDelegate
1231 - (void) setPackageView:(PackageView *)view;
1232 - (void) clearPackage:(Package *)package;
1233 - (void) installPackage:(Package *)package;
1234 - (void) removePackage:(Package *)package;
1235 - (void) slideUp:(UIActionSheet *)alert;
1236 - (void) distUpgrade;
1237 - (void) updateData;
1239 - (void) askForSettings;
1240 - (UIProgressHUD *) addProgressHUD;
1241 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1242 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag;
1243 - (RVPage *) pageForPackage:(NSString *)name;
1244 - (void) openMailToURL:(NSURL *)url;
1245 - (void) clearFirstResponder;
1246 - (PackageView *) packageView;
1250 /* Status Delegation {{{ */
1252 public pkgAcquireStatus
1255 _transient NSObject<ProgressDelegate> *delegate_;
1263 void setDelegate(id delegate) {
1264 delegate_ = delegate;
1267 virtual bool MediaChange(std::string media, std::string drive) {
1271 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1274 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1275 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1276 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
1279 virtual void Done(pkgAcquire::ItemDesc &item) {
1282 virtual void Fail(pkgAcquire::ItemDesc &item) {
1284 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1285 item.Owner->Status == pkgAcquire::Item::StatDone
1289 std::string &error(item.Owner->ErrorText);
1293 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1294 NSArray *fields([description componentsSeparatedByString:@" "]);
1295 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1297 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1298 withObject:[NSArray arrayWithObjects:
1299 [NSString stringWithUTF8String:error.c_str()],
1306 virtual bool Pulse(pkgAcquire *Owner) {
1307 bool value = pkgAcquireStatus::Pulse(Owner);
1310 double(CurrentBytes + CurrentItems) /
1311 double(TotalBytes + TotalItems)
1314 [delegate_ setProgressPercent:percent];
1315 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1318 virtual void Start() {
1319 [delegate_ startProgress];
1322 virtual void Stop() {
1326 /* Progress Delegation {{{ */
1331 _transient id<ProgressDelegate> delegate_;
1334 virtual void Update() {
1335 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1336 [delegate_ setProgressPercent:(Percent / 100)];*/
1345 void setDelegate(id delegate) {
1346 delegate_ = delegate;
1349 virtual void Done() {
1350 //[delegate_ setProgressPercent:1];
1355 /* Database Interface {{{ */
1356 typedef std::map< unsigned long, _H<Source> > SourceMap;
1358 @interface Database : NSObject {
1364 pkgCacheFile cache_;
1365 pkgDepCache::Policy *policy_;
1366 pkgRecords *records_;
1367 pkgProblemResolver *resolver_;
1368 pkgAcquire *fetcher_;
1370 SPtr<pkgPackageManager> manager_;
1371 pkgSourceList *list_;
1374 NSMutableArray *packages_;
1376 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1385 + (Database *) sharedInstance;
1388 - (void) _readCydia:(NSNumber *)fd;
1389 - (void) _readStatus:(NSNumber *)fd;
1390 - (void) _readOutput:(NSNumber *)fd;
1394 - (Package *) packageWithName:(NSString *)name;
1396 - (pkgCacheFile &) cache;
1397 - (pkgDepCache::Policy *) policy;
1398 - (pkgRecords *) records;
1399 - (pkgProblemResolver *) resolver;
1400 - (pkgAcquire &) fetcher;
1401 - (pkgSourceList &) list;
1402 - (NSArray *) packages;
1403 - (NSArray *) sources;
1404 - (void) reloadData;
1412 - (NSString *) updateWithStatus:(Status &)status;
1414 - (void) setDelegate:(id)delegate;
1415 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1419 /* Source Class {{{ */
1420 @interface Source : NSObject {
1421 CYString description_;
1427 CYString distribution_;
1433 CYString defaultIcon_;
1435 NSDictionary *record_;
1439 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1441 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1443 - (NSString *) supportForPackage:(NSString *)package;
1445 - (NSDictionary *) record;
1449 - (NSString *) distribution;
1450 - (NSString *) type;
1452 - (NSString *) host;
1454 - (NSString *) name;
1455 - (NSString *) description;
1456 - (NSString *) label;
1457 - (NSString *) origin;
1458 - (NSString *) version;
1460 - (NSString *) defaultIcon;
1464 @implementation Source
1468 distribution_.clear();
1471 description_.clear();
1476 defaultIcon_.clear();
1478 if (record_ != nil) {
1494 + (NSArray *) _attributeKeys {
1495 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1498 - (NSArray *) attributeKeys {
1499 return [[self class] _attributeKeys];
1502 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1503 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1506 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1509 trusted_ = index->IsTrusted();
1511 uri_.set(pool, index->GetURI());
1512 distribution_.set(pool, index->GetDist());
1513 type_.set(pool, index->GetType());
1515 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1516 if (dindex != NULL) {
1518 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1521 pkgTagFile tags(&fd);
1523 pkgTagSection section;
1530 {"default-icon", &defaultIcon_},
1531 {"description", &description_},
1533 {"origin", &origin_},
1534 {"support", &support_},
1535 {"version", &version_},
1538 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1539 const char *start, *end;
1541 if (section.Find(names[i].name_, start, end)) {
1542 CYString &value(*names[i].value_);
1543 value.set(pool, start, end - start);
1549 record_ = [Sources_ objectForKey:[self key]];
1551 record_ = [record_ retain];
1553 host_ = [[[[NSURL URLWithString:uri_] host] lowercaseString] retain];
1556 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1557 if ((self = [super init]) != nil) {
1558 [self setMetaIndex:index inPool:pool];
1562 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1563 NSDictionary *lhr = [self record];
1564 NSDictionary *rhr = [source record];
1567 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1569 NSString *lhs = [self name];
1570 NSString *rhs = [source name];
1572 if ([lhs length] != 0 && [rhs length] != 0) {
1573 unichar lhc = [lhs characterAtIndex:0];
1574 unichar rhc = [rhs characterAtIndex:0];
1576 if (isalpha(lhc) && !isalpha(rhc))
1577 return NSOrderedAscending;
1578 else if (!isalpha(lhc) && isalpha(rhc))
1579 return NSOrderedDescending;
1582 return [lhs compare:rhs options:LaxCompareOptions_];
1585 - (NSString *) supportForPackage:(NSString *)package {
1586 return support_.empty() ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1589 - (NSDictionary *) record {
1597 - (NSString *) uri {
1601 - (NSString *) distribution {
1602 return distribution_;
1605 - (NSString *) type {
1609 - (NSString *) key {
1610 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1613 - (NSString *) host {
1617 - (NSString *) name {
1618 return origin_.empty() ? host_ : origin_;
1621 - (NSString *) description {
1622 return description_;
1625 - (NSString *) label {
1626 return label_.empty() ? host_ : label_;
1629 - (NSString *) origin {
1633 - (NSString *) version {
1637 - (NSString *) defaultIcon {
1638 return defaultIcon_;
1643 /* Relationship Class {{{ */
1644 @interface Relationship : NSObject {
1649 - (NSString *) type;
1651 - (NSString *) name;
1655 @implementation Relationship
1663 - (NSString *) type {
1671 - (NSString *) name {
1678 /* Package Class {{{ */
1679 @interface Package : NSObject {
1683 pkgCache::VerIterator version_;
1684 pkgCache::PkgIterator iterator_;
1685 _transient Database *database_;
1686 pkgCache::VerFileIterator file_;
1693 NSString *section$_;
1698 NSString *installed_;
1704 CYString depiction_;
1714 NSMutableArray *tags_;
1717 NSArray *relationships_;
1719 NSMutableDictionary *metadata_;
1720 _transient NSDate *firstSeen_;
1721 _transient NSDate *lastSeen_;
1725 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1726 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1728 - (pkgCache::PkgIterator) iterator;
1731 - (NSString *) section;
1732 - (NSString *) simpleSection;
1734 - (NSString *) longSection;
1735 - (NSString *) shortSection;
1739 - (Address *) maintainer;
1741 - (NSString *) longDescription;
1742 - (NSString *) shortDescription;
1745 - (NSMutableDictionary *) metadata;
1747 - (BOOL) subscribed;
1750 - (NSString *) latest;
1751 - (NSString *) installed;
1754 - (BOOL) upgradableAndEssential:(BOOL)essential;
1757 - (BOOL) unfiltered;
1761 - (BOOL) halfConfigured;
1762 - (BOOL) halfInstalled;
1764 - (NSString *) mode;
1767 - (NSString *) name;
1769 - (NSString *) homepage;
1770 - (NSString *) depiction;
1771 - (Address *) author;
1773 - (NSString *) support;
1775 - (NSArray *) files;
1776 - (NSArray *) relationships;
1777 - (NSArray *) warnings;
1778 - (NSArray *) applications;
1780 - (Source *) source;
1781 - (NSString *) role;
1783 - (BOOL) matches:(NSString *)text;
1785 - (bool) hasSupportingRole;
1786 - (BOOL) hasTag:(NSString *)tag;
1787 - (NSString *) primaryPurpose;
1788 - (NSArray *) purposes;
1789 - (bool) isCommercial;
1791 - (CYString &) cyname;
1793 - (uint32_t) compareBySection:(NSArray *)sections;
1795 - (uint32_t) compareForChanges;
1800 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1801 - (bool) isInstalledAndVisible:(NSNumber *)number;
1802 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1803 - (bool) isVisibleInSource:(Source *)source;
1807 uint32_t PackageChangesRadix(Package *self, void *) {
1812 uint32_t timestamp : 30;
1813 uint32_t ignored : 1;
1814 uint32_t upgradable : 1;
1818 bool upgradable([self upgradableAndEssential:YES]);
1819 value.bits.upgradable = upgradable ? 1 : 0;
1822 value.bits.timestamp = 0;
1823 value.bits.ignored = [self ignored] ? 0 : 1;
1824 value.bits.upgradable = 1;
1826 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1827 value.bits.ignored = 0;
1828 value.bits.upgradable = 0;
1831 return _not(uint32_t) - value.key;
1834 _finline static void Stifle(uint8_t &value) {
1837 uint32_t PackagePrefixRadix(Package *self, void *context) {
1838 size_t offset(reinterpret_cast<size_t>(context));
1839 CYString &name([self cyname]);
1841 size_t size(name.size());
1844 char *text(name.data());
1847 if (!isdigit(text[0]))
1851 while (size != digits && isdigit(text[digits]))
1861 if (offset == 0 && zeros != 0) {
1862 memset(data, '0', zeros);
1863 memcpy(data + zeros, text, 4 - zeros);
1865 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1866 if (size <= offset - zeros)
1869 text += offset - zeros;
1870 size -= offset - zeros;
1873 memcpy(data, text, 4);
1875 memcpy(data, text, size);
1876 memset(data + size, 0, 4 - size);
1879 for (size_t i(0); i != 4; ++i)
1880 if (isalpha(data[i]))
1885 data[0] = (data[0] & 0x3f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1887 /* XXX: ntohl may be more honest */
1888 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1891 CYString &(*PackageName)(Package *self, SEL sel);
1893 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1894 _profile(PackageNameCompare)
1895 CYString &lhi(PackageName(lhs, @selector(cyname)));
1896 CYString &rhi(PackageName(rhs, @selector(cyname)));
1897 CFStringRef lhn(lhi), rhn(rhi);
1899 _profile(PackageNameCompare$NumbersLast)
1900 if (!lhi.empty() && !rhi.empty()) {
1901 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1902 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1903 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1904 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1905 return lha ? NSOrderedAscending : NSOrderedDescending;
1909 CFIndex length = CFStringGetLength(lhn);
1911 _profile(PackageNameCompare$Compare)
1912 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1917 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1918 return PackageNameCompare(*lhs, *rhs, context);
1921 struct PackageNameOrdering :
1922 std::binary_function<Package *, Package *, bool>
1924 _finline bool operator ()(Package *lhs, Package *rhs) const {
1925 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1929 @implementation Package
1931 - (NSString *) description {
1932 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1938 if (section$_ != nil)
1939 [section$_ release];
1943 if (installed_ != nil)
1944 [installed_ release];
1946 if (sponsor$_ != nil)
1947 [sponsor$_ release];
1948 if (author$_ != nil)
1955 if (relationships_ != nil)
1956 [relationships_ release];
1957 if (metadata_ != nil)
1958 [metadata_ release];
1963 + (NSString *) webScriptNameForSelector:(SEL)selector {
1964 if (selector == @selector(hasTag:))
1970 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1971 return [self webScriptNameForSelector:selector] == nil;
1974 + (NSArray *) _attributeKeys {
1975 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];
1978 - (NSArray *) attributeKeys {
1979 return [[self class] _attributeKeys];
1982 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1983 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1993 _profile(Package$parse)
1994 pkgRecords::Parser *parser;
1996 _profile(Package$parse$Lookup)
1997 parser = &[database_ records]->Lookup(file_);
2002 _profile(Package$parse$Find)
2008 {"depiction", &depiction_},
2009 {"homepage", &homepage_},
2010 {"website", &website},
2011 {"support", &support_},
2012 {"sponsor", &sponsor_},
2013 {"author", &author_},
2016 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2017 const char *start, *end;
2019 if (parser->Find(names[i].name_, start, end)) {
2020 CYString &value(*names[i].value_);
2021 _profile(Package$parse$Value)
2022 value.set(pool_, start, end - start);
2028 _profile(Package$parse$Tagline)
2029 const char *start, *end;
2030 if (parser->ShortDesc(start, end)) {
2031 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2034 while (stop != start && stop[-1] == '\r')
2036 tagline_.set(pool_, start, stop - start);
2040 _profile(Package$parse$Retain)
2041 if (!homepage_.empty())
2042 homepage_ = website;
2043 if (homepage_ == depiction_)
2049 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2050 if ((self = [super init]) != nil) {
2051 _profile(Package$initWithVersion)
2052 @synchronized (database) {
2053 era_ = [database era];
2057 iterator_ = version.ParentPkg();
2058 database_ = database;
2060 _profile(Package$initWithVersion$Latest)
2061 latest_ = (NSString *) StripVersion(version_.VerStr());
2064 pkgCache::VerIterator current;
2065 _profile(Package$initWithVersion$Versions)
2066 current = iterator_.CurrentVer();
2068 installed_ = (NSString *) StripVersion(current.VerStr());
2070 if (!version_.end())
2071 file_ = version_.FileList();
2073 pkgCache &cache([database_ cache]);
2074 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2078 _profile(Package$initWithVersion$Name)
2079 id_.set(pool_, iterator_.Name());
2080 name_.set(pool, iterator_.Display());
2084 _profile(Package$initWithVersion$Source)
2085 source_ = [database_ getSource:file_.File()];
2092 _profile(Package$initWithVersion$Tags)
2093 pkgCache::TagIterator tag(iterator_.TagList());
2095 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2097 const char *name(tag.Name());
2098 [tags_ addObject:(NSString *)CFCString(name)];
2099 if (role_ == nil && strncmp(name, "role::", 6) == 0)
2100 role_ = (NSString *) CFCString(name + 6);
2102 } while (!tag.end());
2106 bool changed(false);
2107 NSString *key([id_ lowercaseString]);
2109 _profile(Package$initWithVersion$Metadata)
2110 metadata_ = [Packages_ objectForKey:key];
2112 if (metadata_ == nil) {
2115 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2116 firstSeen_, @"FirstSeen",
2117 latest_, @"LastVersion",
2122 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2123 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2125 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2126 subscribed_ = [subscribed boolValue];
2128 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2130 if (firstSeen_ == nil) {
2131 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2132 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2136 if (version == nil) {
2137 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2139 } else if (![version isEqualToString:latest_]) {
2140 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2142 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2147 metadata_ = [metadata_ retain];
2150 [Packages_ setObject:metadata_ forKey:key];
2155 _profile(Package$initWithVersion$Section)
2156 section_.set(pool_, iterator_.Section());
2159 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2160 visible_ = [self hasSupportingRole] && [self unfiltered];
2161 } _end } return self;
2164 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2165 pkgCache::VerIterator version;
2167 _profile(Package$packageWithIterator$GetCandidateVer)
2168 version = [database policy]->GetCandidateVer(iterator);
2174 return [[[Package alloc]
2175 initWithVersion:version
2182 - (pkgCache::PkgIterator) iterator {
2186 - (NSString *) section {
2187 if (section$_ == nil) {
2188 if (section_.empty())
2191 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
2192 NSString *name(section_);
2195 if (NSDictionary *value = [SectionMap_ objectForKey:name])
2196 if (NSString *rename = [value objectForKey:@"Rename"]) {
2201 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
2205 - (NSString *) simpleSection {
2206 if (NSString *section = [self section])
2207 return Simplify(section);
2212 - (NSString *) longSection {
2213 return LocalizeSection([self section]);
2216 - (NSString *) shortSection {
2217 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2220 - (NSString *) uri {
2223 pkgIndexFile *index;
2224 pkgCache::PkgFileIterator file(file_.File());
2225 if (![database_ list].FindIndex(file, index))
2227 return [NSString stringWithUTF8String:iterator_->Path];
2228 //return [NSString stringWithUTF8String:file.Site()];
2229 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2233 - (Address *) maintainer {
2236 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2237 const std::string &maintainer(parser->Maintainer());
2238 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2242 return version_.end() ? 0 : version_->InstalledSize;
2245 - (NSString *) longDescription {
2248 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2249 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2251 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2252 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2253 if ([lines count] < 2)
2256 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2257 for (size_t i(1), e([lines count]); i != e; ++i) {
2258 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2259 [trimmed addObject:trim];
2262 return [trimmed componentsJoinedByString:@"\n"];
2265 - (NSString *) shortDescription {
2270 _profile(Package$index)
2271 CFStringRef name((CFStringRef) [self name]);
2272 if (CFStringGetLength(name) == 0)
2274 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2275 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2277 return toupper(character);
2281 - (NSMutableDictionary *) metadata {
2286 if (subscribed_ && lastSeen_ != nil)
2291 - (BOOL) subscribed {
2296 NSDictionary *metadata([self metadata]);
2297 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2298 return [ignored boolValue];
2303 - (NSString *) latest {
2307 - (NSString *) installed {
2312 return !version_.end();
2315 - (BOOL) upgradableAndEssential:(BOOL)essential {
2316 _profile(Package$upgradableAndEssential)
2317 pkgCache::VerIterator current(iterator_.CurrentVer());
2319 return essential && essential_ && visible_;
2321 return !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2325 - (BOOL) essential {
2330 return [database_ cache][iterator_].InstBroken();
2333 - (BOOL) unfiltered {
2334 NSString *section([self section]);
2335 return section == nil || isSectionVisible(section);
2343 unsigned char current(iterator_->CurrentState);
2344 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2347 - (BOOL) halfConfigured {
2348 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2351 - (BOOL) halfInstalled {
2352 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2356 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2357 return state.Mode != pkgDepCache::ModeKeep;
2360 - (NSString *) mode {
2361 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2363 switch (state.Mode) {
2364 case pkgDepCache::ModeDelete:
2365 if ((state.iFlags & pkgDepCache::Purge) != 0)
2369 case pkgDepCache::ModeKeep:
2370 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2371 return @"REINSTALL";
2372 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2376 case pkgDepCache::ModeInstall:
2377 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2378 return @"REINSTALL";
2379 else*/ switch (state.Status) {
2381 return @"DOWNGRADE";
2387 return @"NEW_INSTALL";
2400 - (NSString *) name {
2401 return name_.empty() ? id_ : name_;
2404 - (UIImage *) icon {
2405 NSString *section = [self simpleSection];
2409 if ([icon_ hasPrefix:@"file:///"])
2410 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2411 if (icon == nil) if (section != nil)
2412 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2413 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2414 if ([dicon hasPrefix:@"file:///"])
2415 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2417 icon = [UIImage applicationImageNamed:@"unknown.png"];
2421 - (NSString *) homepage {
2425 - (NSString *) depiction {
2429 - (Address *) sponsor {
2430 if (sponsor$_ == nil) {
2431 if (sponsor_.empty())
2433 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2437 - (Address *) author {
2438 if (author$_ == nil) {
2439 if (author_.empty())
2441 author$_ = [[Address addressWithString:author_] retain];
2445 - (NSString *) support {
2446 return !support_.empty() ? support_ : [[self source] supportForPackage:id_];
2449 - (NSArray *) files {
2450 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2451 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2454 fin.open([path UTF8String]);
2459 while (std::getline(fin, line))
2460 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2465 - (NSArray *) relationships {
2466 return relationships_;
2469 - (NSArray *) warnings {
2470 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2471 const char *name(iterator_.Name());
2473 size_t length(strlen(name));
2474 if (length < 2) invalid:
2475 [warnings addObject:CYLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2476 else for (size_t i(0); i != length; ++i)
2478 /* XXX: technically this is not allowed */
2479 (name[i] < 'A' || name[i] > 'Z') &&
2480 (name[i] < 'a' || name[i] > 'z') &&
2481 (name[i] < '0' || name[i] > '9') &&
2482 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2485 if (strcmp(name, "cydia") != 0) {
2487 bool _private = false;
2490 bool repository = [[self section] isEqualToString:@"Repositories"];
2492 if (NSArray *files = [self files])
2493 for (NSString *file in files)
2494 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2496 else if (!_private && [file isEqualToString:@"/private"])
2498 else if (!stash && [file isEqualToString:@"/var/stash"])
2501 /* XXX: this is not sensitive enough. only some folders are valid. */
2502 if (cydia && !repository)
2503 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2505 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/private"]];
2507 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2510 return [warnings count] == 0 ? nil : warnings;
2513 - (NSArray *) applications {
2514 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2516 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2518 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2519 if (NSArray *files = [self files])
2520 for (NSString *file in files)
2521 if (application_r(file)) {
2522 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2523 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2524 if ([id isEqualToString:me])
2527 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2529 display = application_r[1];
2531 NSString *bundle([file stringByDeletingLastPathComponent]);
2532 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2533 if (icon == nil || [icon length] == 0)
2535 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2537 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2538 [applications addObject:application];
2540 [application addObject:id];
2541 [application addObject:display];
2542 [application addObject:url];
2545 return [applications count] == 0 ? nil : applications;
2548 - (Source *) source {
2550 @synchronized (database_) {
2551 if ([database_ era] != era_ || file_.end())
2554 source_ = [database_ getSource:file_.File()];
2566 - (NSString *) role {
2570 - (BOOL) matches:(NSString *)text {
2576 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2577 if (range.location != NSNotFound)
2580 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2581 if (range.location != NSNotFound)
2584 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2585 if (range.location != NSNotFound)
2591 - (bool) hasSupportingRole {
2594 if ([role_ isEqualToString:@"enduser"])
2596 if ([Role_ isEqualToString:@"User"])
2598 if ([role_ isEqualToString:@"hacker"])
2600 if ([Role_ isEqualToString:@"Hacker"])
2602 if ([role_ isEqualToString:@"developer"])
2604 if ([Role_ isEqualToString:@"Developer"])
2609 - (BOOL) hasTag:(NSString *)tag {
2610 return tags_ == nil ? NO : [tags_ containsObject:tag];
2613 - (NSString *) primaryPurpose {
2614 for (NSString *tag in tags_)
2615 if ([tag hasPrefix:@"purpose::"])
2616 return [tag substringFromIndex:9];
2620 - (NSArray *) purposes {
2621 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2622 for (NSString *tag in tags_)
2623 if ([tag hasPrefix:@"purpose::"])
2624 [purposes addObject:[tag substringFromIndex:9]];
2625 return [purposes count] == 0 ? nil : purposes;
2628 - (bool) isCommercial {
2629 return [self hasTag:@"cydia::commercial"];
2632 - (CYString &) cyname {
2633 return name_.empty() ? id_ : name_;
2636 - (uint32_t) compareBySection:(NSArray *)sections {
2637 NSString *section([self section]);
2638 for (size_t i(0), e([sections count]); i != e; ++i) {
2639 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2643 return _not(uint32_t);
2646 - (uint32_t) compareForChanges {
2651 uint32_t timestamp : 30;
2652 uint32_t ignored : 1;
2653 uint32_t upgradable : 1;
2657 bool upgradable([self upgradableAndEssential:YES]);
2658 value.bits.upgradable = upgradable ? 1 : 0;
2661 value.bits.timestamp = 0;
2662 value.bits.ignored = [self ignored] ? 0 : 1;
2663 value.bits.upgradable = 1;
2665 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2666 value.bits.ignored = 0;
2667 value.bits.upgradable = 0;
2670 return _not(uint32_t) - value.key;
2674 pkgProblemResolver *resolver = [database_ resolver];
2675 resolver->Clear(iterator_);
2676 resolver->Protect(iterator_);
2680 pkgProblemResolver *resolver = [database_ resolver];
2681 resolver->Clear(iterator_);
2682 resolver->Protect(iterator_);
2683 pkgCacheFile &cache([database_ cache]);
2684 cache->MarkInstall(iterator_, false);
2685 pkgDepCache::StateCache &state((*cache)[iterator_]);
2686 if (!state.Install())
2687 cache->SetReInstall(iterator_, true);
2691 pkgProblemResolver *resolver = [database_ resolver];
2692 resolver->Clear(iterator_);
2693 resolver->Protect(iterator_);
2694 resolver->Remove(iterator_);
2695 [database_ cache]->MarkDelete(iterator_, true);
2698 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2699 _profile(Package$isUnfilteredAndSearchedForBy)
2702 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2703 value &= [self unfiltered];
2706 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2707 value &= [self matches:search];
2714 - (bool) isInstalledAndVisible:(NSNumber *)number {
2715 return (![number boolValue] || [self visible]) && [self installed] != nil;
2718 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2719 NSString *section = [self section];
2723 [self installed] == nil && (
2725 section == nil && [name length] == 0 ||
2726 [name isEqualToString:section]
2730 - (bool) isVisibleInSource:(Source *)source {
2731 return [self source] == source && [self visible];
2736 /* Section Class {{{ */
2737 @interface Section : NSObject {
2742 NSString *localized_;
2745 - (NSComparisonResult) compareByLocalized:(Section *)section;
2746 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2747 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2748 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2749 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2750 - (NSString *) name;
2757 - (void) addToCount;
2759 - (void) setCount:(size_t)count;
2760 - (NSString *) localized;
2764 @implementation Section
2768 if (localized_ != nil)
2769 [localized_ release];
2773 - (NSComparisonResult) compareByLocalized:(Section *)section {
2774 NSString *lhs(localized_);
2775 NSString *rhs([section localized]);
2777 /*if ([lhs length] != 0 && [rhs length] != 0) {
2778 unichar lhc = [lhs characterAtIndex:0];
2779 unichar rhc = [rhs characterAtIndex:0];
2781 if (isalpha(lhc) && !isalpha(rhc))
2782 return NSOrderedAscending;
2783 else if (!isalpha(lhc) && isalpha(rhc))
2784 return NSOrderedDescending;
2787 return [lhs compare:rhs options:LaxCompareOptions_];
2790 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2791 if ((self = [self initWithName:name localize:NO]) != nil) {
2792 if (localized != nil)
2793 localized_ = [localized retain];
2797 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2798 return [self initWithName:name row:0 localize:localize];
2801 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2802 if ((self = [super init]) != nil) {
2803 name_ = [name retain];
2807 localized_ = [LocalizeSection(name_) retain];
2811 /* XXX: localize the index thingees */
2812 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2813 if ((self = [super init]) != nil) {
2814 name_ = [(index == '#' ? @"123" : [NSString stringWithCharacters:&index length:1]) retain];
2820 - (NSString *) name {
2840 - (void) addToCount {
2844 - (void) setCount:(size_t)count {
2848 - (NSString *) localized {
2856 static NSArray *Finishes_;
2858 /* Database Implementation {{{ */
2859 @implementation Database
2861 + (Database *) sharedInstance {
2862 static Database *instance;
2863 if (instance == nil)
2864 instance = [[Database alloc] init];
2874 NSRecycleZone(zone_);
2875 // XXX: malloc_destroy_zone(zone_);
2876 apr_pool_destroy(pool_);
2880 - (void) _readCydia:(NSNumber *)fd { _pooled
2881 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2882 std::istream is(&ib);
2885 static Pcre finish_r("^finish:([^:]*)$");
2887 while (std::getline(is, line)) {
2888 const char *data(line.c_str());
2889 size_t size = line.size();
2890 lprintf("C:%s\n", data);
2892 if (finish_r(data, size)) {
2893 NSString *finish = finish_r[1];
2894 int index = [Finishes_ indexOfObject:finish];
2895 if (index != INT_MAX && index > Finish_)
2903 - (void) _readStatus:(NSNumber *)fd { _pooled
2904 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2905 std::istream is(&ib);
2908 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2909 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2911 while (std::getline(is, line)) {
2912 const char *data(line.c_str());
2913 size_t size = line.size();
2914 lprintf("S:%s\n", data);
2916 if (conffile_r(data, size)) {
2917 [delegate_ setConfigurationData:conffile_r[1]];
2918 } else if (strncmp(data, "status: ", 8) == 0) {
2919 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2920 [delegate_ setProgressTitle:string];
2921 } else if (pmstatus_r(data, size)) {
2922 std::string type([pmstatus_r[1] UTF8String]);
2923 NSString *id = pmstatus_r[2];
2925 float percent([pmstatus_r[3] floatValue]);
2926 [delegate_ setProgressPercent:(percent / 100)];
2928 NSString *string = pmstatus_r[4];
2930 if (type == "pmerror")
2931 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2932 withObject:[NSArray arrayWithObjects:string, id, nil]
2935 else if (type == "pmstatus") {
2936 [delegate_ setProgressTitle:string];
2937 } else if (type == "pmconffile")
2938 [delegate_ setConfigurationData:string];
2939 else _assert(false);
2940 } else _assert(false);
2946 - (void) _readOutput:(NSNumber *)fd { _pooled
2947 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2948 std::istream is(&ib);
2951 while (std::getline(is, line)) {
2952 lprintf("O:%s\n", line.c_str());
2953 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2963 - (Package *) packageWithName:(NSString *)name {
2964 if (static_cast<pkgDepCache *>(cache_) == NULL)
2966 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
2967 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
2970 - (Database *) init {
2971 if ((self = [super init]) != nil) {
2978 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
2979 apr_pool_create(&pool_, NULL);
2981 packages_ = [[NSMutableArray alloc] init];
2985 _assert(pipe(fds) != -1);
2988 _config->Set("APT::Keep-Fds::", cydiafd_);
2989 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
2992 detachNewThreadSelector:@selector(_readCydia:)
2994 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2997 _assert(pipe(fds) != -1);
3001 detachNewThreadSelector:@selector(_readStatus:)
3003 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3006 _assert(pipe(fds) != -1);
3007 _assert(dup2(fds[0], 0) != -1);
3008 _assert(close(fds[0]) != -1);
3010 input_ = fdopen(fds[1], "a");
3012 _assert(pipe(fds) != -1);
3013 _assert(dup2(fds[1], 1) != -1);
3014 _assert(close(fds[1]) != -1);
3017 detachNewThreadSelector:@selector(_readOutput:)
3019 withObject:[[NSNumber numberWithInt:fds[0]] retain]
3024 - (pkgCacheFile &) cache {
3028 - (pkgDepCache::Policy *) policy {
3032 - (pkgRecords *) records {
3036 - (pkgProblemResolver *) resolver {
3040 - (pkgAcquire &) fetcher {
3044 - (pkgSourceList &) list {
3048 - (NSArray *) packages {
3052 - (NSArray *) sources {
3053 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3054 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3055 [sources addObject:i->second];
3059 - (NSArray *) issues {
3060 if (cache_->BrokenCount() == 0)
3063 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3065 for (Package *package in packages_) {
3066 if (![package broken])
3068 pkgCache::PkgIterator pkg([package iterator]);
3070 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3071 [entry addObject:[package name]];
3072 [issues addObject:entry];
3074 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3078 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3079 pkgCache::DepIterator start;
3080 pkgCache::DepIterator end;
3081 dep.GlobOr(start, end); // ++dep
3083 if (!cache_->IsImportantDep(end))
3085 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3088 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3089 [entry addObject:failure];
3090 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3092 Package *package([self packageWithName:[NSString stringWithUTF8String:start.TargetPkg().Name()]]);
3093 [failure addObject:[package name]];
3095 pkgCache::PkgIterator target(start.TargetPkg());
3096 if (target->ProvidesList != 0)
3097 [failure addObject:@"?"];
3099 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3101 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3102 else if (!cache_[target].CandidateVerIter(cache_).end())
3103 [failure addObject:@"-"];
3104 else if (target->ProvidesList == 0)
3105 [failure addObject:@"!"];
3107 [failure addObject:@"%"];
3111 if (start.TargetVer() != 0)
3112 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3123 - (void) reloadData { _pooled
3124 @synchronized (self) {
3128 [packages_ removeAllObjects];
3154 apr_pool_clear(pool_);
3155 NSRecycleZone(zone_);
3157 int chk(creat("/tmp/cydia.chk", 0644));
3162 if (!cache_.Open(progress_, true)) {
3164 if (!_error->PopMessage(error))
3167 lprintf("cache_.Open():[%s]\n", error.c_str());
3169 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3170 [delegate_ repairWithSelector:@selector(configure)];
3171 else if (error == "The package lists or status file could not be parsed or opened.")
3172 [delegate_ repairWithSelector:@selector(update)];
3173 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3174 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3175 // else if (error == "The list of sources could not be read.")
3176 else _assert(false);
3182 unlink("/tmp/cydia.chk");
3184 now_ = [[NSDate date] retain];
3186 policy_ = new pkgDepCache::Policy();
3187 records_ = new pkgRecords(cache_);
3188 resolver_ = new pkgProblemResolver(cache_);
3189 fetcher_ = new pkgAcquire(&status_);
3192 list_ = new pkgSourceList();
3193 _assert(list_->ReadMainList());
3195 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
3196 _assert(pkgApplyStatus(cache_));
3198 if (cache_->BrokenCount() != 0) {
3199 _assert(pkgFixBroken(cache_));
3200 _assert(cache_->BrokenCount() == 0);
3201 _assert(pkgMinimizeUpgrade(cache_));
3206 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3207 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3208 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3209 // XXX: this could be more intelligent
3210 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3211 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3213 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3220 /*std::vector<Package *> packages;
3221 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3222 [packages_ release];
3227 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3228 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3229 //packages.push_back(package);
3230 [packages_ addObject:package];
3234 /*if (packages.empty())
3235 packages_ = [[NSArray alloc] init];
3237 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3240 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3241 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3242 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3250 /*if (!packages.empty())
3251 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3252 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3254 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3256 CFArrayInsertionSortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3258 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3264 - (void) configure {
3265 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3266 system([dpkg UTF8String]);
3274 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3275 _assert(!_error->PendingError());
3278 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3281 public pkgArchiveCleaner
3284 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3289 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3291 while (_error->PopMessage(error))
3292 lprintf("ArchiveCleaner: %s\n", error.c_str());
3297 pkgRecords records(cache_);
3299 lock_ = new FileFd();
3300 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3301 _assert(!_error->PendingError());
3304 // XXX: explain this with an error message
3305 _assert(list.ReadMainList());
3307 manager_ = (_system->CreatePM(cache_));
3308 _assert(manager_->GetArchives(fetcher_, &list, &records));
3309 _assert(!_error->PendingError());
3313 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3315 _assert(list.ReadMainList());
3316 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3317 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3320 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3325 bool failed = false;
3326 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3327 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3330 std::string uri = (*item)->DescURI();
3331 std::string error = (*item)->ErrorText;
3333 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3336 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3337 withObject:[NSArray arrayWithObjects:
3338 [NSString stringWithUTF8String:error.c_str()],
3350 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3352 if (_error->PendingError()) {
3357 if (result == pkgPackageManager::Failed) {
3362 if (result != pkgPackageManager::Completed) {
3367 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3369 _assert(list.ReadMainList());
3370 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3371 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3374 if (![before isEqualToArray:after])
3379 _assert(pkgDistUpgrade(cache_));
3383 [self updateWithStatus:status_];
3386 - (NSString *) updateWithStatus:(Status &)status {
3388 _assert(list.ReadMainList());
3391 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3393 if (_error->PendingError()) {
3395 if (!_error->PopMessage(error))
3398 return [NSString stringWithUTF8String:error.c_str()];
3401 pkgAcquire fetcher(&status);
3402 _assert(list.GetIndexes(&fetcher));
3404 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3405 bool failed = false;
3406 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3407 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3408 (*item)->Finished();
3412 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3413 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3414 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3417 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3424 - (void) setDelegate:(id)delegate {
3425 delegate_ = delegate;
3426 status_.setDelegate(delegate);
3427 progress_.setDelegate(delegate);
3430 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3431 return sources_[file->ID];
3437 /* PopUp Windows {{{ */
3438 @interface PopUpView : UIView {
3439 _transient id delegate_;
3440 UITransitionView *transition_;
3445 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3449 @implementation PopUpView
3452 [transition_ setDelegate:nil];
3453 [transition_ release];
3459 [transition_ transition:UITransitionPushFromTop toView:nil];
3462 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3463 if (from != nil && to == nil)
3464 [self removeFromSuperview];
3467 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3468 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3469 delegate_ = delegate;
3471 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3472 [self addSubview:transition_];
3474 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3476 [view addSubview:self];
3478 [transition_ setDelegate:self];
3480 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3481 [transition_ transition:UITransitionNone toView:blank];
3482 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3490 /* Mail Composition {{{ */
3491 @interface MailToView : PopUpView {
3492 MailComposeController *controller_;
3495 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
3499 @implementation MailToView
3502 [controller_ release];
3506 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
3510 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
3511 NSLog(@"did:%@", delivery);
3512 // [UIApp setStatusBarShowsProgress:NO];
3513 if ([controller error]){
3514 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3515 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3516 [mailAlertSheet setBodyText:[controller error]];
3517 [mailAlertSheet popupAlertAnimated:YES];
3521 - (void) showError {
3522 NSLog(@"%@", [controller_ error]);
3523 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3524 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3525 [mailAlertSheet setBodyText:[controller_ error]];
3526 [mailAlertSheet popupAlertAnimated:YES];
3529 - (void) deliverMessage { _pooled
3533 if (![controller_ deliverMessage])
3534 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
3537 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
3538 if ([controller_ needsDelivery])
3539 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
3544 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
3545 if ((self = [super initWithView:view delegate:delegate]) != nil) {
3546 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
3547 [controller_ setDelegate:self];
3548 [controller_ initializeUI];
3549 [controller_ setupForURL:url];
3551 UIView *view([controller_ view]);
3552 [overlay_ addSubview:view];
3560 /* Confirmation View {{{ */
3561 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3562 if (!iterator.end())
3563 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3564 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3566 pkgCache::PkgIterator package(dep.TargetPkg());
3569 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3576 @protocol ConfirmationViewDelegate
3582 @interface ConfirmationView : BrowserView {
3583 _transient Database *database_;
3584 UIActionSheet *essential_;
3591 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3595 @implementation ConfirmationView
3602 if (essential_ != nil)
3603 [essential_ release];
3609 [book_ popFromSuperviewAnimated:YES];
3612 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3613 NSString *context([sheet context]);
3615 if ([context isEqualToString:@"remove"]) {
3623 [delegate_ confirm];
3630 } else if ([context isEqualToString:@"unable"]) {
3634 [super alertSheet:sheet buttonClicked:button];
3637 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3638 [super webView:sender didClearWindowObject:window forFrame:frame];
3639 [window setValue:changes_ forKey:@"changes"];
3640 [window setValue:issues_ forKey:@"issues"];
3641 [window setValue:sizes_ forKey:@"sizes"];
3644 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3645 if ((self = [super initWithBook:book]) != nil) {
3646 database_ = database;
3648 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3649 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3650 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3651 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3652 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3656 pkgDepCache::Policy *policy([database_ policy]);
3658 pkgCacheFile &cache([database_ cache]);
3659 NSArray *packages = [database_ packages];
3660 for (Package *package in packages) {
3661 pkgCache::PkgIterator iterator = [package iterator];
3662 pkgDepCache::StateCache &state(cache[iterator]);
3664 NSString *name([package name]);
3666 if (state.NewInstall())
3667 [installing addObject:name];
3668 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3669 [reinstalling addObject:name];
3670 else if (state.Upgrade())
3671 [upgrading addObject:name];
3672 else if (state.Downgrade())
3673 [downgrading addObject:name];
3674 else if (state.Delete()) {
3675 if ([package essential])
3677 [removing addObject:name];
3680 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3681 substrate_ |= DepSubstrate(iterator.CurrentVer());
3686 else if (Advanced_ || true) {
3687 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
3689 essential_ = [[UIActionSheet alloc]
3690 initWithTitle:CYLocalize("REMOVING_ESSENTIALS")
3691 buttons:[NSArray arrayWithObjects:
3692 [NSString stringWithFormat:parenthetical, CYLocalize("CANCEL_OPERATION"), CYLocalize("SAFE")],
3693 [NSString stringWithFormat:parenthetical, CYLocalize("FORCE_REMOVAL"), CYLocalize("UNSAFE")],
3695 defaultButtonIndex:0
3701 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3703 [essential_ setBodyText:CYLocalize("REMOVING_ESSENTIALS_EX")];
3705 essential_ = [[UIActionSheet alloc]
3706 initWithTitle:CYLocalize("UNABLE_TO_COMPLY")
3707 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3708 defaultButtonIndex:0
3713 [essential_ setBodyText:CYLocalize("UNABLE_TO_COMPLY_EX")];
3716 changes_ = [[NSArray alloc] initWithObjects:
3724 issues_ = [database_ issues];
3726 issues_ = [issues_ retain];
3728 sizes_ = [[NSArray alloc] initWithObjects:
3729 SizeString([database_ fetcher].FetchNeeded()),
3730 SizeString([database_ fetcher].PartialPresent()),
3731 SizeString([database_ cache]->UsrSize()),
3734 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3738 - (NSString *) backButtonTitle {
3739 return CYLocalize("CONFIRM");
3742 - (NSString *) leftButtonTitle {
3743 return [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("CANCEL"), CYLocalize("QUEUE")];
3746 - (id) rightButtonTitle {
3747 return issues_ != nil ? nil : [super rightButtonTitle];
3750 - (id) _rightButtonTitle {
3751 #if AlwaysReload || IgnoreInstall
3752 return [super _rightButtonTitle];
3754 return CYLocalize("CONFIRM");
3758 - (void) _leftButtonClicked {
3763 - (void) _rightButtonClicked {
3765 return [super _rightButtonClicked];
3767 if (essential_ != nil)
3768 [essential_ popupAlertAnimated:YES];
3772 [delegate_ confirm];
3780 /* Progress Data {{{ */
3781 @interface ProgressData : NSObject {
3787 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3794 @implementation ProgressData
3796 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3797 if ((self = [super init]) != nil) {
3798 selector_ = selector;
3818 /* Progress View {{{ */
3819 @interface ProgressView : UIView <
3820 ConfigurationDelegate,
3823 _transient Database *database_;
3825 UIView *background_;
3826 UITransitionView *transition_;
3828 UINavigationBar *navbar_;
3829 UIProgressBar *progress_;
3830 UITextView *output_;
3831 UITextLabel *status_;
3832 UIPushButton *close_;
3835 SHA1SumValue springlist_;
3836 SHA1SumValue notifyconf_;
3837 SHA1SumValue sandplate_;
3840 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
3842 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
3843 - (void) setContentView:(UIView *)view;
3846 - (void) _retachThread;
3847 - (void) _detachNewThreadData:(ProgressData *)data;
3848 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
3854 @protocol ProgressViewDelegate
3855 - (void) progressViewIsComplete:(ProgressView *)sender;
3858 @implementation ProgressView
3861 [transition_ setDelegate:nil];
3862 [navbar_ setDelegate:nil];
3865 if (background_ != nil)
3866 [background_ release];
3867 [transition_ release];
3870 [progress_ release];
3877 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3878 if (bootstrap_ && from == overlay_ && to == view_)
3882 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
3883 if ((self = [super initWithFrame:frame]) != nil) {
3884 database_ = database;
3885 delegate_ = delegate;
3887 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3888 [transition_ setDelegate:self];
3890 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3893 [overlay_ setBackgroundColor:[UIColor blackColor]];
3895 background_ = [[UIView alloc] initWithFrame:[self bounds]];
3896 [background_ setBackgroundColor:[UIColor blackColor]];
3897 [self addSubview:background_];
3900 [self addSubview:transition_];
3902 CGSize navsize = [UINavigationBar defaultSize];
3903 CGRect navrect = {{0, 0}, navsize};
3905 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
3906 [overlay_ addSubview:navbar_];
3908 [navbar_ setBarStyle:1];
3909 [navbar_ setDelegate:self];
3911 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
3912 [navbar_ pushNavigationItem:navitem];
3914 CGRect bounds = [overlay_ bounds];
3915 CGSize prgsize = [UIProgressBar defaultSize];
3918 (bounds.size.width - prgsize.width) / 2,
3919 bounds.size.height - prgsize.height - 20
3922 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3923 [progress_ setStyle:0];
3925 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3927 bounds.size.height - prgsize.height - 50,
3928 bounds.size.width - 20,
3932 [status_ setColor:[UIColor whiteColor]];
3933 [status_ setBackgroundColor:[UIColor clearColor]];
3935 [status_ setCentersHorizontally:YES];
3936 //[status_ setFont:font];
3939 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3941 navrect.size.height + 20,
3942 bounds.size.width - 20,
3943 bounds.size.height - navsize.height - 62 - navrect.size.height
3947 //[output_ setTextFont:@"Courier New"];
3948 [output_ setTextSize:12];
3950 [output_ setTextColor:[UIColor whiteColor]];
3951 [output_ setBackgroundColor:[UIColor clearColor]];
3953 [output_ setMarginTop:0];
3954 [output_ setAllowsRubberBanding:YES];
3955 [output_ setEditable:NO];
3957 [overlay_ addSubview:output_];
3959 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3961 bounds.size.height - prgsize.height - 50,
3962 bounds.size.width - 20,
3966 [close_ setAutosizesToFit:NO];
3967 [close_ setDrawsShadow:YES];
3968 [close_ setStretchBackground:YES];
3969 [close_ setEnabled:YES];
3971 UIFont *bold = [UIFont boldSystemFontOfSize:22];
3972 [close_ setTitleFont:bold];
3974 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
3975 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
3976 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
3980 - (void) setContentView:(UIView *)view {
3981 view_ = [view retain];
3984 - (void) resetView {
3985 [transition_ transition:6 toView:view_];
3988 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3989 NSString *context([sheet context]);
3991 if ([context isEqualToString:@"error"])
3993 else if ([context isEqualToString:@"conffile"]) {
3994 FILE *input = [database_ input];
3998 fprintf(input, "N\n");
4002 fprintf(input, "Y\n");
4013 - (void) closeButtonPushed {
4022 [delegate_ suspendWithAnimation:YES];
4026 system("launchctl stop com.apple.SpringBoard");
4030 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4039 - (void) _retachThread {
4040 UINavigationItem *item = [navbar_ topItem];
4041 [item setTitle:CYLocalize("COMPLETE")];
4043 [overlay_ addSubview:close_];
4044 [progress_ removeFromSuperview];
4045 [status_ removeFromSuperview];
4047 [delegate_ progressViewIsComplete:self];
4050 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4051 MMap mmap(file, MMap::ReadOnly);
4053 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4054 if (!(sandplate_ == sha1.Result()))
4059 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4060 MMap mmap(file, MMap::ReadOnly);
4062 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4063 if (!(notifyconf_ == sha1.Result()))
4068 FileFd file(SpringBoard_, FileFd::ReadOnly);
4069 MMap mmap(file, MMap::ReadOnly);
4071 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4072 if (!(springlist_ == sha1.Result()))
4077 case 0: [close_ setTitle:CYLocalize("RETURN_TO_CYDIA")]; break;
4078 case 1: [close_ setTitle:CYLocalize("CLOSE_CYDIA")]; break;
4079 case 2: [close_ setTitle:CYLocalize("RESTART_SPRINGBOARD")]; break;
4080 case 3: [close_ setTitle:CYLocalize("RELOAD_SPRINGBOARD")]; break;
4081 case 4: [close_ setTitle:CYLocalize("REBOOT_DEVICE")]; break;
4084 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
4086 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
4087 [cache autorelease];
4089 NSFileManager *manager = [NSFileManager defaultManager];
4090 NSError *error = nil;
4092 id system = [cache objectForKey:@"System"];
4097 if (stat(Cache_, &info) == -1)
4100 [system removeAllObjects];
4102 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
4103 for (NSString *app in apps)
4104 if ([app hasSuffix:@".app"]) {
4105 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
4106 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
4107 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
4109 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
4110 [info setObject:path forKey:@"Path"];
4111 [info setObject:@"System" forKey:@"ApplicationType"];
4112 [system addInfoDictionary:info];
4118 [cache writeToFile:@Cache_ atomically:YES];
4120 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
4122 if (chmod(Cache_, info.st_mode) == -1)
4126 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
4129 notify_post("com.apple.mobile.application_installed");
4131 [delegate_ setStatusBarShowsProgress:NO];
4134 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4135 [[data target] performSelector:[data selector] withObject:[data object]];
4138 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4141 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4142 UINavigationItem *item = [navbar_ topItem];
4143 [item setTitle:title];
4145 [status_ setText:nil];
4146 [output_ setText:@""];
4147 [progress_ setProgress:0];
4149 [close_ removeFromSuperview];
4150 [overlay_ addSubview:progress_];
4151 [overlay_ addSubview:status_];
4153 [delegate_ setStatusBarShowsProgress:YES];
4157 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
4158 MMap mmap(file, MMap::ReadOnly);
4160 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4161 sandplate_ = sha1.Result();
4165 FileFd file(NotifyConfig_, FileFd::ReadOnly);
4166 MMap mmap(file, MMap::ReadOnly);
4168 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4169 notifyconf_ = sha1.Result();
4173 FileFd file(SpringBoard_, FileFd::ReadOnly);
4174 MMap mmap(file, MMap::ReadOnly);
4176 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4177 springlist_ = sha1.Result();
4180 [transition_ transition:6 toView:overlay_];
4183 detachNewThreadSelector:@selector(_detachNewThreadData:)
4185 withObject:[[ProgressData alloc]
4186 initWithSelector:selector
4193 - (void) repairWithSelector:(SEL)selector {
4195 detachNewThreadSelector:selector
4198 title:CYLocalize("REPAIRING")
4202 - (void) setConfigurationData:(NSString *)data {
4204 performSelectorOnMainThread:@selector(_setConfigurationData:)
4210 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
4211 Package *package = id == nil ? nil : [database_ packageWithName:id];
4213 UIActionSheet *sheet = [[[UIActionSheet alloc]
4214 initWithTitle:(package == nil ? id : [package name])
4215 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
4216 defaultButtonIndex:0
4221 [sheet setBodyText:error];
4222 [sheet popupAlertAnimated:YES];
4225 - (void) setProgressTitle:(NSString *)title {
4227 performSelectorOnMainThread:@selector(_setProgressTitle:)
4233 - (void) setProgressPercent:(float)percent {
4235 performSelectorOnMainThread:@selector(_setProgressPercent:)
4236 withObject:[NSNumber numberWithFloat:percent]
4241 - (void) startProgress {
4244 - (void) addProgressOutput:(NSString *)output {
4246 performSelectorOnMainThread:@selector(_addProgressOutput:)
4252 - (bool) isCancelling:(size_t)received {
4256 - (void) _setConfigurationData:(NSString *)data {
4257 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4259 _assert(conffile_r(data));
4261 NSString *ofile = conffile_r[1];
4262 //NSString *nfile = conffile_r[2];
4264 UIActionSheet *sheet = [[[UIActionSheet alloc]
4265 initWithTitle:CYLocalize("CONFIGURATION_UPGRADE")
4266 buttons:[NSArray arrayWithObjects:
4267 CYLocalize("KEEP_OLD_COPY"),
4268 CYLocalize("ACCEPT_NEW_COPY"),
4269 // XXX: CYLocalize("SEE_WHAT_CHANGED"),
4271 defaultButtonIndex:0
4276 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", CYLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
4277 [sheet popupAlertAnimated:YES];
4280 - (void) _setProgressTitle:(NSString *)title {
4281 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4282 for (size_t i(0), e([words count]); i != e; ++i) {
4283 NSString *word([words objectAtIndex:i]);
4284 if (Package *package = [database_ packageWithName:word])
4285 [words replaceObjectAtIndex:i withObject:[package name]];
4288 [status_ setText:[words componentsJoinedByString:@" "]];
4291 - (void) _setProgressPercent:(NSNumber *)percent {
4292 [progress_ setProgress:[percent floatValue]];
4295 - (void) _addProgressOutput:(NSString *)output {
4296 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4297 CGSize size = [output_ contentSize];
4298 CGRect rect = {{0, size.height}, {size.width, 0}};
4299 [output_ scrollRectToVisible:rect animated:YES];
4302 - (BOOL) isRunning {
4309 /* Package Cell {{{ */
4310 @interface PackageCell : UITableCell {
4313 NSString *description_;
4320 UITextLabel *status_;
4324 - (PackageCell *) init;
4325 - (void) setPackage:(Package *)package;
4327 + (int) heightForPackage:(Package *)package;
4331 @implementation PackageCell
4333 - (void) clearPackage {
4344 if (description_ != nil) {
4345 [description_ release];
4349 if (source_ != nil) {
4354 if (badge_ != nil) {
4364 [self clearPackage];
4371 - (PackageCell *) init {
4372 if ((self = [super init]) != nil) {
4374 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4375 [status_ setBackgroundColor:[UIColor clearColor]];
4376 [status_ setFont:small];
4381 - (void) setPackage:(Package *)package {
4382 [self clearPackage];
4385 Source *source = [package source];
4387 icon_ = [[package icon] retain];
4388 name_ = [[package name] retain];
4389 description_ = [[package shortDescription] retain];
4390 commercial_ = [package isCommercial];
4392 package_ = [package retain];
4394 NSString *label = nil;
4395 bool trusted = false;
4397 if (source != nil) {
4398 label = [source label];
4399 trusted = [source trusted];
4400 } else if ([[package id] isEqualToString:@"firmware"])
4401 label = CYLocalize("APPLE");
4403 label = [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("UNKNOWN"), CYLocalize("LOCAL")];
4405 NSString *from(label);
4407 NSString *section = [package simpleSection];
4408 if (section != nil && ![section isEqualToString:label]) {
4409 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4410 from = [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), from, section];
4413 from = [NSString stringWithFormat:CYLocalize("FROM"), from];
4414 source_ = [from retain];
4416 if (NSString *purpose = [package primaryPurpose])
4417 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4418 badge_ = [badge_ retain];
4421 if (NSString *mode = [package mode]) {
4422 [badge_ setImage:[UIImage applicationImageNamed:
4423 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4426 [status_ setText:[NSString stringWithFormat:CYLocalize("QUEUED_FOR"), CYLocalize(mode)]];
4427 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4428 } else if ([package half]) {
4429 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4430 [status_ setText:CYLocalize("PACKAGE_DAMAGED")];
4431 [status_ setColor:[UIColor redColor]];
4433 [badge_ setImage:nil];
4434 [status_ setText:nil];
4441 - (void) drawRect:(CGRect)rect {
4445 if (NSString *mode = [package_ mode]) {
4446 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4447 color = remove ? RemovingColor_ : InstallingColor_;
4449 color = [UIColor whiteColor];
4451 [self setBackgroundColor:color];
4455 [super drawRect:rect];
4458 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4460 CGContextRef context(UIGraphicsGetCurrentContext());
4461 [[self backgroundColor] set];
4463 back.size.height -= 1;
4464 CGContextFillRect(context, back);
4467 [super drawBackgroundInRect:rect withFade:fade];
4470 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4473 rect.size = [icon_ size];
4475 rect.size.width /= 2;
4476 rect.size.height /= 2;
4478 rect.origin.x = 25 - rect.size.width / 2;
4479 rect.origin.y = 25 - rect.size.height / 2;
4481 [icon_ drawInRect:rect];
4484 if (badge_ != nil) {
4485 CGSize size = [badge_ size];
4487 [badge_ drawAtPoint:CGPointMake(
4488 36 - size.width / 2,
4489 36 - size.height / 2
4497 UISetColor(commercial_ ? Purple_ : Black_);
4498 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4499 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4502 UISetColor(commercial_ ? Purplish_ : Gray_);
4503 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4505 [super drawContentInRect:rect selected:selected];
4508 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4510 [super setSelected:selected withFade:fade];
4513 + (int) heightForPackage:(Package *)package {
4519 /* Section Cell {{{ */
4520 @interface SectionCell : UISimpleTableCell {
4525 _UISwitchSlider *switch_;
4530 - (void) setSection:(Section *)section editing:(BOOL)editing;
4534 @implementation SectionCell
4536 - (void) clearSection {
4537 if (section_ != nil) {
4547 if (count_ != nil) {
4554 [self clearSection];
4561 if ((self = [super init]) != nil) {
4562 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4564 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4565 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4569 - (void) onSwitch:(id)sender {
4570 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4571 if (metadata == nil) {
4572 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4573 [Sections_ setObject:metadata forKey:section_];
4577 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4580 - (void) setSection:(Section *)section editing:(BOOL)editing {
4581 if (editing != editing_) {
4583 [switch_ removeFromSuperview];
4585 [self addSubview:switch_];
4589 [self clearSection];
4591 if (section == nil) {
4592 name_ = [CYLocalize("ALL_PACKAGES") retain];
4595 section_ = [section localized];
4596 if (section_ != nil)
4597 section_ = [section_ retain];
4598 name_ = [(section_ == nil ? CYLocalize("NO_SECTION") : section_) retain];
4599 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4602 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4606 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4607 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4614 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4616 CGSize size = [count_ sizeWithFont:Font14_];
4620 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4622 [super drawContentInRect:rect selected:selected];
4628 /* File Table {{{ */
4629 @interface FileTable : RVPage {
4630 _transient Database *database_;
4633 NSMutableArray *files_;
4637 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4638 - (void) setPackage:(Package *)package;
4642 @implementation FileTable
4645 if (package_ != nil)
4654 - (int) numberOfRowsInTable:(UITable *)table {
4655 return files_ == nil ? 0 : [files_ count];
4658 - (float) table:(UITable *)table heightForRow:(int)row {
4662 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4663 if (reusing == nil) {
4664 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4665 UIFont *font = [UIFont systemFontOfSize:16];
4666 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4668 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4672 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4676 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4677 if ((self = [super initWithBook:book]) != nil) {
4678 database_ = database;
4680 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4682 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4683 [self addSubview:list_];
4685 UITableColumn *column = [[[UITableColumn alloc]
4686 initWithTitle:CYLocalize("NAME")
4688 width:[self frame].size.width
4691 [list_ setDataSource:self];
4692 [list_ setSeparatorStyle:1];
4693 [list_ addTableColumn:column];
4694 [list_ setDelegate:self];
4695 [list_ setReusesTableCells:YES];
4699 - (void) setPackage:(Package *)package {
4700 if (package_ != nil) {
4701 [package_ autorelease];
4710 [files_ removeAllObjects];
4712 if (package != nil) {
4713 package_ = [package retain];
4714 name_ = [[package id] retain];
4716 if (NSArray *files = [package files])
4717 [files_ addObjectsFromArray:files];
4719 if ([files_ count] != 0) {
4720 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4721 [files_ removeObjectAtIndex:0];
4722 [files_ sortUsingSelector:@selector(compareByPath:)];
4724 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4725 [stack addObject:@"/"];
4727 for (int i(0), e([files_ count]); i != e; ++i) {
4728 NSString *file = [files_ objectAtIndex:i];
4729 while (![file hasPrefix:[stack lastObject]])
4730 [stack removeLastObject];
4731 NSString *directory = [stack lastObject];
4732 [stack addObject:[file stringByAppendingString:@"/"]];
4733 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4734 ([stack count] - 2) * 3, "",
4735 [file substringFromIndex:[directory length]]
4744 - (void) resetViewAnimated:(BOOL)animated {
4745 [list_ resetViewAnimated:animated];
4748 - (void) reloadData {
4749 [self setPackage:[database_ packageWithName:name_]];
4750 [self reloadButtons];
4753 - (NSString *) title {
4754 return CYLocalize("INSTALLED_FILES");
4757 - (NSString *) backButtonTitle {
4758 return CYLocalize("FILES");
4763 /* Package View {{{ */
4764 @interface PackageView : BrowserView {
4765 _transient Database *database_;
4769 NSMutableArray *buttons_;
4772 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4773 - (void) setPackage:(Package *)package;
4777 @implementation PackageView
4780 if (package_ != nil)
4789 if ([self retainCount] == 1)
4790 [delegate_ setPackageView:self];
4794 /* XXX: this is not safe at all... localization of /fail/ */
4795 - (void) _clickButtonWithName:(NSString *)name {
4796 if ([name isEqualToString:CYLocalize("CLEAR")])
4797 [delegate_ clearPackage:package_];
4798 else if ([name isEqualToString:CYLocalize("INSTALL")])
4799 [delegate_ installPackage:package_];
4800 else if ([name isEqualToString:CYLocalize("REINSTALL")])
4801 [delegate_ installPackage:package_];
4802 else if ([name isEqualToString:CYLocalize("REMOVE")])
4803 [delegate_ removePackage:package_];
4804 else if ([name isEqualToString:CYLocalize("UPGRADE")])
4805 [delegate_ installPackage:package_];
4806 else _assert(false);
4809 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4810 NSString *context([sheet context]);
4812 if ([context isEqualToString:@"modify"]) {
4813 int count = [buttons_ count];
4814 _assert(count != 0);
4815 _assert(button <= count + 1);
4817 if (count != button - 1)
4818 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
4822 [super alertSheet:sheet buttonClicked:button];
4825 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
4826 return [super webView:sender didFinishLoadForFrame:frame];
4829 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4830 [super webView:sender didClearWindowObject:window forFrame:frame];
4831 [window setValue:package_ forKey:@"package"];
4834 - (bool) _allowJavaScriptPanel {
4839 - (void) __rightButtonClicked {
4840 int count = [buttons_ count];
4841 _assert(count != 0);
4844 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
4846 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
4847 [buttons addObjectsFromArray:buttons_];
4848 [buttons addObject:CYLocalize("CANCEL")];
4850 [delegate_ slideUp:[[[UIActionSheet alloc]
4853 defaultButtonIndex:([buttons count] - 1)
4860 - (void) _rightButtonClicked {
4862 [super _rightButtonClicked];
4864 [self __rightButtonClicked];
4868 - (id) _rightButtonTitle {
4869 int count = [buttons_ count];
4870 return count == 0 ? nil : count != 1 ? CYLocalize("MODIFY") : [buttons_ objectAtIndex:0];
4873 - (NSString *) backButtonTitle {
4877 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4878 if ((self = [super initWithBook:book]) != nil) {
4879 database_ = database;
4880 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
4881 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
4885 - (void) setPackage:(Package *)package {
4886 if (package_ != nil) {
4887 [package_ autorelease];
4896 [buttons_ removeAllObjects];
4898 if (package != nil) {
4901 package_ = [package retain];
4902 name_ = [[package id] retain];
4903 commercial_ = [package isCommercial];
4905 if ([package_ mode] != nil)
4906 [buttons_ addObject:CYLocalize("CLEAR")];
4907 if ([package_ source] == nil);
4908 else if ([package_ upgradableAndEssential:NO])
4909 [buttons_ addObject:CYLocalize("UPGRADE")];
4910 else if ([package_ installed] == nil)
4911 [buttons_ addObject:CYLocalize("INSTALL")];
4913 [buttons_ addObject:CYLocalize("REINSTALL")];
4914 if ([package_ installed] != nil)
4915 [buttons_ addObject:CYLocalize("REMOVE")];
4917 if (special_ != NULL) {
4918 CGRect frame([webview_ frame]);
4919 frame.size.width = 320;
4920 frame.size.height = 0;
4921 [webview_ setFrame:frame];
4923 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
4926 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
4928 [self setButtonTitle:nil withStyle:nil toFunction:nil];
4930 [self setFinishHook:nil];
4931 [self setPopupHook:nil];
4934 //[self yieldToSelector:@selector(callFunction:) withObject:special_];
4935 [super callFunction:special_];
4939 [self reloadButtons];
4942 - (bool) isLoading {
4943 return commercial_ ? [super isLoading] : false;
4946 - (void) reloadData {
4947 [self setPackage:[database_ packageWithName:name_]];
4952 /* Package Table {{{ */
4953 @interface PackageTable : RVPage {
4954 _transient Database *database_;
4956 NSMutableArray *packages_;
4957 NSMutableArray *sections_;
4958 UISectionList *list_;
4961 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
4963 - (void) setDelegate:(id)delegate;
4965 - (void) reloadData;
4966 - (void) resetCursor;
4968 - (UISectionList *) list;
4970 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
4974 @implementation PackageTable
4977 [list_ setDataSource:nil];
4980 [packages_ release];
4981 [sections_ release];
4986 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
4987 return [sections_ count];
4990 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
4991 return [[sections_ objectAtIndex:section] name];
4994 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
4995 return [[sections_ objectAtIndex:section] row];
4998 - (int) numberOfRowsInTable:(UITable *)table {
4999 return [packages_ count];
5002 - (float) table:(UITable *)table heightForRow:(int)row {
5003 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
5006 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
5008 reusing = [[[PackageCell alloc] init] autorelease];
5009 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
5013 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5017 - (void) tableRowSelected:(NSNotification *)notification {
5018 int row = [[notification object] selectedRow];
5022 Package *package = [packages_ objectAtIndex:row];
5023 package = [database_ packageWithName:[package id]];
5024 PackageView *view([delegate_ packageView]);
5025 [view setPackage:package];
5026 [view setDelegate:delegate_];
5027 [book_ pushPage:view];
5030 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
5031 if ((self = [super initWithBook:book]) != nil) {
5032 database_ = database;
5033 title_ = [title retain];
5035 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5036 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5038 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
5039 [list_ setDataSource:self];
5041 UITableColumn *column = [[[UITableColumn alloc]
5042 initWithTitle:CYLocalize("NAME")
5044 width:[self frame].size.width
5047 UITable *table = [list_ table];
5048 [table setSeparatorStyle:1];
5049 [table addTableColumn:column];
5050 [table setDelegate:self];
5051 [table setReusesTableCells:YES];
5053 [self addSubview:list_];
5055 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5056 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5060 - (void) setDelegate:(id)delegate {
5061 delegate_ = delegate;
5064 - (bool) hasPackage:(Package *)package {
5068 - (void) reloadData {
5069 NSArray *packages = [database_ packages];
5071 [packages_ removeAllObjects];
5072 [sections_ removeAllObjects];
5074 _profile(PackageTable$reloadData$Filter)
5075 for (Package *package in packages)
5076 if ([self hasPackage:package])
5077 [packages_ addObject:package];
5080 Section *section = nil;
5082 _profile(PackageTable$reloadData$Section)
5083 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5087 _profile(PackageTable$reloadData$Section$Package)
5088 package = [packages_ objectAtIndex:offset];
5089 index = [package index];
5092 if (section == nil || [section index] != index) {
5093 _profile(PackageTable$reloadData$Section$Allocate)
5094 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5097 _profile(PackageTable$reloadData$Section$Add)
5098 [sections_ addObject:section];
5102 [section addToCount];
5106 _profile(PackageTable$reloadData$List)
5111 - (NSString *) title {
5115 - (void) resetViewAnimated:(BOOL)animated {
5116 [list_ resetViewAnimated:animated];
5119 - (void) resetCursor {
5120 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
5123 - (UISectionList *) list {
5127 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5128 [list_ setShouldHideHeaderInShortLists:hide];
5133 /* Filtered Package Table {{{ */
5134 @interface FilteredPackageTable : PackageTable {
5140 - (void) setObject:(id)object;
5142 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5146 @implementation FilteredPackageTable
5154 - (void) setObject:(id)object {
5160 object_ = [object retain];
5163 - (bool) hasPackage:(Package *)package {
5164 _profile(FilteredPackageTable$hasPackage)
5165 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5169 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5170 if ((self = [super initWithBook:book database:database title:title]) != nil) {
5172 object_ = object == nil ? nil : [object retain];
5174 /* XXX: this is an unsafe optimization of doomy hell */
5175 Method method = class_getInstanceMethod([Package class], filter);
5176 _assert(method != NULL);
5177 imp_ = method_getImplementation(method);
5178 _assert(imp_ != NULL);
5187 /* Add Source View {{{ */
5188 @interface AddSourceView : RVPage {
5189 _transient Database *database_;
5192 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5196 @implementation AddSourceView
5198 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5199 if ((self = [super initWithBook:book]) != nil) {
5200 database_ = database;
5206 /* Source Cell {{{ */
5207 @interface SourceCell : UITableCell {
5210 NSString *description_;
5216 - (SourceCell *) initWithSource:(Source *)source;
5220 @implementation SourceCell
5225 [description_ release];
5230 - (SourceCell *) initWithSource:(Source *)source {
5231 if ((self = [super init]) != nil) {
5233 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5235 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5236 icon_ = [icon_ retain];
5238 origin_ = [[source name] retain];
5239 label_ = [[source uri] retain];
5240 description_ = [[source description] retain];
5244 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
5246 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5253 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
5257 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
5261 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
5263 [super drawContentInRect:rect selected:selected];
5268 /* Source Table {{{ */
5269 @interface SourceTable : RVPage {
5270 _transient Database *database_;
5271 UISectionList *list_;
5272 NSMutableArray *sources_;
5273 UIActionSheet *alert_;
5277 UIProgressHUD *hud_;
5280 //NSURLConnection *installer_;
5281 NSURLConnection *trivial_bz2_;
5282 NSURLConnection *trivial_gz_;
5283 //NSURLConnection *automatic_;
5288 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5292 @implementation SourceTable
5294 - (void) _deallocConnection:(NSURLConnection *)connection {
5295 if (connection != nil) {
5296 [connection cancel];
5297 //[connection setDelegate:nil];
5298 [connection release];
5303 [[list_ table] setDelegate:nil];
5304 [list_ setDataSource:nil];
5313 //[self _deallocConnection:installer_];
5314 [self _deallocConnection:trivial_gz_];
5315 [self _deallocConnection:trivial_bz2_];
5316 //[self _deallocConnection:automatic_];
5323 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5324 return offset_ == 0 ? 1 : 2;
5327 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5328 switch (section + (offset_ == 0 ? 1 : 0)) {
5329 case 0: return CYLocalize("ENTERED_BY_USER");
5330 case 1: return CYLocalize("INSTALLED_BY_PACKAGE");
5338 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5339 switch (section + (offset_ == 0 ? 1 : 0)) {
5341 case 1: return offset_;
5349 - (int) numberOfRowsInTable:(UITable *)table {
5350 return [sources_ count];
5353 - (float) table:(UITable *)table heightForRow:(int)row {
5354 Source *source = [sources_ objectAtIndex:row];
5355 return [source description] == nil ? 56 : 73;
5358 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5359 Source *source = [sources_ objectAtIndex:row];
5360 // XXX: weird warning, stupid selectors ;P
5361 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5364 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5368 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5372 - (void) tableRowSelected:(NSNotification*)notification {
5373 UITable *table([list_ table]);
5374 int row([table selectedRow]);
5378 Source *source = [sources_ objectAtIndex:row];
5380 PackageTable *packages = [[[FilteredPackageTable alloc]
5383 title:[source label]
5384 filter:@selector(isVisibleInSource:)
5388 [packages setDelegate:delegate_];
5390 [book_ pushPage:packages];
5393 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5394 Source *source = [sources_ objectAtIndex:row];
5395 return [source record] != nil;
5398 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5399 [[list_ table] setDeleteConfirmationRow:row];
5402 - (void) table:(UITable *)table deleteRow:(int)row {
5403 Source *source = [sources_ objectAtIndex:row];
5404 [Sources_ removeObjectForKey:[source key]];
5405 [delegate_ syncData];
5409 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5412 @"./", @"Distribution",
5413 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5415 [delegate_ syncData];
5418 - (NSString *) getWarning {
5419 NSString *href(href_);
5420 NSRange colon([href rangeOfString:@"://"]);
5421 if (colon.location != NSNotFound)
5422 href = [href substringFromIndex:(colon.location + 3)];
5423 href = [href stringByAddingPercentEscapes];
5424 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5425 href = [href stringByCachingURLWithCurrentCDN];
5427 NSURL *url([NSURL URLWithString:href]);
5429 NSStringEncoding encoding;
5430 NSError *error(nil);
5432 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5433 return [warning length] == 0 ? nil : warning;
5437 - (void) _endConnection:(NSURLConnection *)connection {
5438 NSURLConnection **field = NULL;
5439 if (connection == trivial_bz2_)
5440 field = &trivial_bz2_;
5441 else if (connection == trivial_gz_)
5442 field = &trivial_gz_;
5443 _assert(field != NULL);
5444 [connection release];
5448 trivial_bz2_ == nil &&
5454 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5457 UIActionSheet *sheet = [[[UIActionSheet alloc]
5458 initWithTitle:CYLocalize("SOURCE_WARNING")
5459 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_ANYWAY"), CYLocalize("CANCEL"), nil]
5460 defaultButtonIndex:0
5465 [sheet setNumberOfRows:1];
5467 [sheet setBodyText:warning];
5468 [sheet popupAlertAnimated:YES];
5471 } else if (error_ != nil) {
5472 UIActionSheet *sheet = [[[UIActionSheet alloc]
5473 initWithTitle:CYLocalize("VERIFICATION_ERROR")
5474 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5475 defaultButtonIndex:0
5480 [sheet setBodyText:[error_ localizedDescription]];
5481 [sheet popupAlertAnimated:YES];
5483 UIActionSheet *sheet = [[[UIActionSheet alloc]
5484 initWithTitle:CYLocalize("NOT_REPOSITORY")
5485 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5486 defaultButtonIndex:0
5491 [sheet setBodyText:CYLocalize("NOT_REPOSITORY_EX")];
5492 [sheet popupAlertAnimated:YES];
5495 [delegate_ setStatusBarShowsProgress:NO];
5496 [delegate_ removeProgressHUD:hud_];
5506 if (error_ != nil) {
5513 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5514 switch ([response statusCode]) {
5520 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5521 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5523 error_ = [error retain];
5524 [self _endConnection:connection];
5527 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5528 [self _endConnection:connection];
5531 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5532 NSMutableURLRequest *request = [NSMutableURLRequest
5533 requestWithURL:[NSURL URLWithString:href]
5534 cachePolicy:NSURLRequestUseProtocolCachePolicy
5535 timeoutInterval:20.0
5538 [request setHTTPMethod:method];
5540 if (Machine_ != NULL)
5541 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5542 if (UniqueID_ != nil)
5543 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5546 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5548 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5551 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5552 NSString *context([sheet context]);
5554 if ([context isEqualToString:@"source"]) {
5557 NSString *href = [[sheet textField] text];
5559 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5561 if (![href hasSuffix:@"/"])
5562 href_ = [href stringByAppendingString:@"/"];
5565 href_ = [href_ retain];
5567 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5568 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5569 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5573 hud_ = [[delegate_ addProgressHUD] retain];
5574 [hud_ setText:CYLocalize("VERIFYING_URL")];
5585 } else if ([context isEqualToString:@"trivial"])
5587 else if ([context isEqualToString:@"urlerror"])
5589 else if ([context isEqualToString:@"warning"]) {
5609 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5610 if ((self = [super initWithBook:book]) != nil) {
5611 database_ = database;
5612 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5614 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5615 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5616 [list_ setShouldHideHeaderInShortLists:NO];
5618 [self addSubview:list_];
5619 [list_ setDataSource:self];
5621 UITableColumn *column = [[UITableColumn alloc]
5622 initWithTitle:CYLocalize("NAME")
5624 width:[self frame].size.width
5627 UITable *table = [list_ table];
5628 [table setSeparatorStyle:1];
5629 [table addTableColumn:column];
5630 [table setDelegate:self];
5634 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5635 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5639 - (void) reloadData {
5641 _assert(list.ReadMainList());
5643 [sources_ removeAllObjects];
5644 [sources_ addObjectsFromArray:[database_ sources]];
5646 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5649 int count = [sources_ count];
5650 for (offset_ = 0; offset_ != count; ++offset_) {
5651 Source *source = [sources_ objectAtIndex:offset_];
5652 if ([source record] == nil)
5659 - (void) resetViewAnimated:(BOOL)animated {
5660 [list_ resetViewAnimated:animated];
5663 - (void) _leftButtonClicked {
5664 /*[book_ pushPage:[[[AddSourceView alloc]
5669 UIActionSheet *sheet = [[[UIActionSheet alloc]
5670 initWithTitle:CYLocalize("ENTER_APT_URL")
5671 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_SOURCE"), CYLocalize("CANCEL"), nil]
5672 defaultButtonIndex:0
5677 [sheet setNumberOfRows:1];
5679 [sheet addTextFieldWithValue:@"http://" label:@""];
5681 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5682 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5683 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5684 [traits setKeyboardType:UIKeyboardTypeURL];
5685 // XXX: UIReturnKeyDone
5686 [traits setReturnKeyType:UIReturnKeyNext];
5688 [sheet popupAlertAnimated:YES];
5691 - (void) _rightButtonClicked {
5692 UITable *table = [list_ table];
5693 BOOL editing = [table isRowDeletionEnabled];
5694 [table enableRowDeletion:!editing animated:YES];
5695 [book_ reloadButtonsForPage:self];
5698 - (NSString *) title {
5699 return CYLocalize("SOURCES");
5702 - (NSString *) leftButtonTitle {
5703 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("ADD") : nil;
5706 - (id) rightButtonTitle {
5707 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("DONE") : CYLocalize("EDIT");
5710 - (UINavigationButtonStyle) rightButtonStyle {
5711 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5717 /* Installed View {{{ */
5718 @interface InstalledView : RVPage {
5719 _transient Database *database_;
5720 FilteredPackageTable *packages_;
5724 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5728 @implementation InstalledView
5731 [packages_ release];
5735 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5736 if ((self = [super initWithBook:book]) != nil) {
5737 database_ = database;
5739 packages_ = [[FilteredPackageTable alloc]
5743 filter:@selector(isInstalledAndVisible:)
5744 with:[NSNumber numberWithBool:YES]
5747 [self addSubview:packages_];
5749 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5750 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5754 - (void) resetViewAnimated:(BOOL)animated {
5755 [packages_ resetViewAnimated:animated];
5758 - (void) reloadData {
5759 [packages_ reloadData];
5762 - (void) _rightButtonClicked {
5763 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5764 [packages_ reloadData];
5766 [book_ reloadButtonsForPage:self];
5769 - (NSString *) title {
5770 return CYLocalize("INSTALLED");
5773 - (NSString *) backButtonTitle {
5774 return CYLocalize("PACKAGES");
5777 - (id) rightButtonTitle {
5778 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? CYLocalize("EXPERT") : CYLocalize("SIMPLE");
5781 - (UINavigationButtonStyle) rightButtonStyle {
5782 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5785 - (void) setDelegate:(id)delegate {
5786 [super setDelegate:delegate];
5787 [packages_ setDelegate:delegate];
5794 @interface HomeView : BrowserView {
5799 @implementation HomeView
5801 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5802 NSString *context([sheet context]);
5804 if ([context isEqualToString:@"about"])
5807 [super alertSheet:sheet buttonClicked:button];
5810 - (void) _leftButtonClicked {
5811 UIActionSheet *sheet = [[[UIActionSheet alloc]
5812 initWithTitle:CYLocalize("ABOUT_CYDIA")
5813 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
5814 defaultButtonIndex:0
5820 @"Copyright (C) 2008-2009\n"
5821 "Jay Freeman (saurik)\n"
5822 "saurik@saurik.com\n"
5823 "http://www.saurik.com/\n"
5826 "http://www.theokorigroup.com/\n"
5828 "College of Creative Studies,\n"
5829 "University of California,\n"
5831 "http://www.ccs.ucsb.edu/"
5834 [sheet popupAlertAnimated:YES];
5837 - (NSString *) leftButtonTitle {
5838 return CYLocalize("ABOUT");
5843 /* Manage View {{{ */
5844 @interface ManageView : BrowserView {
5849 @implementation ManageView
5851 - (NSString *) title {
5852 return CYLocalize("MANAGE");
5855 - (void) _leftButtonClicked {
5856 [delegate_ askForSettings];
5859 - (NSString *) leftButtonTitle {
5860 return CYLocalize("SETTINGS");
5864 - (id) _rightButtonTitle {
5865 return Queuing_ ? CYLocalize("QUEUE") : nil;
5868 - (UINavigationButtonStyle) rightButtonStyle {
5869 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5872 - (void) _rightButtonClicked {
5877 - (bool) isLoading {
5884 #include <BrowserView.m>
5886 /* Cydia Book {{{ */
5887 @interface CYBook : RVBook <
5890 _transient Database *database_;
5891 UINavigationBar *overlay_;
5892 UINavigationBar *underlay_;
5893 UIProgressIndicator *indicator_;
5894 UITextLabel *prompt_;
5895 UIProgressBar *progress_;
5896 UINavigationButton *cancel_;
5900 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
5906 @implementation CYBook
5910 [indicator_ release];
5912 [progress_ release];
5917 - (NSString *) getTitleForPage:(RVPage *)page {
5918 return [super getTitleForPage:page];
5926 [UIView beginAnimations:nil context:NULL];
5928 CGRect ovrframe = [overlay_ frame];
5929 ovrframe.origin.y = 0;
5930 [overlay_ setFrame:ovrframe];
5932 CGRect barframe = [navbar_ frame];
5933 barframe.origin.y += ovrframe.size.height;
5934 [navbar_ setFrame:barframe];
5936 CGRect trnframe = [transition_ frame];
5937 trnframe.origin.y += ovrframe.size.height;
5938 trnframe.size.height -= ovrframe.size.height;
5939 [transition_ setFrame:trnframe];
5941 [UIView endAnimations];
5943 [indicator_ startAnimation];
5944 [prompt_ setText:CYLocalize("UPDATING_DATABASE")];
5945 [progress_ setProgress:0];
5948 [overlay_ addSubview:cancel_];
5951 detachNewThreadSelector:@selector(_update)
5957 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5958 NSString *context([sheet context]);
5960 if ([context isEqualToString:@"refresh"])
5964 - (void) _update_:(NSString *)error {
5967 [indicator_ stopAnimation];
5969 [UIView beginAnimations:nil context:NULL];
5971 CGRect ovrframe = [overlay_ frame];
5972 ovrframe.origin.y = -ovrframe.size.height;
5973 [overlay_ setFrame:ovrframe];
5975 CGRect barframe = [navbar_ frame];
5976 barframe.origin.y -= ovrframe.size.height;
5977 [navbar_ setFrame:barframe];
5979 CGRect trnframe = [transition_ frame];
5980 trnframe.origin.y -= ovrframe.size.height;
5981 trnframe.size.height += ovrframe.size.height;
5982 [transition_ setFrame:trnframe];
5984 [UIView commitAnimations];
5987 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
5989 UIActionSheet *sheet = [[[UIActionSheet alloc]
5990 initWithTitle:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), CYLocalize("REFRESH")]
5991 buttons:[NSArray arrayWithObjects:
5994 defaultButtonIndex:0
5999 [sheet setBodyText:error];
6000 [sheet popupAlertAnimated:YES];
6002 [self reloadButtons];
6006 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
6007 if ((self = [super initWithFrame:frame]) != nil) {
6008 database_ = database;
6010 CGRect ovrrect = [navbar_ bounds];
6011 ovrrect.size.height = [UINavigationBar defaultSize].height;
6012 ovrrect.origin.y = -ovrrect.size.height;
6014 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6015 [self addSubview:overlay_];
6017 ovrrect.origin.y = frame.size.height;
6018 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
6019 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6020 [self addSubview:underlay_];
6022 [overlay_ setBarStyle:1];
6023 [underlay_ setBarStyle:1];
6025 int barstyle = [overlay_ _barStyle:NO];
6026 bool ugly = barstyle == 0;
6028 UIProgressIndicatorStyle style = ugly ?
6029 UIProgressIndicatorStyleMediumBrown :
6030 UIProgressIndicatorStyleMediumWhite;
6032 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
6033 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
6034 CGRect indrect = {{indoffset, indoffset}, indsize};
6036 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
6037 [indicator_ setStyle:style];
6038 [overlay_ addSubview:indicator_];
6040 CGSize prmsize = {215, indsize.height + 4};
6043 indoffset * 2 + indsize.width,
6047 unsigned(ovrrect.size.height - prmsize.height) / 2
6050 UIFont *font = [UIFont systemFontOfSize:15];
6052 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
6054 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6055 [prompt_ setBackgroundColor:[UIColor clearColor]];
6056 [prompt_ setFont:font];
6058 [overlay_ addSubview:prompt_];
6060 CGSize prgsize = {75, 100};
6063 ovrrect.size.width - prgsize.width - 10,
6064 (ovrrect.size.height - prgsize.height) / 2
6067 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
6068 [progress_ setStyle:0];
6069 [overlay_ addSubview:progress_];
6071 cancel_ = [[UINavigationButton alloc] initWithTitle:CYLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6072 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
6074 CGRect frame = [cancel_ frame];
6075 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
6076 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
6077 [cancel_ setFrame:frame];
6079 [cancel_ setBarStyle:barstyle];
6083 - (void) _onCancel {
6085 [cancel_ removeFromSuperview];
6088 - (void) _update { _pooled
6090 status.setDelegate(self);
6092 NSString *error([database_ updateWithStatus:status]);
6095 performSelectorOnMainThread:@selector(_update_:)
6101 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
6102 [prompt_ setText:[NSString stringWithFormat:CYLocalize("COLON_DELIMITED"), CYLocalize("ERROR"), error]];
6105 - (void) setProgressTitle:(NSString *)title {
6107 performSelectorOnMainThread:@selector(_setProgressTitle:)
6113 - (void) setProgressPercent:(float)percent {
6115 performSelectorOnMainThread:@selector(_setProgressPercent:)
6116 withObject:[NSNumber numberWithFloat:percent]
6121 - (void) startProgress {
6124 - (void) addProgressOutput:(NSString *)output {
6126 performSelectorOnMainThread:@selector(_addProgressOutput:)
6132 - (bool) isCancelling:(size_t)received {
6136 - (void) _setProgressTitle:(NSString *)title {
6137 [prompt_ setText:title];
6140 - (void) _setProgressPercent:(NSNumber *)percent {
6141 [progress_ setProgress:[percent floatValue]];
6144 - (void) _addProgressOutput:(NSString *)output {
6149 /* Cydia:// Protocol {{{ */
6150 @interface CydiaURLProtocol : NSURLProtocol {
6155 @implementation CydiaURLProtocol
6157 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6158 NSURL *url([request URL]);
6161 NSString *scheme([[url scheme] lowercaseString]);
6162 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6167 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6171 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6172 id<NSURLProtocolClient> client([self client]);
6174 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6176 NSData *data(UIImagePNGRepresentation(icon));
6178 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6179 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6180 [client URLProtocol:self didLoadData:data];
6181 [client URLProtocolDidFinishLoading:self];
6185 - (void) startLoading {
6186 id<NSURLProtocolClient> client([self client]);
6187 NSURLRequest *request([self request]);
6189 NSURL *url([request URL]);
6190 NSString *href([url absoluteString]);
6192 NSString *path([href substringFromIndex:8]);
6193 NSRange slash([path rangeOfString:@"/"]);
6196 if (slash.location == NSNotFound) {
6200 command = [path substringToIndex:slash.location];
6201 path = [path substringFromIndex:(slash.location + 1)];
6204 Database *database([Database sharedInstance]);
6206 if ([command isEqualToString:@"package-icon"]) {
6209 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6210 Package *package([database packageWithName:path]);
6213 UIImage *icon([package icon]);
6214 [self _returnPNGWithImage:icon forRequest:request];
6215 } else if ([command isEqualToString:@"source-icon"]) {
6218 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6219 NSString *source(Simplify(path));
6220 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6222 icon = [UIImage applicationImageNamed:@"unknown.png"];
6223 [self _returnPNGWithImage:icon forRequest:request];
6224 } else if ([command isEqualToString:@"uikit-image"]) {
6227 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6228 UIImage *icon(_UIImageWithName(path));
6229 [self _returnPNGWithImage:icon forRequest:request];
6230 } else if ([command isEqualToString:@"section-icon"]) {
6233 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6234 NSString *section(Simplify(path));
6235 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6237 icon = [UIImage applicationImageNamed:@"unknown.png"];
6238 [self _returnPNGWithImage:icon forRequest:request];
6240 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6244 - (void) stopLoading {
6250 /* Sections View {{{ */
6251 @interface SectionsView : RVPage {
6252 _transient Database *database_;
6253 NSMutableArray *sections_;
6254 NSMutableArray *filtered_;
6255 UITransitionView *transition_;
6261 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6262 - (void) reloadData;
6267 @implementation SectionsView
6270 [list_ setDataSource:nil];
6271 [list_ setDelegate:nil];
6273 [sections_ release];
6274 [filtered_ release];
6275 [transition_ release];
6277 [accessory_ release];
6281 - (int) numberOfRowsInTable:(UITable *)table {
6282 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6285 - (float) table:(UITable *)table heightForRow:(int)row {
6289 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6291 reusing = [[[SectionCell alloc] init] autorelease];
6292 [(SectionCell *)reusing setSection:(editing_ ?
6293 [sections_ objectAtIndex:row] :
6294 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
6295 ) editing:editing_];
6299 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6303 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6307 - (void) tableRowSelected:(NSNotification *)notification {
6308 int row = [[notification object] selectedRow];
6319 title = CYLocalize("ALL_PACKAGES");
6321 section = [filtered_ objectAtIndex:(row - 1)];
6322 name = [section name];
6325 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6328 title = CYLocalize("NO_SECTION");
6332 PackageTable *table = [[[FilteredPackageTable alloc]
6336 filter:@selector(isVisiblyUninstalledInSection:)
6340 [table setDelegate:delegate_];
6342 [book_ pushPage:table];
6345 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6346 if ((self = [super initWithBook:book]) != nil) {
6347 database_ = database;
6349 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6350 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6352 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6353 [self addSubview:transition_];
6355 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6356 [transition_ transition:0 toView:list_];
6358 UITableColumn *column = [[[UITableColumn alloc]
6359 initWithTitle:CYLocalize("NAME")
6361 width:[self frame].size.width
6364 [list_ setDataSource:self];
6365 [list_ setSeparatorStyle:1];
6366 [list_ addTableColumn:column];
6367 [list_ setDelegate:self];
6368 [list_ setReusesTableCells:YES];
6372 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6373 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6377 - (void) reloadData {
6378 NSArray *packages = [database_ packages];
6380 [sections_ removeAllObjects];
6381 [filtered_ removeAllObjects];
6384 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6385 SectionMap sections;
6386 sections.resize(64);
6388 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6392 for (Package *package in packages) {
6393 NSString *name([package section]);
6394 NSString *key(name == nil ? @"" : name);
6399 _profile(SectionsView$reloadData$Section)
6400 section = §ions[key];
6401 if (*section == nil) {
6402 _profile(SectionsView$reloadData$Section$Allocate)
6403 *section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6408 [*section addToCount];
6410 _profile(SectionsView$reloadData$Filter)
6411 if (![package valid] || [package installed] != nil || ![package visible])
6415 [*section addToRow];
6419 _profile(SectionsView$reloadData$Section)
6420 section = [sections objectForKey:key];
6421 if (section == nil) {
6422 _profile(SectionsView$reloadData$Section$Allocate)
6423 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6424 [sections setObject:section forKey:key];
6429 [section addToCount];
6431 _profile(SectionsView$reloadData$Filter)
6432 if (![package valid] || [package installed] != nil || ![package visible])
6442 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6443 [sections_ addObject:i->second];
6445 [sections_ addObjectsFromArray:[sections allValues]];
6448 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6450 for (Section *section in sections_) {
6451 size_t count([section row]);
6455 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6456 [section setCount:count];
6457 [filtered_ addObject:section];
6464 - (void) resetView {
6466 [self _rightButtonClicked];
6469 - (void) resetViewAnimated:(BOOL)animated {
6470 [list_ resetViewAnimated:animated];
6473 - (void) _rightButtonClicked {
6474 if ((editing_ = !editing_))
6477 [delegate_ updateData];
6478 [book_ reloadTitleForPage:self];
6479 [book_ reloadButtonsForPage:self];
6482 - (NSString *) title {
6483 return editing_ ? CYLocalize("SECTION_VISIBILITY") : CYLocalize("INSTALL_BY_SECTION");
6486 - (NSString *) backButtonTitle {
6487 return CYLocalize("SECTIONS");
6490 - (id) rightButtonTitle {
6491 return [sections_ count] == 0 ? nil : editing_ ? CYLocalize("DONE") : CYLocalize("EDIT");
6494 - (UINavigationButtonStyle) rightButtonStyle {
6495 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6498 - (UIView *) accessoryView {
6504 /* Changes View {{{ */
6505 @interface ChangesView : RVPage {
6506 _transient Database *database_;
6507 NSMutableArray *packages_;
6508 NSMutableArray *sections_;
6509 UISectionList *list_;
6513 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6514 - (void) reloadData;
6518 @implementation ChangesView
6521 [[list_ table] setDelegate:nil];
6522 [list_ setDataSource:nil];
6524 [packages_ release];
6525 [sections_ release];
6530 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6531 return [sections_ count];
6534 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6535 return [[sections_ objectAtIndex:section] name];
6538 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6539 return [[sections_ objectAtIndex:section] row];
6542 - (int) numberOfRowsInTable:(UITable *)table {
6543 return [packages_ count];
6546 - (float) table:(UITable *)table heightForRow:(int)row {
6547 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6550 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6552 reusing = [[[PackageCell alloc] init] autorelease];
6553 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6557 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6561 - (void) tableRowSelected:(NSNotification *)notification {
6562 int row = [[notification object] selectedRow];
6565 Package *package = [packages_ objectAtIndex:row];
6566 PackageView *view([delegate_ packageView]);
6567 [view setDelegate:delegate_];
6568 [view setPackage:package];
6569 [book_ pushPage:view];
6572 - (void) _leftButtonClicked {
6573 [(CYBook *)book_ update];
6574 [self reloadButtons];
6577 - (void) _rightButtonClicked {
6578 [delegate_ distUpgrade];
6581 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6582 if ((self = [super initWithBook:book]) != nil) {
6583 database_ = database;
6585 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6586 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6588 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6589 [self addSubview:list_];
6591 [list_ setShouldHideHeaderInShortLists:NO];
6592 [list_ setDataSource:self];
6593 //[list_ setSectionListStyle:1];
6595 UITableColumn *column = [[[UITableColumn alloc]
6596 initWithTitle:CYLocalize("NAME")
6598 width:[self frame].size.width
6601 UITable *table = [list_ table];
6602 [table setSeparatorStyle:1];
6603 [table addTableColumn:column];
6604 [table setDelegate:self];
6605 [table setReusesTableCells:YES];
6609 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6610 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6614 - (void) reloadData {
6615 NSArray *packages = [database_ packages];
6617 [packages_ removeAllObjects];
6618 [sections_ removeAllObjects];
6621 for (Package *package in packages)
6623 [package installed] == nil && [package valid] && [package visible] ||
6624 [package upgradableAndEssential:YES]
6626 [packages_ addObject:package];
6629 [packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6632 Section *upgradable = [[[Section alloc] initWithName:CYLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6633 Section *ignored = [[[Section alloc] initWithName:CYLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
6634 Section *section = nil;
6638 bool unseens = false;
6640 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6642 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6643 Package *package = [packages_ objectAtIndex:offset];
6645 BOOL uae = [package upgradableAndEssential:YES];
6651 _profile(ChangesView$reloadData$Remember)
6652 seen = [package seen];
6655 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
6660 name = CYLocalize("UNKNOWN");
6662 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6666 _profile(ChangesView$reloadData$Allocate)
6667 name = [NSString stringWithFormat:CYLocalize("NEW_AT"), name];
6668 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6669 [sections_ addObject:section];
6673 [section addToCount];
6674 } else if ([package ignored])
6675 [ignored addToCount];
6678 [upgradable addToCount];
6683 CFRelease(formatter);
6686 Section *last = [sections_ lastObject];
6687 size_t count = [last count];
6688 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6689 [sections_ removeLastObject];
6692 if ([ignored count] != 0)
6693 [sections_ insertObject:ignored atIndex:0];
6695 [sections_ insertObject:upgradable atIndex:0];
6698 [self reloadButtons];
6701 - (void) resetViewAnimated:(BOOL)animated {
6702 [list_ resetViewAnimated:animated];
6705 - (NSString *) leftButtonTitle {
6706 return [(CYBook *)book_ updating] ? nil : CYLocalize("REFRESH");
6709 - (id) rightButtonTitle {
6710 return upgrades_ == 0 ? nil : [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6713 - (NSString *) title {
6714 return CYLocalize("CHANGES");
6719 /* Search View {{{ */
6720 @protocol SearchViewDelegate
6721 - (void) showKeyboard:(BOOL)show;
6724 @interface SearchView : RVPage {
6726 UISearchField *field_;
6727 UITransitionView *transition_;
6728 FilteredPackageTable *table_;
6729 UIPreferencesTable *advanced_;
6735 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6736 - (void) reloadData;
6740 @implementation SearchView
6743 [field_ setDelegate:nil];
6745 [accessory_ release];
6747 [transition_ release];
6749 [advanced_ release];
6754 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6758 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6760 case 0: return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("ADVANCED_SEARCH"), CYLocalize("COMING_SOON")];
6762 default: _assert(false);
6766 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6770 default: _assert(false);
6774 - (void) _showKeyboard:(BOOL)show {
6775 CGSize keysize = [UIKeyboard defaultSize];
6776 CGRect keydown = [book_ pageBounds];
6777 CGRect keyup = keydown;
6778 keyup.size.height -= keysize.height - ButtonBarHeight_;
6780 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6782 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6783 [animation setSignificantRectFields:8];
6786 [animation setStartFrame:keydown];
6787 [animation setEndFrame:keyup];
6789 [animation setStartFrame:keyup];
6790 [animation setEndFrame:keydown];
6793 UIAnimator *animator = [UIAnimator sharedAnimator];
6796 addAnimations:[NSArray arrayWithObjects:animation, nil]
6797 withDuration:(KeyboardTime_ - delay)
6802 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6804 [delegate_ showKeyboard:show];
6807 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6808 [self _showKeyboard:YES];
6811 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
6812 [self _showKeyboard:NO];
6815 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
6817 NSString *text([field_ text]);
6818 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6824 - (void) textFieldClearButtonPressed:(UITextField *)field {
6828 - (void) keyboardInputShouldDelete:(id)input {
6832 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
6833 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6837 [field_ resignFirstResponder];
6842 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6843 if ((self = [super initWithBook:book]) != nil) {
6844 CGRect pageBounds = [book_ pageBounds];
6846 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6847 [self addSubview:transition_];
6849 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6851 [advanced_ setReusesTableCells:YES];
6852 [advanced_ setDataSource:self];
6853 [advanced_ reloadData];
6855 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6856 CGColor dimmed(space_, 0, 0, 0, 0.5);
6857 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
6859 table_ = [[FilteredPackageTable alloc]
6863 filter:@selector(isUnfilteredAndSearchedForBy:)
6867 [table_ setShouldHideHeaderInShortLists:NO];
6868 [transition_ transition:0 toView:table_];
6877 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
6884 [self bounds].size.width - area.origin.x - 18;
6886 area.size.height = [UISearchField defaultHeight];
6888 field_ = [[UISearchField alloc] initWithFrame:area];
6890 UIFont *font = [UIFont systemFontOfSize:16];
6891 [field_ setFont:font];
6893 [field_ setPlaceholder:CYLocalize("SEARCH_EX")];
6894 [field_ setDelegate:self];
6896 [field_ setPaddingTop:5];
6898 UITextInputTraits *traits([field_ textInputTraits]);
6899 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6900 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6901 [traits setReturnKeyType:UIReturnKeySearch];
6903 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
6905 accessory_ = [[UIView alloc] initWithFrame:accrect];
6906 [accessory_ addSubview:field_];
6908 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
6909 [configure setShowPressFeedback:YES];
6910 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
6911 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
6912 [accessory_ addSubview:configure];*/
6914 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6915 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6921 LKAnimation *animation = [LKTransition animation];
6922 [animation setType:@"oglFlip"];
6923 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
6924 [animation setFillMode:@"extended"];
6925 [animation setTransitionFlags:3];
6926 [animation setDuration:10];
6927 [animation setSpeed:0.35];
6928 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
6929 [[transition_ _layer] addAnimation:animation forKey:0];
6930 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
6931 flipped_ = !flipped_;
6935 - (void) configurePushed {
6936 [field_ resignFirstResponder];
6940 - (void) resetViewAnimated:(BOOL)animated {
6943 [table_ resetViewAnimated:animated];
6946 - (void) _reloadData {
6949 - (void) reloadData {
6952 [table_ setObject:[field_ text]];
6953 _profile(SearchView$reloadData)
6954 [table_ reloadData];
6957 [table_ resetCursor];
6960 - (UIView *) accessoryView {
6964 - (NSString *) title {
6968 - (NSString *) backButtonTitle {
6969 return CYLocalize("SEARCH");
6972 - (void) setDelegate:(id)delegate {
6973 [table_ setDelegate:delegate];
6974 [super setDelegate:delegate];
6980 @interface SettingsView : RVPage {
6981 _transient Database *database_;
6984 UIPreferencesTable *table_;
6985 _UISwitchSlider *subscribedSwitch_;
6986 _UISwitchSlider *ignoredSwitch_;
6987 UIPreferencesControlTableCell *subscribedCell_;
6988 UIPreferencesControlTableCell *ignoredCell_;
6991 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6995 @implementation SettingsView
6998 [table_ setDataSource:nil];
7001 if (package_ != nil)
7004 [subscribedSwitch_ release];
7005 [ignoredSwitch_ release];
7006 [subscribedCell_ release];
7007 [ignoredCell_ release];
7011 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
7012 if (package_ == nil)
7018 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
7019 if (package_ == nil)
7026 default: _assert(false);
7032 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
7033 if (package_ == nil)
7040 default: _assert(false);
7046 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
7047 if (package_ == nil)
7054 default: _assert(false);
7060 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
7061 if (package_ == nil)
7064 _UISwitchSlider *slider([cell control]);
7065 BOOL value([slider value] != 0);
7066 NSMutableDictionary *metadata([package_ metadata]);
7069 if (NSNumber *number = [metadata objectForKey:key])
7070 before = [number boolValue];
7074 if (value != before) {
7075 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7077 [delegate_ updateData];
7081 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
7082 [self onSomething:cell withKey:@"IsSubscribed"];
7085 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
7086 [self onSomething:cell withKey:@"IsIgnored"];
7089 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
7090 if (package_ == nil)
7094 case 0: switch (row) {
7096 return subscribedCell_;
7098 return ignoredCell_;
7099 default: _assert(false);
7102 case 1: switch (row) {
7104 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
7105 [cell setShowSelection:NO];
7106 [cell setTitle:CYLocalize("SHOW_ALL_CHANGES_EX")];
7110 default: _assert(false);
7113 default: _assert(false);
7119 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7120 if ((self = [super initWithBook:book])) {
7121 database_ = database;
7122 name_ = [package retain];
7124 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
7125 [self addSubview:table_];
7127 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7128 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
7130 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
7131 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
7133 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
7134 [subscribedCell_ setShowSelection:NO];
7135 [subscribedCell_ setTitle:CYLocalize("SHOW_ALL_CHANGES")];
7136 [subscribedCell_ setControl:subscribedSwitch_];
7138 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
7139 [ignoredCell_ setShowSelection:NO];
7140 [ignoredCell_ setTitle:CYLocalize("IGNORE_UPGRADES")];
7141 [ignoredCell_ setControl:ignoredSwitch_];
7143 [table_ setDataSource:self];
7148 - (void) resetViewAnimated:(BOOL)animated {
7149 [table_ resetViewAnimated:animated];
7152 - (void) reloadData {
7153 if (package_ != nil)
7154 [package_ autorelease];
7155 package_ = [database_ packageWithName:name_];
7156 if (package_ != nil) {
7158 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
7159 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
7162 [table_ reloadData];
7165 - (NSString *) title {
7166 return CYLocalize("SETTINGS");
7171 /* Signature View {{{ */
7172 @interface SignatureView : BrowserView {
7173 _transient Database *database_;
7177 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
7181 @implementation SignatureView
7188 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7190 [super webView:sender didClearWindowObject:window forFrame:frame];
7193 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
7194 if ((self = [super initWithBook:book]) != nil) {
7195 database_ = database;
7196 package_ = [package retain];
7201 - (void) resetViewAnimated:(BOOL)animated {
7204 - (void) reloadData {
7205 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7211 @interface Cydia : UIApplication <
7212 ConfirmationViewDelegate,
7213 ProgressViewDelegate,
7222 UIToolbar *buttonbar_;
7226 NSMutableArray *essential_;
7227 NSMutableArray *broken_;
7229 Database *database_;
7230 ProgressView *progress_;
7234 UIKeyboard *keyboard_;
7235 UIProgressHUD *hud_;
7237 SectionsView *sections_;
7238 ChangesView *changes_;
7239 ManageView *manage_;
7240 SearchView *search_;
7242 NSMutableArray *details_;
7247 @implementation Cydia
7250 if ([broken_ count] != 0) {
7251 int count = [broken_ count];
7253 UIActionSheet *sheet = [[[UIActionSheet alloc]
7254 initWithTitle:(count == 1 ? CYLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:CYLocalize("HALFINSTALLED_PACKAGES"), count])
7255 buttons:[NSArray arrayWithObjects:
7256 CYLocalize("FORCIBLY_CLEAR"),
7257 CYLocalize("TEMPORARY_IGNORE"),
7259 defaultButtonIndex:0
7264 [sheet setBodyText:CYLocalize("HALFINSTALLED_PACKAGE_EX")];
7265 [sheet popupAlertAnimated:YES];
7266 } else if (!Ignored_ && [essential_ count] != 0) {
7267 int count = [essential_ count];
7269 UIActionSheet *sheet = [[[UIActionSheet alloc]
7270 initWithTitle:(count == 1 ? CYLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:CYLocalize("ESSENTIAL_UPGRADES"), count])
7271 buttons:[NSArray arrayWithObjects:
7272 CYLocalize("UPGRADE_ESSENTIAL"),
7273 CYLocalize("COMPLETE_UPGRADE"),
7274 CYLocalize("TEMPORARY_IGNORE"),
7276 defaultButtonIndex:0
7281 [sheet setBodyText:CYLocalize("ESSENTIAL_UPGRADE_EX")];
7282 [sheet popupAlertAnimated:YES];
7286 - (void) _reloadData {
7289 static bool loaded(false);
7290 UIProgressHUD *hud([self addProgressHUD]);
7291 [hud setText:(loaded ? CYLocalize("RELOADING_DATA") : CYLocalize("LOADING_DATA"))];
7294 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7297 [self removeProgressHUD:hud];
7301 [essential_ removeAllObjects];
7302 [broken_ removeAllObjects];
7304 NSArray *packages = [database_ packages];
7305 for (Package *package in packages) {
7307 [broken_ addObject:package];
7308 if ([package upgradableAndEssential:NO]) {
7309 if ([package essential])
7310 [essential_ addObject:package];
7316 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7317 [buttonbar_ setBadgeValue:badge forButton:3];
7318 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7319 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7320 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7321 [self setApplicationBadge:badge];
7323 [self setApplicationBadgeString:badge];
7325 [buttonbar_ setBadgeValue:nil forButton:3];
7326 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7327 [buttonbar_ setBadgeAnimated:NO forButton:3];
7328 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7329 [self removeApplicationBadge];
7330 else // XXX: maybe use setApplicationBadgeString also?
7331 [self setApplicationIconBadgeNumber:0];
7335 [buttonbar_ setBadgeValue:nil forButton:4];
7339 // XXX: what is this line of code for?
7340 if ([packages count] == 0);
7341 else if (Loaded_ || ManualRefresh) loaded:
7346 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7347 NSTimeInterval interval([update timeIntervalSinceNow]);
7348 if (interval <= 0 && interval > -600)
7356 - (void) _saveConfig {
7359 NSString *error(nil);
7360 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7362 NSError *error(nil);
7363 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7364 NSLog(@"failure to save metadata data: %@", error);
7367 NSLog(@"failure to serialize metadata: %@", error);
7375 - (void) updateData {
7378 /* XXX: this is just stupid */
7379 if (tag_ != 2 && sections_ != nil)
7380 [sections_ reloadData];
7381 if (tag_ != 3 && changes_ != nil)
7382 [changes_ reloadData];
7383 if (tag_ != 5 && search_ != nil)
7384 [search_ reloadData];
7394 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7395 _assert(file != NULL);
7397 NSArray *keys = [Sources_ allKeys];
7399 for (NSString *key in keys) {
7400 NSDictionary *source = [Sources_ objectForKey:key];
7402 fprintf(file, "%s %s %s\n",
7403 [[source objectForKey:@"Type"] UTF8String],
7404 [[source objectForKey:@"URI"] UTF8String],
7405 [[source objectForKey:@"Distribution"] UTF8String]
7414 detachNewThreadSelector:@selector(update_)
7417 title:CYLocalize("UPDATING_SOURCES")
7421 - (void) reloadData {
7422 @synchronized (self) {
7423 if (confirm_ == nil)
7429 pkgProblemResolver *resolver = [database_ resolver];
7431 resolver->InstallProtect();
7432 if (!resolver->Resolve(true))
7436 - (void) popUpBook:(RVBook *)book {
7437 [underlay_ popSubview:book];
7440 - (CGRect) popUpBounds {
7441 return [underlay_ bounds];
7445 [database_ prepare];
7447 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7448 [confirm_ setDelegate:self];
7450 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7451 [page setDelegate:self];
7453 [confirm_ setPage:page];
7454 [self popUpBook:confirm_];
7458 @synchronized (self) {
7463 - (void) clearPackage:(Package *)package {
7464 @synchronized (self) {
7471 - (void) installPackage:(Package *)package {
7472 @synchronized (self) {
7479 - (void) removePackage:(Package *)package {
7480 @synchronized (self) {
7487 - (void) distUpgrade {
7488 @synchronized (self) {
7489 [database_ upgrade];
7495 [self slideUp:[[[UIActionSheet alloc]
7497 buttons:[NSArray arrayWithObjects:CYLocalize("CONTINUE_QUEUING"), CYLocalize("CANCEL_CLEAR"), nil]
7498 defaultButtonIndex:1
7505 @synchronized (self) {
7508 if (confirm_ != nil) {
7516 [overlay_ removeFromSuperview];
7520 detachNewThreadSelector:@selector(perform)
7523 title:CYLocalize("RUNNING")
7527 - (void) bootstrap_ {
7529 [database_ upgrade];
7530 [database_ prepare];
7531 [database_ perform];
7534 /* XXX: replace and localize */
7535 - (void) bootstrap {
7537 detachNewThreadSelector:@selector(bootstrap_)
7540 title:@"Bootstrap Install"
7544 - (void) progressViewIsComplete:(ProgressView *)progress {
7545 if (confirm_ != nil) {
7546 [underlay_ addSubview:overlay_];
7547 [confirm_ popFromSuperviewAnimated:NO];
7553 - (void) setPage:(RVPage *)page {
7554 [page resetViewAnimated:NO];
7555 [page setDelegate:self];
7556 [book_ setPage:page];
7559 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7560 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7561 [browser loadURL:url];
7565 - (void) _setHomePage {
7566 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7569 - (SectionsView *) sectionsView {
7570 if (sections_ == nil)
7571 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7575 - (void) buttonBarItemTapped:(id)sender {
7576 unsigned tag = [sender tag];
7578 [book_ resetViewAnimated:YES];
7580 } else if (tag_ == 2 && tag != 2)
7581 [[self sectionsView] resetView];
7584 case 1: [self _setHomePage]; break;
7586 case 2: [self setPage:[self sectionsView]]; break;
7587 case 3: [self setPage:changes_]; break;
7588 case 4: [self setPage:manage_]; break;
7589 case 5: [self setPage:search_]; break;
7591 default: _assert(false);
7597 - (void) applicationWillSuspend {
7599 [super applicationWillSuspend];
7602 - (void) askForSettings {
7603 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
7605 UIActionSheet *role = [[[UIActionSheet alloc]
7606 initWithTitle:CYLocalize("WHO_ARE_YOU")
7607 buttons:[NSArray arrayWithObjects:
7608 [NSString stringWithFormat:parenthetical, CYLocalize("USER"), CYLocalize("USER_EX")],
7609 [NSString stringWithFormat:parenthetical, CYLocalize("HACKER"), CYLocalize("HACKER_EX")],
7610 [NSString stringWithFormat:parenthetical, CYLocalize("DEVELOPER"), CYLocalize("DEVELOPER_EX")],
7612 defaultButtonIndex:-1
7617 [role setBodyText:CYLocalize("ROLE_EX")];
7618 [role popupAlertAnimated:YES];
7621 - (void) setPackageView:(PackageView *)view {
7623 [view setPackage:nil];
7624 if ([details_ count] < 3)
7625 [details_ addObject:view];
7629 - (PackageView *) _packageView {
7630 return [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7633 - (PackageView *) packageView {
7635 size_t count([details_ count]);
7638 view = [self _packageView];
7640 [details_ addObject:[self _packageView]];
7642 view = [[[details_ lastObject] retain] autorelease];
7643 [details_ removeLastObject];
7653 [self setStatusBarShowsProgress:NO];
7654 [self removeProgressHUD:hud_];
7659 pid_t pid = ExecFork();
7661 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7662 perror("launchctl stop");
7669 [self askForSettings];
7674 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7676 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7677 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7678 0, 0, screenrect.size.width, screenrect.size.height - 48
7679 ) database:database_];
7681 [book_ setDelegate:self];
7683 [overlay_ addSubview:book_];
7685 NSArray *buttonitems = [NSArray arrayWithObjects:
7686 [NSDictionary dictionaryWithObjectsAndKeys:
7687 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7688 @"home-up.png", kUIButtonBarButtonInfo,
7689 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7690 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7691 self, kUIButtonBarButtonTarget,
7692 @"Cydia", kUIButtonBarButtonTitle,
7693 @"0", kUIButtonBarButtonType,
7696 [NSDictionary dictionaryWithObjectsAndKeys:
7697 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7698 @"install-up.png", kUIButtonBarButtonInfo,
7699 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7700 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7701 self, kUIButtonBarButtonTarget,
7702 CYLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7703 @"0", kUIButtonBarButtonType,
7706 [NSDictionary dictionaryWithObjectsAndKeys:
7707 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7708 @"changes-up.png", kUIButtonBarButtonInfo,
7709 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7710 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7711 self, kUIButtonBarButtonTarget,
7712 CYLocalize("CHANGES"), kUIButtonBarButtonTitle,
7713 @"0", kUIButtonBarButtonType,
7716 [NSDictionary dictionaryWithObjectsAndKeys:
7717 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7718 @"manage-up.png", kUIButtonBarButtonInfo,
7719 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7720 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7721 self, kUIButtonBarButtonTarget,
7722 CYLocalize("MANAGE"), kUIButtonBarButtonTitle,
7723 @"0", kUIButtonBarButtonType,
7726 [NSDictionary dictionaryWithObjectsAndKeys:
7727 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7728 @"search-up.png", kUIButtonBarButtonInfo,
7729 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7730 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7731 self, kUIButtonBarButtonTarget,
7732 CYLocalize("SEARCH"), kUIButtonBarButtonTitle,
7733 @"0", kUIButtonBarButtonType,
7737 buttonbar_ = [[UIToolbar alloc]
7739 withFrame:CGRectMake(
7740 0, screenrect.size.height - ButtonBarHeight_,
7741 screenrect.size.width, ButtonBarHeight_
7743 withItemList:buttonitems
7746 [buttonbar_ setDelegate:self];
7747 [buttonbar_ setBarStyle:1];
7748 [buttonbar_ setButtonBarTrackingMode:2];
7750 int buttons[5] = {1, 2, 3, 4, 5};
7751 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7752 [buttonbar_ showButtonGroup:0 withDuration:0];
7754 for (int i = 0; i != 5; ++i)
7755 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7756 i * 64 + 2, 1, 60, ButtonBarHeight_
7759 [buttonbar_ showSelectionForButton:1];
7760 [overlay_ addSubview:buttonbar_];
7762 [UIKeyboard initImplementationNow];
7763 CGSize keysize = [UIKeyboard defaultSize];
7764 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7765 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7766 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
7767 [overlay_ addSubview:keyboard_];
7770 [underlay_ addSubview:overlay_];
7774 [self sectionsView];
7775 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7776 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7778 manage_ = (ManageView *) [[self
7779 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7780 withClass:[ManageView class]
7783 details_ = [[NSMutableArray alloc] initWithCapacity:4];
7784 [details_ addObject:[self _packageView]];
7785 [details_ addObject:[self _packageView]];
7792 [self _setHomePage];
7795 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7796 NSString *context([sheet context]);
7798 if ([context isEqualToString:@"missing"])
7800 else if ([context isEqualToString:@"cancel"]) {
7818 @synchronized (self) {
7823 [buttonbar_ setBadgeValue:CYLocalize("Q_D") forButton:4];
7827 if (confirm_ != nil) {
7832 } else if ([context isEqualToString:@"fixhalf"]) {
7835 @synchronized (self) {
7836 for (Package *broken in broken_) {
7839 NSString *id = [broken id];
7840 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7841 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7842 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7843 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7852 [broken_ removeAllObjects];
7861 } else if ([context isEqualToString:@"role"]) {
7863 case 1: Role_ = @"User"; break;
7864 case 2: Role_ = @"Hacker"; break;
7865 case 3: Role_ = @"Developer"; break;
7872 bool reset = Settings_ != nil;
7874 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7878 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7888 } else if ([context isEqualToString:@"upgrade"]) {
7891 @synchronized (self) {
7892 for (Package *essential in essential_)
7893 [essential install];
7916 - (void) reorganize { _pooled
7917 system("/usr/libexec/cydia/free.sh");
7918 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
7921 - (void) applicationSuspend:(__GSEvent *)event {
7922 if (hud_ == nil && ![progress_ isRunning])
7923 [super applicationSuspend:event];
7926 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7928 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7931 - (void) _setSuspended:(BOOL)value {
7933 [super _setSuspended:value];
7936 - (UIProgressHUD *) addProgressHUD {
7937 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
7938 [window_ setUserInteractionEnabled:NO];
7940 [progress_ addSubview:hud];
7944 - (void) removeProgressHUD:(UIProgressHUD *)hud {
7946 [hud removeFromSuperview];
7947 [window_ setUserInteractionEnabled:YES];
7950 - (void) openMailToURL:(NSURL *)url {
7951 // XXX: this makes me sad
7953 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
7955 [UIApp openURL:url];// asPanel:YES];
7959 - (void) clearFirstResponder {
7960 if (id responder = [window_ firstResponder])
7961 [responder resignFirstResponder];
7964 - (RVPage *) pageForPackage:(NSString *)name {
7965 if (Package *package = [database_ packageWithName:name]) {
7966 PackageView *view([self packageView]);
7967 [view setPackage:package];
7970 UIActionSheet *sheet = [[[UIActionSheet alloc]
7971 initWithTitle:CYLocalize("CANNOT_LOCATE_PACKAGE")
7972 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
7973 defaultButtonIndex:0
7978 [sheet setBodyText:[NSString stringWithFormat:CYLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
7980 [sheet popupAlertAnimated:YES];
7985 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
7989 NSString *scheme([[url scheme] lowercaseString]);
7990 if (![scheme isEqualToString:@"cydia"])
7992 NSString *path([url absoluteString]);
7993 if ([path length] < 8)
7995 path = [path substringFromIndex:8];
7996 if (![path hasPrefix:@"/"])
7997 path = [@"/" stringByAppendingString:path];
7999 if ([path isEqualToString:@"/add-source"])
8000 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
8001 else if ([path isEqualToString:@"/storage"])
8002 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[BrowserView class]];
8003 else if ([path isEqualToString:@"/sources"])
8004 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
8005 else if ([path isEqualToString:@"/packages"])
8006 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
8007 else if ([path hasPrefix:@"/url/"])
8008 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[BrowserView class]];
8009 else if ([path hasPrefix:@"/launch/"])
8010 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8011 else if ([path hasPrefix:@"/package-settings/"])
8012 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
8013 else if ([path hasPrefix:@"/package-signature/"])
8014 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
8015 else if ([path hasPrefix:@"/package/"])
8016 return [self pageForPackage:[path substringFromIndex:9]];
8017 else if ([path hasPrefix:@"/files/"]) {
8018 NSString *name = [path substringFromIndex:7];
8020 if (Package *package = [database_ packageWithName:name]) {
8021 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
8022 [files setPackage:package];
8030 - (void) applicationOpenURL:(NSURL *)url {
8031 [super applicationOpenURL:url];
8033 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
8034 [self setPage:page];
8035 [buttonbar_ showSelectionForButton:tag];
8040 - (void) applicationDidFinishLaunching:(id)unused {
8042 Font12_ = [[UIFont systemFontOfSize:12] retain];
8043 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8044 Font14_ = [[UIFont systemFontOfSize:14] retain];
8045 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8046 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8050 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8051 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8053 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8055 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
8056 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
8058 [window_ orderFront:self];
8059 [window_ makeKey:self];
8060 [window_ setHidden:NO];
8062 database_ = [Database sharedInstance];
8063 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
8064 [database_ setDelegate:progress_];
8065 [window_ setContentView:progress_];
8067 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
8068 [progress_ setContentView:underlay_];
8070 [progress_ resetView];
8073 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8074 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8075 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8076 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8077 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8078 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
8079 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
8081 [self setIdleTimerDisabled:YES];
8083 hud_ = [[self addProgressHUD] retain];
8084 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
8086 [self setStatusBarShowsProgress:YES];
8089 detachNewThreadSelector:@selector(reorganize)
8097 - (void) showKeyboard:(BOOL)show {
8098 CGSize keysize = [UIKeyboard defaultSize];
8099 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
8100 CGRect keyup = keydown;
8101 keyup.origin.y -= keysize.height;
8103 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
8104 [animation setSignificantRectFields:2];
8107 [animation setStartFrame:keydown];
8108 [animation setEndFrame:keyup];
8109 [keyboard_ activate];
8111 [animation setStartFrame:keyup];
8112 [animation setEndFrame:keydown];
8113 [keyboard_ deactivate];
8116 [[UIAnimator sharedAnimator]
8117 addAnimations:[NSArray arrayWithObjects:animation, nil]
8118 withDuration:KeyboardTime_
8123 - (void) slideUp:(UIActionSheet *)alert {
8125 [alert presentSheetFromButtonBar:buttonbar_];
8127 [alert presentSheetInView:overlay_];
8132 void AddPreferences(NSString *plist) { _pooled
8133 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
8134 _assert(settings != NULL);
8135 NSMutableArray *items = [settings objectForKey:@"items"];
8139 for (NSMutableDictionary *item in items) {
8140 NSString *label = [item objectForKey:@"label"];
8141 if (label != nil && [label isEqualToString:@"Cydia"]) {
8148 for (size_t i(0); i != [items count]; ++i) {
8149 NSDictionary *item([items objectAtIndex:i]);
8150 NSString *label = [item objectForKey:@"label"];
8151 if (label != nil && [label isEqualToString:@"General"]) {
8152 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
8153 @"CydiaSettings", @"bundle",
8154 @"PSLinkCell", @"cell",
8155 [NSNumber numberWithBool:YES], @"hasIcon",
8156 [NSNumber numberWithBool:YES], @"isController",
8158 nil] atIndex:(i + 1)];
8164 _assert([settings writeToFile:plist atomically:YES] == YES);
8169 id Alloc_(id self, SEL selector) {
8170 id object = alloc_(self, selector);
8171 lprintf("[%s]A-%p\n", self->isa->name, object);
8176 id Dealloc_(id self, SEL selector) {
8177 id object = dealloc_(self, selector);
8178 lprintf("[%s]D-%p\n", self->isa->name, object);
8182 Class $WebDefaultUIKitDelegate;
8184 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
8186 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
8187 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8188 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8189 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
8192 int main(int argc, char *argv[]) { _pooled
8195 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8197 /* Library Hacks {{{ */
8198 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8200 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8201 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8202 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8203 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8204 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8207 /* Set Locale {{{ */
8208 Locale_ = CFLocaleCopyCurrent();
8209 Languages_ = [NSLocale preferredLanguages];
8210 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8211 //NSLog(@"%@", [Languages_ description]);
8213 if (Languages_ == nil || [Languages_ count] == 0)
8216 lang = [[Languages_ objectAtIndex:0] UTF8String];
8217 setenv("LANG", lang, true);
8218 //std::setlocale(LC_ALL, lang);
8219 NSLog(@"Setting Language: %s", lang);
8222 // XXX: apr_app_initialize?
8225 /* Parse Arguments {{{ */
8226 bool substrate(false);
8232 for (int argi(1); argi != argc; ++argi)
8233 if (strcmp(argv[argi], "--") == 0) {
8235 argv[argi] = argv[0];
8241 for (int argi(1); argi != arge; ++argi)
8242 if (strcmp(args[argi], "--bootstrap") == 0)
8244 else if (strcmp(args[argi], "--substrate") == 0)
8247 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8252 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
8253 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
8254 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
8255 Sounds_Keyboard_ = [keyboard boolValue];
8258 App_ = [[NSBundle mainBundle] bundlePath];
8259 Home_ = NSHomeDirectory();
8264 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8265 alloc_ = alloc->method_imp;
8266 alloc->method_imp = (IMP) &Alloc_;*/
8268 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8269 dealloc_ = dealloc->method_imp;
8270 dealloc->method_imp = (IMP) &Dealloc_;*/
8275 size = sizeof(maxproc);
8276 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8277 perror("sysctlbyname(\"kern.maxproc\", ?)");
8278 else if (maxproc < 64) {
8280 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8281 perror("sysctlbyname(\"kern.maxproc\", #)");
8284 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8285 char *machine = new char[size];
8286 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8287 perror("sysctlbyname(\"hw.machine\", ?)");
8291 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8293 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8294 Build_ = [system objectForKey:@"ProductBuildVersion"];
8295 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
8296 Product_ = [info objectForKey:@"SafariProductVersion"];
8297 Safari_ = [info objectForKey:@"CFBundleVersion"];
8300 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
8301 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
8303 /* Load Database {{{ */
8305 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
8307 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8310 if (Metadata_ == NULL)
8311 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8313 Settings_ = [Metadata_ objectForKey:@"Settings"];
8315 Packages_ = [Metadata_ objectForKey:@"Packages"];
8316 Sections_ = [Metadata_ objectForKey:@"Sections"];
8317 Sources_ = [Metadata_ objectForKey:@"Sources"];
8320 if (Settings_ != nil)
8321 Role_ = [Settings_ objectForKey:@"Role"];
8323 if (Packages_ == nil) {
8324 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8325 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8328 if (Sections_ == nil) {
8329 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8330 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8333 if (Sources_ == nil) {
8334 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8335 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8340 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8343 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8344 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8345 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8346 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8348 if (access("/User", F_OK) != 0) {
8350 system("/usr/libexec/cydia/firmware.sh");
8354 _assert([[NSFileManager defaultManager]
8355 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8356 withIntermediateDirectories:YES
8361 if (access("/tmp/cydia.chk", F_OK) == 0) {
8362 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8363 _assert(errno == ENOENT);
8364 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8365 _assert(errno == ENOENT);
8368 _assert(pkgInitConfig(*_config));
8369 _assert(pkgInitSystem(*_config, _system));
8372 _config->Set("APT::Acquire::Translation", lang);
8373 _config->Set("Acquire::http::Timeout", 15);
8374 _config->Set("Acquire::http::MaxParallel", 4);
8376 /* Color Choices {{{ */
8377 space_ = CGColorSpaceCreateDeviceRGB();
8379 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8380 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8381 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8382 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8383 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8384 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8385 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8386 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8387 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8388 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8389 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8390 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8391 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8392 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8393 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8396 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8397 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8400 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8402 /* UIKit Configuration {{{ */
8403 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8404 if ($GSFontSetUseLegacyFontMetrics != NULL)
8405 $GSFontSetUseLegacyFontMetrics(YES);
8407 UIKeyboardDisableAutomaticAppearance();
8411 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8413 CGColorSpaceRelease(space_);