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>
52 #import <QuartzCore/CALayer.h>
53 #import <UIKit/UIKit.h>
55 #include <WebCore/WebCoreThread.h>
56 #import <WebKit/WebDefaultUIKitDelegate.h>
62 #include <ext/stdio_filebuf.h>
64 #include <apt-pkg/acquire.h>
65 #include <apt-pkg/acquire-item.h>
66 #include <apt-pkg/algorithms.h>
67 #include <apt-pkg/cachefile.h>
68 #include <apt-pkg/clean.h>
69 #include <apt-pkg/configuration.h>
70 #include <apt-pkg/debmetaindex.h>
71 #include <apt-pkg/error.h>
72 #include <apt-pkg/init.h>
73 #include <apt-pkg/mmap.h>
74 #include <apt-pkg/pkgrecords.h>
75 #include <apt-pkg/sha1.h>
76 #include <apt-pkg/sourcelist.h>
77 #include <apt-pkg/sptr.h>
78 #include <apt-pkg/strutl.h>
80 #include <apr-1/apr_pools.h>
82 #include <sys/types.h>
84 #include <sys/sysctl.h>
85 #include <sys/param.h>
86 #include <sys/mount.h>
92 #include <mach-o/nlist.h>
102 #include <ext/hash_map>
104 #import "BrowserView.h"
105 #import "ResetView.h"
107 #import "substrate.h"
110 //#define _finline __attribute__((force_inline))
111 #define _finline inline
116 #define _limit(count) do { \
117 static size_t _count(0); \
118 if (++_count == count) \
123 #define _timestamp ({ \
125 gettimeofday(&tv, NULL); \
126 tv.tv_sec * 1000000 + tv.tv_usec; \
129 typedef std::vector<class ProfileTime *> TimeList;
139 ProfileTime(const char *name) :
143 times_.push_back(this);
146 void AddTime(uint64_t time) {
153 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
165 ProfileTimer(ProfileTime &time) :
172 time_.AddTime(_timestamp - start_);
177 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
179 std::cerr << "========" << std::endl;
182 #define _profile(name) { \
183 static ProfileTime name(#name); \
184 ProfileTimer _ ## name(name);
188 /* Objective-C Handle<> {{{ */
189 template <typename Type_>
191 typedef _H<Type_> This_;
196 _finline void Retain_() {
201 _finline void Clear_() {
207 _finline _H(Type_ *value = NULL, bool mended = false) :
218 _finline This_ &operator =(Type_ *value) {
219 if (value_ != value) {
228 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
230 void NSLogPoint(const char *fix, const CGPoint &point) {
231 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
234 void NSLogRect(const char *fix, const CGRect &rect) {
235 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
238 @interface NSObject (Cydia)
239 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
240 - (id) yieldToSelector:(SEL)selector;
243 @implementation NSObject (Cydia)
248 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
249 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
250 id object([[context objectAtIndex:1] nonretainedObjectValue]);
251 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
253 /* XXX: deal with exceptions */
254 id value([self performSelector:selector withObject:object]);
256 [context removeAllObjects];
258 [context addObject:value];
263 performSelectorOnMainThread:@selector(doNothing)
269 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
270 /*return [self performSelector:selector withObject:object];*/
272 volatile bool stopped(false);
274 NSMutableArray *context([NSMutableArray arrayWithObjects:
275 [NSValue valueWithPointer:selector],
276 [NSValue valueWithNonretainedObject:object],
277 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
280 NSThread *thread([[[NSThread alloc]
282 selector:@selector(_yieldToContext:)
288 NSRunLoop *loop([NSRunLoop currentRunLoop]);
289 NSDate *future([NSDate distantFuture]);
291 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
293 return [context count] == 0 ? nil : [context objectAtIndex:0];
296 - (id) yieldToSelector:(SEL)selector {
297 return [self yieldToSelector:selector withObject:nil];
302 /* NSForcedOrderingSearch doesn't work on the iPhone */
303 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
304 static const NSStringCompareOptions BaseCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch;
305 static const NSStringCompareOptions ForcedCompareOptions_ = BaseCompareOptions_;
306 static const NSStringCompareOptions LaxCompareOptions_ = BaseCompareOptions_ | NSCaseInsensitiveSearch;
308 /* iPhoneOS 2.0 Compatibility {{{ */
310 @interface UITextView (iPhoneOS)
311 - (void) setTextSize:(float)size;
314 @implementation UITextView (iPhoneOS)
316 - (void) setTextSize:(float)size {
317 [self setFont:[[self font] fontWithSize:size]];
324 extern NSString * const kCAFilterNearest;
326 /* Information Dictionaries {{{ */
327 @interface NSMutableArray (Cydia)
328 - (void) addInfoDictionary:(NSDictionary *)info;
331 @implementation NSMutableArray (Cydia)
333 - (void) addInfoDictionary:(NSDictionary *)info {
334 [self addObject:info];
339 @interface NSMutableDictionary (Cydia)
340 - (void) addInfoDictionary:(NSDictionary *)info;
343 @implementation NSMutableDictionary (Cydia)
345 - (void) addInfoDictionary:(NSDictionary *)info {
346 NSString *bundle = [info objectForKey:@"CFBundleIdentifier"];
347 [self setObject:info forKey:bundle];
352 /* Pop Transitions {{{ */
353 @interface PopTransitionView : UITransitionView {
358 @implementation PopTransitionView
360 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
361 if (from != nil && to == nil)
362 [self removeFromSuperview];
367 @implementation UIView (PopUpView)
369 - (void) popFromSuperviewAnimated:(BOOL)animated {
370 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
373 - (void) popSubview:(UIView *)view {
374 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
375 [transition setDelegate:transition];
376 [self addSubview:transition];
378 UIView *blank = [[[UIView alloc] initWithFrame:[transition bounds]] autorelease];
379 [transition transition:UITransitionNone toView:blank];
380 [transition transition:UITransitionPushFromBottom toView:view];
386 #define lprintf(args...) fprintf(stderr, args)
389 #define ForSaurik (0 && !ForRelease)
390 #define LogBrowser (1 && !ForRelease)
391 #define ManualRefresh (1 && !ForRelease)
392 #define ShowInternals (0 && !ForRelease)
393 #define IgnoreInstall (0 && !ForRelease)
394 #define RecycleWebViews 0
395 #define AlwaysReload (1 && !ForRelease)
399 #define _trace(args...)
401 #define _profile(name) {
404 #define PrintTimes() do {} while (false)
408 @interface NSMutableArray (Radix)
409 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
410 - (void) radixSortUsingFunction:(uint32_t (*)(id, void *))function withArgument:(void *)argument;
418 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
419 struct RadixItem_ *lhs(swap), *rhs(swap + count);
421 static const size_t width = 32;
422 static const size_t bits = 11;
423 static const size_t slots = 1 << bits;
424 static const size_t passes = (width + (bits - 1)) / bits;
426 size_t *hist(new size_t[slots]);
428 for (size_t pass(0); pass != passes; ++pass) {
429 memset(hist, 0, sizeof(size_t) * slots);
431 for (size_t i(0); i != count; ++i) {
432 uint32_t key(lhs[i].key);
434 key &= _not(uint32_t) >> width - bits;
439 for (size_t i(0); i != slots; ++i) {
440 size_t local(offset);
445 for (size_t i(0); i != count; ++i) {
446 uint32_t key(lhs[i].key);
448 key &= _not(uint32_t) >> width - bits;
449 rhs[hist[key]++] = lhs[i];
452 RadixItem_ *tmp(lhs);
459 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
460 for (size_t i(0); i != count; ++i)
461 [values addObject:[self objectAtIndex:lhs[i].index]];
462 [self setArray:values];
467 @implementation NSMutableArray (Radix)
469 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
470 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
471 [invocation setSelector:selector];
472 [invocation setArgument:&object atIndex:2];
474 size_t count([self count]);
475 struct RadixItem_ *swap(new RadixItem_[count * 2]);
477 for (size_t i(0); i != count; ++i) {
478 RadixItem_ &item(swap[i]);
481 id object([self objectAtIndex:i]);
482 [invocation setTarget:object];
485 [invocation getReturnValue:&item.key];
488 RadixSort_(self, count, swap);
491 - (void) radixSortUsingFunction:(uint32_t (*)(id, void *))function withArgument:(void *)argument {
492 size_t count([self count]);
493 struct RadixItem_ *swap(new RadixItem_[count * 2]);
495 for (size_t i(0); i != count; ++i) {
496 RadixItem_ &item(swap[i]);
499 id object([self objectAtIndex:i]);
500 item.key = function(object, argument);
503 RadixSort_(self, count, swap);
509 /* Apple Bug Fixes {{{ */
510 @implementation UIWebDocumentView (Cydia)
512 - (void) _setScrollerOffset:(CGPoint)offset {
513 UIScroller *scroller([self _scroller]);
515 CGSize size([scroller contentSize]);
516 CGSize bounds([scroller bounds].size);
519 max.x = size.width - bounds.width;
520 max.y = size.height - bounds.height;
528 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
529 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
531 [scroller setOffset:offset];
538 kUIControlEventMouseDown = 1 << 0,
539 kUIControlEventMouseMovedInside = 1 << 2, // mouse moved inside control target
540 kUIControlEventMouseMovedOutside = 1 << 3, // mouse moved outside control target
541 kUIControlEventMouseUpInside = 1 << 6, // mouse up inside control target
542 kUIControlEventMouseUpOutside = 1 << 7, // mouse up outside control target
543 kUIControlAllEvents = (kUIControlEventMouseDown | kUIControlEventMouseMovedInside | kUIControlEventMouseMovedOutside | kUIControlEventMouseUpInside | kUIControlEventMouseUpOutside)
544 } UIControlEventMasks;
546 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
547 size_t length([self length] - state->state);
550 else if (length > count)
552 for (size_t i(0); i != length; ++i)
553 objects[i] = [self item:state->state++];
554 state->itemsPtr = objects;
555 state->mutationsPtr = (unsigned long *) self;
559 @interface NSString (UIKit)
560 - (NSString *) stringByAddingPercentEscapes;
561 - (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
564 @interface NSString (Cydia)
565 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
566 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
567 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
568 - (NSComparisonResult) compareByPath:(NSString *)other;
569 - (NSString *) stringByCachingURLWithCurrentCDN;
570 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
573 @implementation NSString (Cydia)
575 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
576 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
579 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
580 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
581 memcpy(data, bytes, length);
582 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
585 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
586 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
589 - (NSComparisonResult) compareByPath:(NSString *)other {
590 NSString *prefix = [self commonPrefixWithString:other options:0];
591 size_t length = [prefix length];
593 NSRange lrange = NSMakeRange(length, [self length] - length);
594 NSRange rrange = NSMakeRange(length, [other length] - length);
596 lrange = [self rangeOfString:@"/" options:0 range:lrange];
597 rrange = [other rangeOfString:@"/" options:0 range:rrange];
599 NSComparisonResult value;
601 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
602 value = NSOrderedSame;
603 else if (lrange.location == NSNotFound)
604 value = NSOrderedAscending;
605 else if (rrange.location == NSNotFound)
606 value = NSOrderedDescending;
608 value = NSOrderedSame;
610 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
611 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
612 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
613 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
615 NSComparisonResult result = [lpath compare:rpath];
616 return result == NSOrderedSame ? value : result;
619 - (NSString *) stringByCachingURLWithCurrentCDN {
621 stringByReplacingOccurrencesOfString:@"://"
622 withString:@"://ne.edgecastcdn.net/8003A4/"
624 /* XXX: this is somewhat inaccurate */
625 range:NSMakeRange(0, 10)
629 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
630 return [(id)CFURLCreateStringByAddingPercentEscapes(
635 kCFStringEncodingUTF8
641 static inline NSString *CYLocalizeEx(NSString *key, NSString *value = nil) {
642 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:nil];
645 #define CYLocalize(key) CYLocalizeEx(@ key)
653 _finline void clear_() {
659 _finline bool empty() const {
663 _finline size_t size() const {
667 _finline char *data() const {
671 _finline void clear() {
676 _finline CYString() :
683 _finline ~CYString() {
687 void operator =(const CYString &rhs) {
691 if (rhs.cache_ == nil)
694 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
697 void set(apr_pool_t *pool, const char *data, size_t size) {
703 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size)));
704 memcpy(temp, data, size);
710 _finline void set(apr_pool_t *pool, const char *data) {
711 set(pool, data, data == NULL ? 0 : strlen(data));
714 _finline void set(apr_pool_t *pool, const std::string &rhs) {
715 set(pool, rhs.data(), rhs.size());
718 bool operator ==(const CYString &rhs) const {
719 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
723 if (cache_ == NULL) {
726 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
727 } return (id) cache_;
732 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
735 struct NSStringMapHash :
736 std::unary_function<NSString *, size_t>
738 _finline size_t operator ()(NSString *value) const {
739 return CFStringHashNSString((CFStringRef) value);
743 struct NSStringMapLess :
744 std::binary_function<NSString *, NSString *, bool>
746 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
747 return [lhs compare:rhs] == NSOrderedAscending;
751 struct NSStringMapEqual :
752 std::binary_function<NSString *, NSString *, bool>
754 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
755 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
756 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
757 //[lhs isEqualToString:rhs];
761 /* Perl-Compatible RegEx {{{ */
771 Pcre(const char *regex) :
776 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
779 lprintf("%d:%s\n", offset, error);
783 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
784 matches_ = new int[(capture_ + 1) * 3];
792 NSString *operator [](size_t match) {
793 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
796 bool operator ()(NSString *data) {
797 // XXX: length is for characters, not for bytes
798 return operator ()([data UTF8String], [data length]);
801 bool operator ()(const char *data, size_t size) {
803 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
807 /* Mime Addresses {{{ */
808 @interface Address : NSObject {
814 - (NSString *) address;
816 - (void) setAddress:(NSString *)address;
818 + (Address *) addressWithString:(NSString *)string;
819 - (Address *) initWithString:(NSString *)string;
822 @implementation Address
831 - (NSString *) name {
835 - (NSString *) address {
839 - (void) setAddress:(NSString *)address {
841 [address_ autorelease];
845 address_ = [address retain];
848 + (Address *) addressWithString:(NSString *)string {
849 return [[[Address alloc] initWithString:string] autorelease];
852 + (NSArray *) _attributeKeys {
853 return [NSArray arrayWithObjects:@"address", @"name", nil];
856 - (NSArray *) attributeKeys {
857 return [[self class] _attributeKeys];
860 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
861 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
864 - (Address *) initWithString:(NSString *)string {
865 if ((self = [super init]) != nil) {
866 const char *data = [string UTF8String];
867 size_t size = [string length];
869 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
871 if (address_r(data, size)) {
872 name_ = [address_r[1] retain];
873 address_ = [address_r[2] retain];
875 name_ = [string retain];
883 /* CoreGraphics Primitives {{{ */
894 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
897 Set(space, red, green, blue, alpha);
902 CGColorRelease(color_);
909 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
911 float color[] = {red, green, blue, alpha};
912 color_ = CGColorCreate(space, color);
915 operator CGColorRef() {
921 extern "C" void UISetColor(CGColorRef color);
923 /* Random Global Variables {{{ */
924 static const int PulseInterval_ = 50000;
925 static const int ButtonBarHeight_ = 48;
926 static const float KeyboardTime_ = 0.3f;
928 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
929 #define SandboxTemplate_ "/usr/share/sandbox/SandboxTemplate.sb"
930 #define NotifyConfig_ "/etc/notify.conf"
932 static bool Queuing_;
934 static CGColor Blue_;
935 static CGColor Blueish_;
936 static CGColor Black_;
938 static CGColor White_;
939 static CGColor Gray_;
940 static CGColor Green_;
941 static CGColor Purple_;
942 static CGColor Purplish_;
944 static UIColor *InstallingColor_;
945 static UIColor *RemovingColor_;
947 static NSString *App_;
948 static NSString *Home_;
949 static BOOL Sounds_Keyboard_;
951 static BOOL Advanced_;
953 static BOOL Ignored_;
955 static UIFont *Font12_;
956 static UIFont *Font12Bold_;
957 static UIFont *Font14_;
958 static UIFont *Font18Bold_;
959 static UIFont *Font22Bold_;
961 static const char *Machine_ = NULL;
962 static const NSString *UniqueID_ = nil;
963 static const NSString *Build_ = nil;
964 static const NSString *Product_ = nil;
965 static const NSString *Safari_ = nil;
968 CGColorSpaceRef space_;
973 static NSDictionary *SectionMap_;
974 static NSMutableDictionary *Metadata_;
975 static _transient NSMutableDictionary *Settings_;
976 static _transient NSString *Role_;
977 static _transient NSMutableDictionary *Packages_;
978 static _transient NSMutableDictionary *Sections_;
979 static _transient NSMutableDictionary *Sources_;
980 static bool Changed_;
984 static NSMutableArray *Documents_;
987 NSString *GetLastUpdate() {
988 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
991 return CYLocalize("NEVER_OR_UNKNOWN");
993 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
994 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
996 CFRelease(formatter);
998 return [(NSString *) formatted autorelease];
1001 /* Display Helpers {{{ */
1002 inline float Interpolate(float begin, float end, float fraction) {
1003 return (end - begin) * fraction + begin;
1006 /* XXX: localize this! */
1007 NSString *SizeString(double size) {
1008 bool negative = size < 0;
1013 while (size > 1024) {
1018 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1020 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1023 NSString *StripVersion(NSString *version) {
1024 NSRange colon = [version rangeOfString:@":"];
1025 if (colon.location != NSNotFound)
1026 version = [version substringFromIndex:(colon.location + 1)];
1030 NSString *LocalizeSection(NSString *section) {
1034 NSString *Simplify(NSString *title) {
1035 const char *data = [title UTF8String];
1036 size_t size = [title length];
1038 static Pcre square_r("^\\[(.*)\\]$");
1039 if (square_r(data, size))
1040 return Simplify(square_r[1]);
1042 static Pcre paren_r("^\\((.*)\\)$");
1043 if (paren_r(data, size))
1044 return Simplify(paren_r[1]);
1046 static Pcre title_r("^(.*?) \\(.*\\)$");
1047 if (title_r(data, size))
1048 return Simplify(title_r[1]);
1054 bool isSectionVisible(NSString *section) {
1055 NSDictionary *metadata = [Sections_ objectForKey:section];
1056 NSNumber *hidden = metadata == nil ? nil : [metadata objectForKey:@"Hidden"];
1057 return hidden == nil || ![hidden boolValue];
1060 /* Delegate Prototypes {{{ */
1064 @interface NSObject (ProgressDelegate)
1067 @implementation NSObject(ProgressDelegate)
1069 - (void) _setProgressError:(NSArray *)args {
1070 [self performSelector:@selector(setProgressError:forPackage:)
1071 withObject:[args objectAtIndex:0]
1072 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1078 @protocol ProgressDelegate
1079 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1080 - (void) setProgressTitle:(NSString *)title;
1081 - (void) setProgressPercent:(float)percent;
1082 - (void) startProgress;
1083 - (void) addProgressOutput:(NSString *)output;
1084 - (bool) isCancelling:(size_t)received;
1087 @protocol ConfigurationDelegate
1088 - (void) repairWithSelector:(SEL)selector;
1089 - (void) setConfigurationData:(NSString *)data;
1094 @protocol CydiaDelegate
1095 - (void) setPackageView:(PackageView *)view;
1096 - (void) clearPackage:(Package *)package;
1097 - (void) installPackage:(Package *)package;
1098 - (void) removePackage:(Package *)package;
1099 - (void) slideUp:(UIActionSheet *)alert;
1100 - (void) distUpgrade;
1101 - (void) updateData;
1103 - (void) askForSettings;
1104 - (UIProgressHUD *) addProgressHUD;
1105 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1106 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag;
1107 - (RVPage *) pageForPackage:(NSString *)name;
1108 - (void) openMailToURL:(NSURL *)url;
1109 - (void) clearFirstResponder;
1110 - (PackageView *) packageView;
1114 /* Status Delegation {{{ */
1116 public pkgAcquireStatus
1119 _transient NSObject<ProgressDelegate> *delegate_;
1127 void setDelegate(id delegate) {
1128 delegate_ = delegate;
1131 virtual bool MediaChange(std::string media, std::string drive) {
1135 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1138 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1139 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1140 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
1143 virtual void Done(pkgAcquire::ItemDesc &item) {
1146 virtual void Fail(pkgAcquire::ItemDesc &item) {
1148 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1149 item.Owner->Status == pkgAcquire::Item::StatDone
1153 std::string &error(item.Owner->ErrorText);
1157 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1158 NSArray *fields([description componentsSeparatedByString:@" "]);
1159 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1161 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1162 withObject:[NSArray arrayWithObjects:
1163 [NSString stringWithUTF8String:error.c_str()],
1170 virtual bool Pulse(pkgAcquire *Owner) {
1171 bool value = pkgAcquireStatus::Pulse(Owner);
1174 double(CurrentBytes + CurrentItems) /
1175 double(TotalBytes + TotalItems)
1178 [delegate_ setProgressPercent:percent];
1179 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1182 virtual void Start() {
1183 [delegate_ startProgress];
1186 virtual void Stop() {
1190 /* Progress Delegation {{{ */
1195 _transient id<ProgressDelegate> delegate_;
1198 virtual void Update() {
1199 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1200 [delegate_ setProgressPercent:(Percent / 100)];*/
1209 void setDelegate(id delegate) {
1210 delegate_ = delegate;
1213 virtual void Done() {
1214 //[delegate_ setProgressPercent:1];
1219 /* Database Interface {{{ */
1220 @interface Database : NSObject {
1226 pkgCacheFile cache_;
1227 pkgDepCache::Policy *policy_;
1228 pkgRecords *records_;
1229 pkgProblemResolver *resolver_;
1230 pkgAcquire *fetcher_;
1232 SPtr<pkgPackageManager> manager_;
1233 pkgSourceList *list_;
1235 NSMutableDictionary *sources_;
1236 NSMutableArray *packages_;
1238 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1247 + (Database *) sharedInstance;
1250 - (void) _readCydia:(NSNumber *)fd;
1251 - (void) _readStatus:(NSNumber *)fd;
1252 - (void) _readOutput:(NSNumber *)fd;
1256 - (Package *) packageWithName:(NSString *)name;
1258 - (pkgCacheFile &) cache;
1259 - (pkgDepCache::Policy *) policy;
1260 - (pkgRecords *) records;
1261 - (pkgProblemResolver *) resolver;
1262 - (pkgAcquire &) fetcher;
1263 - (pkgSourceList &) list;
1264 - (NSArray *) packages;
1265 - (NSArray *) sources;
1266 - (void) reloadData;
1274 - (void) updateWithStatus:(Status &)status;
1276 - (void) setDelegate:(id)delegate;
1277 - (Source *) getSource:(const pkgCache::PkgFileIterator &)file;
1281 /* Source Class {{{ */
1282 @interface Source : NSObject {
1283 NSString *description_;
1289 NSString *distribution_;
1293 NSString *defaultIcon_;
1295 NSDictionary *record_;
1299 - (Source *) initWithMetaIndex:(metaIndex *)index;
1301 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1303 - (NSString *) supportForPackage:(NSString *)package;
1305 - (NSDictionary *) record;
1309 - (NSString *) distribution;
1310 - (NSString *) type;
1312 - (NSString *) host;
1314 - (NSString *) name;
1315 - (NSString *) description;
1316 - (NSString *) label;
1317 - (NSString *) origin;
1318 - (NSString *) version;
1320 - (NSString *) defaultIcon;
1324 @implementation Source
1326 #define _clear(field) \
1333 _clear(distribution_)
1336 _clear(description_)
1341 _clear(defaultIcon_)
1350 + (NSArray *) _attributeKeys {
1351 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1354 - (NSArray *) attributeKeys {
1355 return [[self class] _attributeKeys];
1358 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1359 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1362 - (void) setMetaIndex:(metaIndex *)index {
1365 trusted_ = index->IsTrusted();
1367 uri_ = [[NSString stringWithUTF8String:index->GetURI().c_str()] retain];
1368 distribution_ = [[NSString stringWithUTF8String:index->GetDist().c_str()] retain];
1369 type_ = [[NSString stringWithUTF8String:index->GetType()] retain];
1371 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1372 if (dindex != NULL) {
1373 std::ifstream release(dindex->MetaIndexFile("Release").c_str());
1375 while (std::getline(release, line)) {
1376 std::string::size_type colon(line.find(':'));
1377 if (colon == std::string::npos)
1380 std::string name(line.substr(0, colon));
1381 std::string value(line.substr(colon + 1));
1382 while (!value.empty() && value[0] == ' ')
1383 value = value.substr(1);
1385 if (name == "Default-Icon")
1386 defaultIcon_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1387 else if (name == "Description")
1388 description_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1389 else if (name == "Label")
1390 label_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1391 else if (name == "Origin")
1392 origin_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1393 else if (name == "Support")
1394 support_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1395 else if (name == "Version")
1396 version_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1400 record_ = [Sources_ objectForKey:[self key]];
1402 record_ = [record_ retain];
1405 - (Source *) initWithMetaIndex:(metaIndex *)index {
1406 if ((self = [super init]) != nil) {
1407 [self setMetaIndex:index];
1411 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1412 NSDictionary *lhr = [self record];
1413 NSDictionary *rhr = [source record];
1416 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1418 NSString *lhs = [self name];
1419 NSString *rhs = [source name];
1421 if ([lhs length] != 0 && [rhs length] != 0) {
1422 unichar lhc = [lhs characterAtIndex:0];
1423 unichar rhc = [rhs characterAtIndex:0];
1425 if (isalpha(lhc) && !isalpha(rhc))
1426 return NSOrderedAscending;
1427 else if (!isalpha(lhc) && isalpha(rhc))
1428 return NSOrderedDescending;
1431 return [lhs compare:rhs options:LaxCompareOptions_];
1434 - (NSString *) supportForPackage:(NSString *)package {
1435 return support_ == nil ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1438 - (NSDictionary *) record {
1446 - (NSString *) uri {
1450 - (NSString *) distribution {
1451 return distribution_;
1454 - (NSString *) type {
1458 - (NSString *) key {
1459 return [NSString stringWithFormat:@"%@:%@:%@", type_, uri_, distribution_];
1462 - (NSString *) host {
1463 return [[[NSURL URLWithString:[self uri]] host] lowercaseString];
1466 - (NSString *) name {
1467 return origin_ == nil ? [self host] : origin_;
1470 - (NSString *) description {
1471 return description_;
1474 - (NSString *) label {
1475 return label_ == nil ? [self host] : label_;
1478 - (NSString *) origin {
1482 - (NSString *) version {
1486 - (NSString *) defaultIcon {
1487 return defaultIcon_;
1492 /* Relationship Class {{{ */
1493 @interface Relationship : NSObject {
1498 - (NSString *) type;
1500 - (NSString *) name;
1504 @implementation Relationship
1512 - (NSString *) type {
1520 - (NSString *) name {
1527 /* Package Class {{{ */
1528 @interface Package : NSObject {
1531 pkgCache::PkgIterator iterator_;
1532 _transient Database *database_;
1533 pkgCache::VerIterator version_;
1534 pkgCache::VerFileIterator file_;
1540 NSString *section$_;
1544 NSString *installed_;
1550 CYString depiction_;
1563 NSArray *relationships_;
1564 NSMutableDictionary *metadata_;
1567 - (Package *) initWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1568 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1570 - (pkgCache::PkgIterator) iterator;
1572 - (NSString *) section;
1573 - (NSString *) simpleSection;
1575 - (NSString *) longSection;
1576 - (NSString *) shortSection;
1580 - (Address *) maintainer;
1582 - (NSString *) description;
1585 - (NSMutableDictionary *) metadata;
1587 - (BOOL) subscribed;
1590 - (NSString *) latest;
1591 - (NSString *) installed;
1594 - (BOOL) upgradableAndEssential:(BOOL)essential;
1597 - (BOOL) unfiltered;
1601 - (BOOL) halfConfigured;
1602 - (BOOL) halfInstalled;
1604 - (NSString *) mode;
1607 - (NSString *) name;
1608 - (NSString *) tagline;
1610 - (NSString *) homepage;
1611 - (NSString *) depiction;
1612 - (Address *) author;
1614 - (NSString *) support;
1616 - (NSArray *) files;
1617 - (NSArray *) relationships;
1618 - (NSArray *) warnings;
1619 - (NSArray *) applications;
1621 - (Source *) source;
1622 - (NSString *) role;
1624 - (BOOL) matches:(NSString *)text;
1626 - (bool) hasSupportingRole;
1627 - (BOOL) hasTag:(NSString *)tag;
1628 - (NSString *) primaryPurpose;
1629 - (NSArray *) purposes;
1630 - (bool) isCommercial;
1632 - (uint32_t) compareByPrefix;
1633 - (NSComparisonResult) compareByName:(Package *)package;
1634 - (uint32_t) compareBySection:(NSArray *)sections;
1636 - (uint32_t) compareForChanges;
1641 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1642 - (bool) isInstalledAndVisible:(NSNumber *)number;
1643 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1644 - (bool) isVisibleInSource:(Source *)source;
1648 uint32_t PackageChangesRadix(Package *self, void *) {
1653 uint32_t timestamp : 30;
1654 uint32_t ignored : 1;
1655 uint32_t upgradable : 1;
1659 bool upgradable([self upgradableAndEssential:YES]);
1660 value.bits.upgradable = upgradable ? 1 : 0;
1663 value.bits.timestamp = 0;
1664 value.bits.ignored = [self ignored] ? 0 : 1;
1665 value.bits.upgradable = 1;
1667 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1668 value.bits.ignored = 0;
1669 value.bits.upgradable = 0;
1672 return _not(uint32_t) - value.key;
1675 @implementation Package
1680 if (section$_ != nil)
1681 [section$_ release];
1684 if (installed_ != nil)
1685 [installed_ release];
1688 if (sponsor$_ != nil)
1689 [sponsor$_ release];
1690 if (author$_ != nil)
1697 if (relationships_ != nil)
1698 [relationships_ release];
1699 if (metadata_ != nil)
1700 [metadata_ release];
1705 + (NSString *) webScriptNameForSelector:(SEL)selector {
1706 if (selector == @selector(hasTag:))
1712 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1713 return [self webScriptNameForSelector:selector] == nil;
1716 + (NSArray *) _attributeKeys {
1717 return [NSArray arrayWithObjects:@"applications", @"author", @"depiction", @"description", @"essential", @"homepage", @"icon", @"id", @"installed", @"latest", @"longSection", @"maintainer", @"mode", @"name", @"purposes", @"section", @"shortSection", @"simpleSection", @"size", @"source", @"sponsor", @"support", @"tagline", @"warnings", nil];
1720 - (NSArray *) attributeKeys {
1721 return [[self class] _attributeKeys];
1724 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1725 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1728 - (Package *) initWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
1729 if ((self = [super init]) != nil) {
1730 _profile(Package$initWithIterator)
1731 @synchronized (database) {
1732 era_ = [database era];
1734 iterator_ = iterator;
1735 database_ = database;
1737 _profile(Package$initWithIterator$Control)
1740 _profile(Package$initWithIterator$Version)
1741 version_ = [database_ policy]->GetCandidateVer(iterator_);
1744 NSString *latest = version_.end() ? nil : [NSString stringWithUTF8String:version_.VerStr()];
1746 _profile(Package$initWithIterator$Latest)
1747 latest_ = latest == nil ? nil : [StripVersion(latest) retain];
1750 pkgCache::VerIterator current;
1751 NSString *installed;
1753 _profile(Package$initWithIterator$Current)
1754 current = iterator_.CurrentVer();
1755 installed = current.end() ? nil : [NSString stringWithUTF8String:current.VerStr()];
1758 _profile(Package$initWithIterator$Installed)
1759 installed_ = [StripVersion(installed) retain];
1762 _profile(Package$initWithIterator$File)
1763 if (!version_.end())
1764 file_ = version_.FileList();
1766 pkgCache &cache([database_ cache]);
1767 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
1771 _profile(Package$initWithIterator$Name)
1772 id_ = [[NSString stringWithUTF8String:iterator_.Name()] retain];
1776 _profile(Package$initWithIterator$Parse)
1777 pkgRecords::Parser *parser;
1779 _profile(Package$initWithIterator$Parse$Lookup)
1780 parser = &[database_ records]->Lookup(file_);
1783 const char *begin, *end;
1784 parser->GetRec(begin, end);
1795 {"depiction", &depiction_},
1796 {"homepage", &homepage_},
1797 {"website", &website},
1798 {"support", &support_},
1799 {"sponsor", &sponsor_},
1800 {"author", &author_},
1804 while (begin != end)
1805 if (*begin == '\n') {
1808 } else if (isblank(*begin)) next: {
1809 begin = static_cast<char *>(memchr(begin + 1, '\n', end - begin - 1));
1812 } else if (const char *colon = static_cast<char *>(memchr(begin, ':', end - begin))) {
1813 const char *name(begin);
1814 size_t size(colon - begin);
1816 begin = static_cast<char *>(memchr(begin, '\n', end - begin));
1819 const char *stop(begin == NULL ? end : begin);
1820 while (stop[-1] == '\r')
1822 while (++colon != stop && isblank(*colon));
1824 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i)
1825 if (strncasecmp(names[i].name_, name, size) == 0) {
1826 CYString &value(*names[i].value_);
1828 _profile(Package$initWithIterator$Parse$Value)
1829 value.set(pool, colon, stop - colon);
1841 _profile(Package$initWithIterator$Parse$Tagline)
1842 tagline_.set(pool, parser->ShortDesc());
1845 _profile(Package$initWithIterator$Parse$Retain)
1846 if (!homepage_.empty())
1847 homepage_ = website;
1848 if (homepage_ == depiction_)
1851 tags_ = [[tag componentsSeparatedByString:@", "] retain];
1855 _profile(Package$initWithIterator$Tags)
1857 for (NSString *tag in tags_)
1858 if ([tag hasPrefix:@"role::"]) {
1859 role_ = [[tag substringFromIndex:6] retain];
1864 NSString *solid(latest == nil ? installed : latest);
1865 bool changed(false);
1867 NSString *key([id_ lowercaseString]);
1869 _profile(Package$initWithIterator$Metadata)
1870 metadata_ = [Packages_ objectForKey:key];
1871 if (metadata_ == nil) {
1872 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
1877 [metadata_ setObject:solid forKey:@"LastVersion"];
1880 NSDate *first([metadata_ objectForKey:@"FirstSeen"]);
1881 NSDate *last([metadata_ objectForKey:@"LastSeen"]);
1882 NSString *version([metadata_ objectForKey:@"LastVersion"]);
1885 first = last == nil ? now_ : last;
1886 [metadata_ setObject:first forKey:@"FirstSeen"];
1891 if (version == nil) {
1892 [metadata_ setObject:solid forKey:@"LastVersion"];
1894 } else if (![version isEqualToString:solid]) {
1895 [metadata_ setObject:solid forKey:@"LastVersion"];
1897 [metadata_ setObject:last forKey:@"LastSeen"];
1902 metadata_ = [metadata_ retain];
1905 [Packages_ setObject:metadata_ forKey:key];
1910 _profile(Package$initWithIterator$Section)
1911 section_.set(pool, iterator_.Section());
1914 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
1915 } _end } return self;
1918 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
1919 return [[[Package alloc]
1920 initWithIterator:iterator
1927 - (pkgCache::PkgIterator) iterator {
1931 - (NSString *) section {
1932 if (section$_ == nil) {
1933 if (section_.empty())
1936 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
1937 NSString *name(section_);
1940 if (NSDictionary *value = [SectionMap_ objectForKey:name])
1941 if (NSString *rename = [value objectForKey:@"Rename"]) {
1946 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
1950 - (NSString *) simpleSection {
1951 if (NSString *section = [self section])
1952 return Simplify(section);
1957 - (NSString *) longSection {
1958 return LocalizeSection(section_);
1961 - (NSString *) shortSection {
1962 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
1965 - (NSString *) uri {
1968 pkgIndexFile *index;
1969 pkgCache::PkgFileIterator file(file_.File());
1970 if (![database_ list].FindIndex(file, index))
1972 return [NSString stringWithUTF8String:iterator_->Path];
1973 //return [NSString stringWithUTF8String:file.Site()];
1974 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
1978 - (Address *) maintainer {
1981 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
1982 const std::string &maintainer(parser->Maintainer());
1983 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
1987 return version_.end() ? 0 : version_->InstalledSize;
1990 - (NSString *) description {
1993 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
1994 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
1996 NSArray *lines = [description componentsSeparatedByString:@"\n"];
1997 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
1998 if ([lines count] < 2)
2001 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2002 for (size_t i(1), e([lines count]); i != e; ++i) {
2003 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2004 [trimmed addObject:trim];
2007 return [trimmed componentsJoinedByString:@"\n"];
2011 _profile(Package$index)
2012 NSString *name([self name]);
2013 if ([name length] == 0)
2015 unichar character([name characterAtIndex:0]);
2016 if (!isalpha(character))
2018 return toupper(character);
2022 - (NSMutableDictionary *) metadata {
2023 if (metadata_ == nil)
2024 metadata_ = [[Packages_ objectForKey:[id_ lowercaseString]] retain];
2029 NSDictionary *metadata([self metadata]);
2030 if ([self subscribed])
2031 if (NSDate *last = [metadata objectForKey:@"LastSeen"])
2033 return [metadata objectForKey:@"FirstSeen"];
2036 - (BOOL) subscribed {
2037 NSDictionary *metadata([self metadata]);
2038 if (NSNumber *subscribed = [metadata objectForKey:@"IsSubscribed"])
2039 return [subscribed boolValue];
2045 NSDictionary *metadata([self metadata]);
2046 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2047 return [ignored boolValue];
2052 - (NSString *) latest {
2056 - (NSString *) installed {
2061 return !version_.end();
2064 - (BOOL) upgradableAndEssential:(BOOL)essential {
2065 pkgCache::VerIterator current = iterator_.CurrentVer();
2069 value = essential && [self essential] && [self visible];
2071 value = !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2075 - (BOOL) essential {
2080 return [database_ cache][iterator_].InstBroken();
2083 - (BOOL) unfiltered {
2084 NSString *section = [self section];
2085 return section == nil || isSectionVisible(section);
2089 return [self hasSupportingRole] && [self unfiltered];
2093 unsigned char current = iterator_->CurrentState;
2094 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2097 - (BOOL) halfConfigured {
2098 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2101 - (BOOL) halfInstalled {
2102 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2106 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2107 return state.Mode != pkgDepCache::ModeKeep;
2110 - (NSString *) mode {
2111 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2113 switch (state.Mode) {
2114 case pkgDepCache::ModeDelete:
2115 if ((state.iFlags & pkgDepCache::Purge) != 0)
2119 case pkgDepCache::ModeKeep:
2120 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2121 return @"REINSTALL";
2122 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2126 case pkgDepCache::ModeInstall:
2127 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2128 return @"REINSTALL";
2129 else*/ switch (state.Status) {
2131 return @"DOWNGRADE";
2137 return @"NEW_INSTALL";
2150 - (NSString *) name {
2151 return name_ == nil ? id_ : name_;
2154 - (NSString *) tagline {
2158 - (UIImage *) icon {
2159 NSString *section = [self simpleSection];
2163 if ([icon_ hasPrefix:@"file:///"])
2164 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2165 if (icon == nil) if (section != nil)
2166 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2167 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2168 if ([dicon hasPrefix:@"file:///"])
2169 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2171 icon = [UIImage applicationImageNamed:@"unknown.png"];
2175 - (NSString *) homepage {
2179 - (NSString *) depiction {
2183 - (Address *) sponsor {
2184 if (sponsor$_ == nil) {
2185 if (sponsor_.empty())
2187 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2191 - (Address *) author {
2192 if (author$_ == nil) {
2193 if (author_.empty())
2195 author$_ = [[Address addressWithString:author_] retain];
2199 - (NSString *) support {
2200 return support_ != nil ? support_ : [[self source] supportForPackage:id_];
2203 - (NSArray *) files {
2204 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", id_];
2205 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2208 fin.open([path UTF8String]);
2213 while (std::getline(fin, line))
2214 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2219 - (NSArray *) relationships {
2220 return relationships_;
2223 - (NSArray *) warnings {
2224 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2225 const char *name(iterator_.Name());
2227 size_t length(strlen(name));
2228 if (length < 2) invalid:
2229 [warnings addObject:CYLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2230 else for (size_t i(0); i != length; ++i)
2232 /* XXX: technically this is not allowed */
2233 (name[i] < 'A' || name[i] > 'Z') &&
2234 (name[i] < 'a' || name[i] > 'z') &&
2235 (name[i] < '0' || name[i] > '9') &&
2236 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2239 if (strcmp(name, "cydia") != 0) {
2241 bool _private = false;
2244 bool repository = [[self section] isEqualToString:@"Repositories"];
2246 if (NSArray *files = [self files])
2247 for (NSString *file in files)
2248 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2250 else if (!_private && [file isEqualToString:@"/private"])
2252 else if (!stash && [file isEqualToString:@"/var/stash"])
2255 /* XXX: this is not sensitive enough. only some folders are valid. */
2256 if (cydia && !repository)
2257 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2259 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/private"]];
2261 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2264 return [warnings count] == 0 ? nil : warnings;
2267 - (NSArray *) applications {
2268 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2270 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2272 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2273 if (NSArray *files = [self files])
2274 for (NSString *file in files)
2275 if (application_r(file)) {
2276 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2277 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2278 if ([id isEqualToString:me])
2281 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2283 display = application_r[1];
2285 NSString *bundle([file stringByDeletingLastPathComponent]);
2286 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2287 if (icon == nil || [icon length] == 0)
2289 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2291 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2292 [applications addObject:application];
2294 [application addObject:id];
2295 [application addObject:display];
2296 [application addObject:url];
2299 return [applications count] == 0 ? nil : applications;
2302 - (Source *) source {
2304 @synchronized (database_) {
2305 if ([database_ era] != era_ || file_.end())
2308 source_ = [database_ getSource:file_.File()];
2320 - (NSString *) role {
2324 - (BOOL) matches:(NSString *)text {
2330 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2331 if (range.location != NSNotFound)
2334 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2335 if (range.location != NSNotFound)
2338 range = [[self tagline] rangeOfString:text options:MatchCompareOptions_];
2339 if (range.location != NSNotFound)
2345 - (bool) hasSupportingRole {
2348 if ([role_ isEqualToString:@"enduser"])
2350 if ([Role_ isEqualToString:@"User"])
2352 if ([role_ isEqualToString:@"hacker"])
2354 if ([Role_ isEqualToString:@"Hacker"])
2356 if ([role_ isEqualToString:@"developer"])
2358 if ([Role_ isEqualToString:@"Developer"])
2363 - (BOOL) hasTag:(NSString *)tag {
2364 return tags_ == nil ? NO : [tags_ containsObject:tag];
2367 - (NSString *) primaryPurpose {
2368 for (NSString *tag in tags_)
2369 if ([tag hasPrefix:@"purpose::"])
2370 return [tag substringFromIndex:9];
2374 - (NSArray *) purposes {
2375 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2376 for (NSString *tag in tags_)
2377 if ([tag hasPrefix:@"purpose::"])
2378 [purposes addObject:[tag substringFromIndex:9]];
2379 return [purposes count] == 0 ? nil : purposes;
2382 - (bool) isCommercial {
2383 return [self hasTag:@"cydia::commercial"];
2386 - (uint32_t) compareByPrefix {
2390 - (NSComparisonResult) compareByName:(Package *)package {
2391 NSString *lhs = [self name];
2392 NSString *rhs = [package name];
2394 /*if ([lhs length] != 0 && [rhs length] != 0) {
2395 unichar lhc = [lhs characterAtIndex:0];
2396 unichar rhc = [rhs characterAtIndex:0];
2398 if (isalpha(lhc) && !isalpha(rhc))
2399 return NSOrderedAscending;
2400 else if (!isalpha(lhc) && isalpha(rhc))
2401 return NSOrderedDescending;
2404 return [lhs compare:rhs options:LaxCompareOptions_];*/
2406 return [lhs compare:rhs];
2409 - (uint32_t) compareBySection:(NSArray *)sections {
2410 NSString *section([self section]);
2411 for (size_t i(0), e([sections count]); i != e; ++i) {
2412 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2416 return _not(uint32_t);
2419 - (uint32_t) compareForChanges {
2424 uint32_t timestamp : 30;
2425 uint32_t ignored : 1;
2426 uint32_t upgradable : 1;
2430 bool upgradable([self upgradableAndEssential:YES]);
2431 value.bits.upgradable = upgradable ? 1 : 0;
2434 value.bits.timestamp = 0;
2435 value.bits.ignored = [self ignored] ? 0 : 1;
2436 value.bits.upgradable = 1;
2438 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2439 value.bits.ignored = 0;
2440 value.bits.upgradable = 0;
2443 return _not(uint32_t) - value.key;
2447 pkgProblemResolver *resolver = [database_ resolver];
2448 resolver->Clear(iterator_);
2449 resolver->Protect(iterator_);
2453 pkgProblemResolver *resolver = [database_ resolver];
2454 resolver->Clear(iterator_);
2455 resolver->Protect(iterator_);
2456 pkgCacheFile &cache([database_ cache]);
2457 cache->MarkInstall(iterator_, false);
2458 pkgDepCache::StateCache &state((*cache)[iterator_]);
2459 if (!state.Install())
2460 cache->SetReInstall(iterator_, true);
2464 pkgProblemResolver *resolver = [database_ resolver];
2465 resolver->Clear(iterator_);
2466 resolver->Protect(iterator_);
2467 resolver->Remove(iterator_);
2468 [database_ cache]->MarkDelete(iterator_, true);
2471 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2472 _profile(Package$isUnfilteredAndSearchedForBy)
2475 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2476 value &= [self unfiltered];
2479 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2480 value &= [self matches:search];
2487 - (bool) isInstalledAndVisible:(NSNumber *)number {
2488 return (![number boolValue] || [self visible]) && [self installed] != nil;
2491 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2492 NSString *section = [self section];
2496 [self installed] == nil && (
2498 section == nil && [name length] == 0 ||
2499 [name isEqualToString:section]
2503 - (bool) isVisibleInSource:(Source *)source {
2504 return [self source] == source && [self visible];
2509 /* Section Class {{{ */
2510 @interface Section : NSObject {
2515 NSString *localized_;
2518 - (NSComparisonResult) compareByName:(Section *)section;
2519 - (Section *) initWithName:(NSString *)name;
2520 - (Section *) initWithName:(NSString *)name row:(size_t)row;
2521 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2522 - (NSString *) name;
2529 - (void) addToCount;
2531 - (void) setCount:(size_t)count;
2535 @implementation Section
2539 if (localized_ != nil)
2540 [localized_ release];
2544 - (NSComparisonResult) compareByName:(Section *)section {
2545 NSString *lhs = [self name];
2546 NSString *rhs = [section name];
2548 if ([lhs length] != 0 && [rhs length] != 0) {
2549 unichar lhc = [lhs characterAtIndex:0];
2550 unichar rhc = [rhs characterAtIndex:0];
2552 if (isalpha(lhc) && !isalpha(rhc))
2553 return NSOrderedAscending;
2554 else if (!isalpha(lhc) && isalpha(rhc))
2555 return NSOrderedDescending;
2558 return [lhs compare:rhs options:LaxCompareOptions_];
2561 - (Section *) initWithName:(NSString *)name {
2562 return [self initWithName:name row:0];
2565 - (Section *) initWithName:(NSString *)name row:(size_t)row {
2566 if ((self = [super init]) != nil) {
2567 name_ = [name retain];
2570 localized_ = LocalizeSection(name_);
2574 /* XXX: localize the index thingees */
2575 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2576 if ((self = [super init]) != nil) {
2577 name_ = [(index == '#' ? @"123" : [NSString stringWithCharacters:&index length:1]) retain];
2583 - (NSString *) name {
2603 - (void) addToCount {
2607 - (void) setCount:(size_t)count {
2611 - (NSString *) localized {
2619 static NSArray *Finishes_;
2621 /* Database Implementation {{{ */
2622 @implementation Database
2624 + (Database *) sharedInstance {
2625 static Database *instance;
2626 if (instance == nil)
2627 instance = [[Database alloc] init];
2637 NSRecycleZone(zone_);
2638 // XXX: malloc_destroy_zone(zone_);
2639 apr_pool_destroy(pool_);
2643 - (void) _readCydia:(NSNumber *)fd { _pooled
2644 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2645 std::istream is(&ib);
2648 static Pcre finish_r("^finish:([^:]*)$");
2650 while (std::getline(is, line)) {
2651 const char *data(line.c_str());
2652 size_t size = line.size();
2653 lprintf("C:%s\n", data);
2655 if (finish_r(data, size)) {
2656 NSString *finish = finish_r[1];
2657 int index = [Finishes_ indexOfObject:finish];
2658 if (index != INT_MAX && index > Finish_)
2666 - (void) _readStatus:(NSNumber *)fd { _pooled
2667 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2668 std::istream is(&ib);
2671 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2672 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2674 while (std::getline(is, line)) {
2675 const char *data(line.c_str());
2676 size_t size = line.size();
2677 lprintf("S:%s\n", data);
2679 if (conffile_r(data, size)) {
2680 [delegate_ setConfigurationData:conffile_r[1]];
2681 } else if (strncmp(data, "status: ", 8) == 0) {
2682 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2683 [delegate_ setProgressTitle:string];
2684 } else if (pmstatus_r(data, size)) {
2685 std::string type([pmstatus_r[1] UTF8String]);
2686 NSString *id = pmstatus_r[2];
2688 float percent([pmstatus_r[3] floatValue]);
2689 [delegate_ setProgressPercent:(percent / 100)];
2691 NSString *string = pmstatus_r[4];
2693 if (type == "pmerror")
2694 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2695 withObject:[NSArray arrayWithObjects:string, id, nil]
2698 else if (type == "pmstatus") {
2699 [delegate_ setProgressTitle:string];
2700 } else if (type == "pmconffile")
2701 [delegate_ setConfigurationData:string];
2702 else _assert(false);
2703 } else _assert(false);
2709 - (void) _readOutput:(NSNumber *)fd { _pooled
2710 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2711 std::istream is(&ib);
2714 while (std::getline(is, line)) {
2715 lprintf("O:%s\n", line.c_str());
2716 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2726 - (Package *) packageWithName:(NSString *)name {
2727 if (static_cast<pkgDepCache *>(cache_) == NULL)
2729 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
2730 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
2733 - (Database *) init {
2734 if ((self = [super init]) != nil) {
2741 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
2742 apr_pool_create(&pool_, NULL);
2744 sources_ = [[NSMutableDictionary dictionaryWithCapacity:16] retain];
2745 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
2749 _assert(pipe(fds) != -1);
2752 _config->Set("APT::Keep-Fds::", cydiafd_);
2753 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
2756 detachNewThreadSelector:@selector(_readCydia:)
2758 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2761 _assert(pipe(fds) != -1);
2765 detachNewThreadSelector:@selector(_readStatus:)
2767 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2770 _assert(pipe(fds) != -1);
2771 _assert(dup2(fds[0], 0) != -1);
2772 _assert(close(fds[0]) != -1);
2774 input_ = fdopen(fds[1], "a");
2776 _assert(pipe(fds) != -1);
2777 _assert(dup2(fds[1], 1) != -1);
2778 _assert(close(fds[1]) != -1);
2781 detachNewThreadSelector:@selector(_readOutput:)
2783 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2788 - (pkgCacheFile &) cache {
2792 - (pkgDepCache::Policy *) policy {
2796 - (pkgRecords *) records {
2800 - (pkgProblemResolver *) resolver {
2804 - (pkgAcquire &) fetcher {
2808 - (pkgSourceList &) list {
2812 - (NSArray *) packages {
2816 - (NSArray *) sources {
2817 return [sources_ allValues];
2820 - (NSArray *) issues {
2821 if (cache_->BrokenCount() == 0)
2824 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
2826 for (Package *package in packages_) {
2827 if (![package broken])
2829 pkgCache::PkgIterator pkg([package iterator]);
2831 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
2832 [entry addObject:[package name]];
2833 [issues addObject:entry];
2835 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
2839 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
2840 pkgCache::DepIterator start;
2841 pkgCache::DepIterator end;
2842 dep.GlobOr(start, end); // ++dep
2844 if (!cache_->IsImportantDep(end))
2846 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
2849 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
2850 [entry addObject:failure];
2851 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
2853 Package *package([self packageWithName:[NSString stringWithUTF8String:start.TargetPkg().Name()]]);
2854 [failure addObject:[package name]];
2856 pkgCache::PkgIterator target(start.TargetPkg());
2857 if (target->ProvidesList != 0)
2858 [failure addObject:@"?"];
2860 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
2862 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
2863 else if (!cache_[target].CandidateVerIter(cache_).end())
2864 [failure addObject:@"-"];
2865 else if (target->ProvidesList == 0)
2866 [failure addObject:@"!"];
2868 [failure addObject:@"%"];
2872 if (start.TargetVer() != 0)
2873 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
2884 - (void) reloadData { _pooled
2885 @synchronized (self) {
2907 apr_pool_clear(pool_);
2908 NSRecycleZone(zone_);
2911 if (!cache_.Open(progress_, true)) {
2913 if (!_error->PopMessage(error))
2916 lprintf("cache_.Open():[%s]\n", error.c_str());
2918 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
2919 [delegate_ repairWithSelector:@selector(configure)];
2920 else if (error == "The package lists or status file could not be parsed or opened.")
2921 [delegate_ repairWithSelector:@selector(update)];
2922 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
2923 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
2924 // else if (error == "The list of sources could not be read.")
2925 else _assert(false);
2931 now_ = [[NSDate date] retain];
2933 policy_ = new pkgDepCache::Policy();
2934 records_ = new pkgRecords(cache_);
2935 resolver_ = new pkgProblemResolver(cache_);
2936 fetcher_ = new pkgAcquire(&status_);
2939 list_ = new pkgSourceList();
2940 _assert(list_->ReadMainList());
2942 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
2943 _assert(pkgApplyStatus(cache_));
2945 if (cache_->BrokenCount() != 0) {
2946 _assert(pkgFixBroken(cache_));
2947 _assert(cache_->BrokenCount() == 0);
2948 _assert(pkgMinimizeUpgrade(cache_));
2951 [sources_ removeAllObjects];
2952 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
2953 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
2954 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
2956 setObject:[[[Source alloc] initWithMetaIndex:*source] autorelease]
2957 forKey:[NSNumber numberWithLong:reinterpret_cast<uintptr_t>(*index)]
2961 [packages_ removeAllObjects];
2963 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
2964 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
2965 [packages_ addObject:package];
2967 [packages_ sortUsingSelector:@selector(compareByName:)];
2970 _config->Set("Acquire::http::Timeout", 15);
2971 _config->Set("Acquire::http::MaxParallel", 4);
2974 - (void) configure {
2975 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
2976 system([dpkg UTF8String]);
2984 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
2985 _assert(!_error->PendingError());
2988 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
2991 public pkgArchiveCleaner
2994 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
2999 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3001 while (_error->PopMessage(error))
3002 lprintf("ArchiveCleaner: %s\n", error.c_str());
3007 pkgRecords records(cache_);
3009 lock_ = new FileFd();
3010 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3011 _assert(!_error->PendingError());
3014 // XXX: explain this with an error message
3015 _assert(list.ReadMainList());
3017 manager_ = (_system->CreatePM(cache_));
3018 _assert(manager_->GetArchives(fetcher_, &list, &records));
3019 _assert(!_error->PendingError());
3023 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3025 _assert(list.ReadMainList());
3026 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3027 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3030 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3035 bool failed = false;
3036 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3037 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3040 std::string uri = (*item)->DescURI();
3041 std::string error = (*item)->ErrorText;
3043 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3046 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3047 withObject:[NSArray arrayWithObjects:
3048 [NSString stringWithUTF8String:error.c_str()],
3060 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3062 if (_error->PendingError()) {
3067 if (result == pkgPackageManager::Failed) {
3072 if (result != pkgPackageManager::Completed) {
3077 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3079 _assert(list.ReadMainList());
3080 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3081 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3084 if (![before isEqualToArray:after])
3089 _assert(pkgDistUpgrade(cache_));
3093 [self updateWithStatus:status_];
3096 - (void) updateWithStatus:(Status &)status {
3098 _assert(list.ReadMainList());
3101 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3102 _assert(!_error->PendingError());
3104 pkgAcquire fetcher(&status);
3105 _assert(list.GetIndexes(&fetcher));
3107 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3108 bool failed = false;
3109 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3110 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3111 (*item)->Finished();
3115 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3116 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3117 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3120 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3125 - (void) setDelegate:(id)delegate {
3126 delegate_ = delegate;
3127 status_.setDelegate(delegate);
3128 progress_.setDelegate(delegate);
3131 - (Source *) getSource:(const pkgCache::PkgFileIterator &)file {
3132 pkgIndexFile *index(NULL);
3133 list_->FindIndex(file, index);
3134 return [sources_ objectForKey:[NSNumber numberWithLong:reinterpret_cast<uintptr_t>(index)]];
3140 /* PopUp Windows {{{ */
3141 @interface PopUpView : UIView {
3142 _transient id delegate_;
3143 UITransitionView *transition_;
3148 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3152 @implementation PopUpView
3155 [transition_ setDelegate:nil];
3156 [transition_ release];
3162 [transition_ transition:UITransitionPushFromTop toView:nil];
3165 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3166 if (from != nil && to == nil)
3167 [self removeFromSuperview];
3170 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3171 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3172 delegate_ = delegate;
3174 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3175 [self addSubview:transition_];
3177 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3179 [view addSubview:self];
3181 [transition_ setDelegate:self];
3183 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3184 [transition_ transition:UITransitionNone toView:blank];
3185 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3193 /* Mail Composition {{{ */
3194 @interface MailToView : PopUpView {
3195 MailComposeController *controller_;
3198 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
3202 @implementation MailToView
3205 [controller_ release];
3209 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
3213 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
3214 NSLog(@"did:%@", delivery);
3215 // [UIApp setStatusBarShowsProgress:NO];
3216 if ([controller error]){
3217 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3218 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3219 [mailAlertSheet setBodyText:[controller error]];
3220 [mailAlertSheet popupAlertAnimated:YES];
3224 - (void) showError {
3225 NSLog(@"%@", [controller_ error]);
3226 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3227 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3228 [mailAlertSheet setBodyText:[controller_ error]];
3229 [mailAlertSheet popupAlertAnimated:YES];
3232 - (void) deliverMessage { _pooled
3236 if (![controller_ deliverMessage])
3237 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
3240 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
3241 if ([controller_ needsDelivery])
3242 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
3247 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
3248 if ((self = [super initWithView:view delegate:delegate]) != nil) {
3249 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
3250 [controller_ setDelegate:self];
3251 [controller_ initializeUI];
3252 [controller_ setupForURL:url];
3254 UIView *view([controller_ view]);
3255 [overlay_ addSubview:view];
3263 /* Confirmation View {{{ */
3264 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3265 if (!iterator.end())
3266 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3267 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3269 pkgCache::PkgIterator package(dep.TargetPkg());
3272 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3279 @protocol ConfirmationViewDelegate
3285 @interface ConfirmationView : BrowserView {
3286 _transient Database *database_;
3287 UIActionSheet *essential_;
3294 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3298 @implementation ConfirmationView
3305 if (essential_ != nil)
3306 [essential_ release];
3312 [book_ popFromSuperviewAnimated:YES];
3315 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3316 NSString *context([sheet context]);
3318 if ([context isEqualToString:@"remove"]) {
3326 [delegate_ confirm];
3333 } else if ([context isEqualToString:@"unable"]) {
3337 [super alertSheet:sheet buttonClicked:button];
3340 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3341 [super webView:sender didClearWindowObject:window forFrame:frame];
3342 [window setValue:changes_ forKey:@"changes"];
3343 [window setValue:issues_ forKey:@"issues"];
3344 [window setValue:sizes_ forKey:@"sizes"];
3347 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3348 if ((self = [super initWithBook:book]) != nil) {
3349 database_ = database;
3351 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3352 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3353 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3354 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3355 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3359 pkgDepCache::Policy *policy([database_ policy]);
3361 pkgCacheFile &cache([database_ cache]);
3362 NSArray *packages = [database_ packages];
3363 for (Package *package in packages) {
3364 pkgCache::PkgIterator iterator = [package iterator];
3365 pkgDepCache::StateCache &state(cache[iterator]);
3367 NSString *name([package name]);
3369 if (state.NewInstall())
3370 [installing addObject:name];
3371 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3372 [reinstalling addObject:name];
3373 else if (state.Upgrade())
3374 [upgrading addObject:name];
3375 else if (state.Downgrade())
3376 [downgrading addObject:name];
3377 else if (state.Delete()) {
3378 if ([package essential])
3380 [removing addObject:name];
3383 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3384 substrate_ |= DepSubstrate(iterator.CurrentVer());
3389 else if (Advanced_ || true) {
3390 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
3392 essential_ = [[UIActionSheet alloc]
3393 initWithTitle:CYLocalize("REMOVING_ESSENTIALS")
3394 buttons:[NSArray arrayWithObjects:
3395 [NSString stringWithFormat:parenthetical, CYLocalize("CANCEL_OPERATION"), CYLocalize("SAFE")],
3396 [NSString stringWithFormat:parenthetical, CYLocalize("FORCE_REMOVAL"), CYLocalize("UNSAFE")],
3398 defaultButtonIndex:0
3404 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3406 [essential_ setBodyText:CYLocalize("REMOVING_ESSENTIALS_EX")];
3408 essential_ = [[UIActionSheet alloc]
3409 initWithTitle:CYLocalize("UNABLE_TO_COMPLY")
3410 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3411 defaultButtonIndex:0
3416 [essential_ setBodyText:CYLocalize("UNABLE_TO_COMPLY_EX")];
3419 changes_ = [[NSArray alloc] initWithObjects:
3427 issues_ = [database_ issues];
3429 issues_ = [issues_ retain];
3431 sizes_ = [[NSArray alloc] initWithObjects:
3432 SizeString([database_ fetcher].FetchNeeded()),
3433 SizeString([database_ fetcher].PartialPresent()),
3434 SizeString([database_ cache]->UsrSize()),
3437 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3441 - (NSString *) backButtonTitle {
3442 return CYLocalize("CONFIRM");
3445 - (NSString *) leftButtonTitle {
3446 return [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("CANCEL"), CYLocalize("QUEUE")];
3449 - (id) rightButtonTitle {
3450 return issues_ != nil ? nil : [super rightButtonTitle];
3453 - (id) _rightButtonTitle {
3454 #if AlwaysReload || IgnoreInstall
3455 return [super _rightButtonTitle];
3457 return CYLocalize("CONFIRM");
3461 - (void) _leftButtonClicked {
3466 - (void) _rightButtonClicked {
3468 return [super _rightButtonClicked];
3470 if (essential_ != nil)
3471 [essential_ popupAlertAnimated:YES];
3475 [delegate_ confirm];
3483 /* Progress Data {{{ */
3484 @interface ProgressData : NSObject {
3490 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3497 @implementation ProgressData
3499 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3500 if ((self = [super init]) != nil) {
3501 selector_ = selector;
3521 /* Progress View {{{ */
3522 @interface ProgressView : UIView <
3523 ConfigurationDelegate,
3526 _transient Database *database_;
3528 UIView *background_;
3529 UITransitionView *transition_;
3531 UINavigationBar *navbar_;
3532 UIProgressBar *progress_;
3533 UITextView *output_;
3534 UITextLabel *status_;
3535 UIPushButton *close_;
3538 SHA1SumValue springlist_;
3539 SHA1SumValue notifyconf_;
3540 SHA1SumValue sandplate_;
3543 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
3545 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
3546 - (void) setContentView:(UIView *)view;
3549 - (void) _retachThread;
3550 - (void) _detachNewThreadData:(ProgressData *)data;
3551 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
3557 @protocol ProgressViewDelegate
3558 - (void) progressViewIsComplete:(ProgressView *)sender;
3561 @implementation ProgressView
3564 [transition_ setDelegate:nil];
3565 [navbar_ setDelegate:nil];
3568 if (background_ != nil)
3569 [background_ release];
3570 [transition_ release];
3573 [progress_ release];
3580 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3581 if (bootstrap_ && from == overlay_ && to == view_)
3585 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
3586 if ((self = [super initWithFrame:frame]) != nil) {
3587 database_ = database;
3588 delegate_ = delegate;
3590 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3591 [transition_ setDelegate:self];
3593 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3596 [overlay_ setBackgroundColor:[UIColor blackColor]];
3598 background_ = [[UIView alloc] initWithFrame:[self bounds]];
3599 [background_ setBackgroundColor:[UIColor blackColor]];
3600 [self addSubview:background_];
3603 [self addSubview:transition_];
3605 CGSize navsize = [UINavigationBar defaultSize];
3606 CGRect navrect = {{0, 0}, navsize};
3608 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
3609 [overlay_ addSubview:navbar_];
3611 [navbar_ setBarStyle:1];
3612 [navbar_ setDelegate:self];
3614 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
3615 [navbar_ pushNavigationItem:navitem];
3617 CGRect bounds = [overlay_ bounds];
3618 CGSize prgsize = [UIProgressBar defaultSize];
3621 (bounds.size.width - prgsize.width) / 2,
3622 bounds.size.height - prgsize.height - 20
3625 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3626 [progress_ setStyle:0];
3628 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3630 bounds.size.height - prgsize.height - 50,
3631 bounds.size.width - 20,
3635 [status_ setColor:[UIColor whiteColor]];
3636 [status_ setBackgroundColor:[UIColor clearColor]];
3638 [status_ setCentersHorizontally:YES];
3639 //[status_ setFont:font];
3642 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3644 navrect.size.height + 20,
3645 bounds.size.width - 20,
3646 bounds.size.height - navsize.height - 62 - navrect.size.height
3650 //[output_ setTextFont:@"Courier New"];
3651 [output_ setTextSize:12];
3653 [output_ setTextColor:[UIColor whiteColor]];
3654 [output_ setBackgroundColor:[UIColor clearColor]];
3656 [output_ setMarginTop:0];
3657 [output_ setAllowsRubberBanding:YES];
3658 [output_ setEditable:NO];
3660 [overlay_ addSubview:output_];
3662 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3664 bounds.size.height - prgsize.height - 50,
3665 bounds.size.width - 20,
3669 [close_ setAutosizesToFit:NO];
3670 [close_ setDrawsShadow:YES];
3671 [close_ setStretchBackground:YES];
3672 [close_ setEnabled:YES];
3674 UIFont *bold = [UIFont boldSystemFontOfSize:22];
3675 [close_ setTitleFont:bold];
3677 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
3678 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
3679 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
3683 - (void) setContentView:(UIView *)view {
3684 view_ = [view retain];
3687 - (void) resetView {
3688 [transition_ transition:6 toView:view_];
3691 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3692 NSString *context([sheet context]);
3694 if ([context isEqualToString:@"error"])
3696 else if ([context isEqualToString:@"conffile"]) {
3697 FILE *input = [database_ input];
3701 fprintf(input, "N\n");
3705 fprintf(input, "Y\n");
3716 - (void) closeButtonPushed {
3725 [delegate_ suspendWithAnimation:YES];
3729 system("launchctl stop com.apple.SpringBoard");
3733 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
3742 - (void) _retachThread {
3743 UINavigationItem *item = [navbar_ topItem];
3744 [item setTitle:CYLocalize("COMPLETE")];
3746 [overlay_ addSubview:close_];
3747 [progress_ removeFromSuperview];
3748 [status_ removeFromSuperview];
3750 [delegate_ progressViewIsComplete:self];
3753 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
3754 MMap mmap(file, MMap::ReadOnly);
3756 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3757 if (!(sandplate_ == sha1.Result()))
3762 FileFd file(NotifyConfig_, FileFd::ReadOnly);
3763 MMap mmap(file, MMap::ReadOnly);
3765 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3766 if (!(notifyconf_ == sha1.Result()))
3771 FileFd file(SpringBoard_, FileFd::ReadOnly);
3772 MMap mmap(file, MMap::ReadOnly);
3774 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3775 if (!(springlist_ == sha1.Result()))
3780 case 0: [close_ setTitle:CYLocalize("RETURN_TO_CYDIA")]; break;
3781 case 1: [close_ setTitle:CYLocalize("CLOSE_CYDIA")]; break;
3782 case 2: [close_ setTitle:CYLocalize("RESTART_SPRINGBOARD")]; break;
3783 case 3: [close_ setTitle:CYLocalize("RELOAD_SPRINGBOARD")]; break;
3784 case 4: [close_ setTitle:CYLocalize("REBOOT_DEVICE")]; break;
3787 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
3789 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
3790 [cache autorelease];
3792 NSFileManager *manager = [NSFileManager defaultManager];
3793 NSError *error = nil;
3795 id system = [cache objectForKey:@"System"];
3800 if (stat(Cache_, &info) == -1)
3803 [system removeAllObjects];
3805 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
3806 for (NSString *app in apps)
3807 if ([app hasSuffix:@".app"]) {
3808 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
3809 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
3810 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
3812 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
3813 [info setObject:path forKey:@"Path"];
3814 [info setObject:@"System" forKey:@"ApplicationType"];
3815 [system addInfoDictionary:info];
3821 [cache writeToFile:@Cache_ atomically:YES];
3823 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
3825 if (chmod(Cache_, info.st_mode) == -1)
3829 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
3832 notify_post("com.apple.mobile.application_installed");
3834 [delegate_ setStatusBarShowsProgress:NO];
3837 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
3838 [[data target] performSelector:[data selector] withObject:[data object]];
3841 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
3844 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
3845 UINavigationItem *item = [navbar_ topItem];
3846 [item setTitle:title];
3848 [status_ setText:nil];
3849 [output_ setText:@""];
3850 [progress_ setProgress:0];
3852 [close_ removeFromSuperview];
3853 [overlay_ addSubview:progress_];
3854 [overlay_ addSubview:status_];
3856 [delegate_ setStatusBarShowsProgress:YES];
3860 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
3861 MMap mmap(file, MMap::ReadOnly);
3863 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3864 sandplate_ = sha1.Result();
3868 FileFd file(NotifyConfig_, FileFd::ReadOnly);
3869 MMap mmap(file, MMap::ReadOnly);
3871 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3872 notifyconf_ = sha1.Result();
3876 FileFd file(SpringBoard_, FileFd::ReadOnly);
3877 MMap mmap(file, MMap::ReadOnly);
3879 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3880 springlist_ = sha1.Result();
3883 [transition_ transition:6 toView:overlay_];
3886 detachNewThreadSelector:@selector(_detachNewThreadData:)
3888 withObject:[[ProgressData alloc]
3889 initWithSelector:selector
3896 - (void) repairWithSelector:(SEL)selector {
3898 detachNewThreadSelector:selector
3901 title:CYLocalize("REPAIRING")
3905 - (void) setConfigurationData:(NSString *)data {
3907 performSelectorOnMainThread:@selector(_setConfigurationData:)
3913 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
3914 Package *package = id == nil ? nil : [database_ packageWithName:id];
3916 UIActionSheet *sheet = [[[UIActionSheet alloc]
3917 initWithTitle:(package == nil ? id : [package name])
3918 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3919 defaultButtonIndex:0
3924 [sheet setBodyText:error];
3925 [sheet popupAlertAnimated:YES];
3928 - (void) setProgressTitle:(NSString *)title {
3930 performSelectorOnMainThread:@selector(_setProgressTitle:)
3936 - (void) setProgressPercent:(float)percent {
3938 performSelectorOnMainThread:@selector(_setProgressPercent:)
3939 withObject:[NSNumber numberWithFloat:percent]
3944 - (void) startProgress {
3947 - (void) addProgressOutput:(NSString *)output {
3949 performSelectorOnMainThread:@selector(_addProgressOutput:)
3955 - (bool) isCancelling:(size_t)received {
3959 - (void) _setConfigurationData:(NSString *)data {
3960 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
3962 _assert(conffile_r(data));
3964 NSString *ofile = conffile_r[1];
3965 //NSString *nfile = conffile_r[2];
3967 UIActionSheet *sheet = [[[UIActionSheet alloc]
3968 initWithTitle:CYLocalize("CONFIGURATION_UPGRADE")
3969 buttons:[NSArray arrayWithObjects:
3970 CYLocalize("KEEP_OLD_COPY"),
3971 CYLocalize("ACCEPT_NEW_COPY"),
3972 // XXX: CYLocalize("SEE_WHAT_CHANGED"),
3974 defaultButtonIndex:0
3979 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", CYLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
3980 [sheet popupAlertAnimated:YES];
3983 - (void) _setProgressTitle:(NSString *)title {
3984 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
3985 for (size_t i(0), e([words count]); i != e; ++i) {
3986 NSString *word([words objectAtIndex:i]);
3987 if (Package *package = [database_ packageWithName:word])
3988 [words replaceObjectAtIndex:i withObject:[package name]];
3991 [status_ setText:[words componentsJoinedByString:@" "]];
3994 - (void) _setProgressPercent:(NSNumber *)percent {
3995 [progress_ setProgress:[percent floatValue]];
3998 - (void) _addProgressOutput:(NSString *)output {
3999 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4000 CGSize size = [output_ contentSize];
4001 CGRect rect = {{0, size.height}, {size.width, 0}};
4002 [output_ scrollRectToVisible:rect animated:YES];
4005 - (BOOL) isRunning {
4012 /* Package Cell {{{ */
4013 @interface PackageCell : UITableCell {
4016 NSString *description_;
4023 UITextLabel *status_;
4027 - (PackageCell *) init;
4028 - (void) setPackage:(Package *)package;
4030 + (int) heightForPackage:(Package *)package;
4034 @implementation PackageCell
4036 - (void) clearPackage {
4047 if (description_ != nil) {
4048 [description_ release];
4052 if (source_ != nil) {
4057 if (badge_ != nil) {
4067 [self clearPackage];
4074 - (PackageCell *) init {
4075 if ((self = [super init]) != nil) {
4077 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4078 [status_ setBackgroundColor:[UIColor clearColor]];
4079 [status_ setFont:small];
4084 - (void) setPackage:(Package *)package {
4085 [self clearPackage];
4087 Source *source = [package source];
4089 icon_ = [[package icon] retain];
4090 name_ = [[package name] retain];
4091 description_ = [[package tagline] retain];
4092 commercial_ = [package isCommercial];
4094 package_ = [package retain];
4096 NSString *label = nil;
4097 bool trusted = false;
4099 if (source != nil) {
4100 label = [source label];
4101 trusted = [source trusted];
4102 } else if ([[package id] isEqualToString:@"firmware"])
4103 label = CYLocalize("APPLE");
4105 label = [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("UNKNOWN"), CYLocalize("LOCAL")];
4107 NSString *from(label);
4109 NSString *section = [package simpleSection];
4110 if (section != nil && ![section isEqualToString:label]) {
4111 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4112 from = [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), from, section];
4115 from = [NSString stringWithFormat:CYLocalize("FROM"), label];
4116 source_ = [from retain];
4118 if (NSString *purpose = [package primaryPurpose])
4119 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4120 badge_ = [badge_ retain];
4123 if (NSString *mode = [package mode]) {
4124 [badge_ setImage:[UIImage applicationImageNamed:
4125 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4128 [status_ setText:[NSString stringWithFormat:CYLocalize("QUEUED_FOR"), CYLocalize(mode)]];
4129 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4130 } else if ([package half]) {
4131 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4132 [status_ setText:CYLocalize("PACKAGE_DAMAGED")];
4133 [status_ setColor:[UIColor redColor]];
4135 [badge_ setImage:nil];
4136 [status_ setText:nil];
4143 - (void) drawRect:(CGRect)rect {
4147 if (NSString *mode = [package_ mode]) {
4148 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4149 color = remove ? RemovingColor_ : InstallingColor_;
4151 color = [UIColor whiteColor];
4153 [self setBackgroundColor:color];
4157 [super drawRect:rect];
4160 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4162 CGContextRef context(UIGraphicsGetCurrentContext());
4163 [[self backgroundColor] set];
4165 back.size.height -= 1;
4166 CGContextFillRect(context, back);
4169 [super drawBackgroundInRect:rect withFade:fade];
4172 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4175 rect.size = [icon_ size];
4177 rect.size.width /= 2;
4178 rect.size.height /= 2;
4180 rect.origin.x = 25 - rect.size.width / 2;
4181 rect.origin.y = 25 - rect.size.height / 2;
4183 [icon_ drawInRect:rect];
4186 if (badge_ != nil) {
4187 CGSize size = [badge_ size];
4189 [badge_ drawAtPoint:CGPointMake(
4190 36 - size.width / 2,
4191 36 - size.height / 2
4199 UISetColor(commercial_ ? Purple_ : Black_);
4200 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4201 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4204 UISetColor(commercial_ ? Purplish_ : Gray_);
4205 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4207 [super drawContentInRect:rect selected:selected];
4210 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4212 [super setSelected:selected withFade:fade];
4215 + (int) heightForPackage:(Package *)package {
4216 NSString *tagline([package tagline]);
4217 int height = tagline == nil || [tagline length] == 0 ? -17 : 0;
4219 if ([package hasMode] || [package half])
4228 /* Section Cell {{{ */
4229 @interface SectionCell : UISimpleTableCell {
4234 _UISwitchSlider *switch_;
4239 - (void) setSection:(Section *)section editing:(BOOL)editing;
4243 @implementation SectionCell
4245 - (void) clearSection {
4246 if (section_ != nil) {
4256 if (count_ != nil) {
4263 [self clearSection];
4270 if ((self = [super init]) != nil) {
4271 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4273 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4274 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4278 - (void) onSwitch:(id)sender {
4279 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4280 if (metadata == nil) {
4281 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4282 [Sections_ setObject:metadata forKey:section_];
4286 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4289 - (void) setSection:(Section *)section editing:(BOOL)editing {
4290 if (editing != editing_) {
4292 [switch_ removeFromSuperview];
4294 [self addSubview:switch_];
4298 [self clearSection];
4300 if (section == nil) {
4301 name_ = [CYLocalize("ALL_PACKAGES") retain];
4304 section_ = [section name];
4305 if (section_ != nil)
4306 section_ = [section_ retain];
4307 name_ = [(section_ == nil ? CYLocalize("NO_SECTION") : section_) retain];
4308 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4311 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4315 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4316 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4323 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4325 CGSize size = [count_ sizeWithFont:Font14_];
4329 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4331 [super drawContentInRect:rect selected:selected];
4337 /* File Table {{{ */
4338 @interface FileTable : RVPage {
4339 _transient Database *database_;
4342 NSMutableArray *files_;
4346 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4347 - (void) setPackage:(Package *)package;
4351 @implementation FileTable
4354 if (package_ != nil)
4363 - (int) numberOfRowsInTable:(UITable *)table {
4364 return files_ == nil ? 0 : [files_ count];
4367 - (float) table:(UITable *)table heightForRow:(int)row {
4371 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4372 if (reusing == nil) {
4373 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4374 UIFont *font = [UIFont systemFontOfSize:16];
4375 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4377 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4381 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4385 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4386 if ((self = [super initWithBook:book]) != nil) {
4387 database_ = database;
4389 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4391 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4392 [self addSubview:list_];
4394 UITableColumn *column = [[[UITableColumn alloc]
4395 initWithTitle:CYLocalize("NAME")
4397 width:[self frame].size.width
4400 [list_ setDataSource:self];
4401 [list_ setSeparatorStyle:1];
4402 [list_ addTableColumn:column];
4403 [list_ setDelegate:self];
4404 [list_ setReusesTableCells:YES];
4408 - (void) setPackage:(Package *)package {
4409 if (package_ != nil) {
4410 [package_ autorelease];
4419 [files_ removeAllObjects];
4421 if (package != nil) {
4422 package_ = [package retain];
4423 name_ = [[package id] retain];
4425 if (NSArray *files = [package files])
4426 [files_ addObjectsFromArray:files];
4428 if ([files_ count] != 0) {
4429 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4430 [files_ removeObjectAtIndex:0];
4431 [files_ sortUsingSelector:@selector(compareByPath:)];
4433 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4434 [stack addObject:@"/"];
4436 for (int i(0), e([files_ count]); i != e; ++i) {
4437 NSString *file = [files_ objectAtIndex:i];
4438 while (![file hasPrefix:[stack lastObject]])
4439 [stack removeLastObject];
4440 NSString *directory = [stack lastObject];
4441 [stack addObject:[file stringByAppendingString:@"/"]];
4442 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4443 ([stack count] - 2) * 3, "",
4444 [file substringFromIndex:[directory length]]
4453 - (void) resetViewAnimated:(BOOL)animated {
4454 [list_ resetViewAnimated:animated];
4457 - (void) reloadData {
4458 [self setPackage:[database_ packageWithName:name_]];
4459 [self reloadButtons];
4462 - (NSString *) title {
4463 return CYLocalize("INSTALLED_FILES");
4466 - (NSString *) backButtonTitle {
4467 return CYLocalize("FILES");
4472 /* Package View {{{ */
4473 @interface PackageView : BrowserView {
4474 _transient Database *database_;
4478 NSMutableArray *buttons_;
4481 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4482 - (void) setPackage:(Package *)package;
4486 @implementation PackageView
4489 if (package_ != nil)
4497 /*- (void) release {
4498 if ([self retainCount] == 1)
4499 [delegate_ setPackageView:self];
4503 /* XXX: this is not safe at all... localization of /fail/ */
4504 - (void) _clickButtonWithName:(NSString *)name {
4505 if ([name isEqualToString:CYLocalize("CLEAR")])
4506 [delegate_ clearPackage:package_];
4507 else if ([name isEqualToString:CYLocalize("INSTALL")])
4508 [delegate_ installPackage:package_];
4509 else if ([name isEqualToString:CYLocalize("REINSTALL")])
4510 [delegate_ installPackage:package_];
4511 else if ([name isEqualToString:CYLocalize("REMOVE")])
4512 [delegate_ removePackage:package_];
4513 else if ([name isEqualToString:CYLocalize("UPGRADE")])
4514 [delegate_ installPackage:package_];
4515 else _assert(false);
4518 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4519 NSString *context([sheet context]);
4521 if ([context isEqualToString:@"modify"]) {
4522 int count = [buttons_ count];
4523 _assert(count != 0);
4524 _assert(button <= count + 1);
4526 if (count != button - 1)
4527 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
4531 [super alertSheet:sheet buttonClicked:button];
4534 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
4535 return [super webView:sender didFinishLoadForFrame:frame];
4538 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4539 [super webView:sender didClearWindowObject:window forFrame:frame];
4540 [window setValue:package_ forKey:@"package"];
4543 - (bool) _allowJavaScriptPanel {
4548 - (void) __rightButtonClicked {
4549 int count = [buttons_ count];
4550 _assert(count != 0);
4553 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
4555 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
4556 [buttons addObjectsFromArray:buttons_];
4557 [buttons addObject:CYLocalize("CANCEL")];
4559 [delegate_ slideUp:[[[UIActionSheet alloc]
4562 defaultButtonIndex:([buttons count] - 1)
4569 - (void) _rightButtonClicked {
4571 [super _rightButtonClicked];
4573 [self __rightButtonClicked];
4577 - (id) _rightButtonTitle {
4578 int count = [buttons_ count];
4579 return count == 0 ? nil : count != 1 ? CYLocalize("MODIFY") : [buttons_ objectAtIndex:0];
4582 - (NSString *) backButtonTitle {
4586 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4587 if ((self = [super initWithBook:book]) != nil) {
4588 database_ = database;
4589 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
4590 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
4594 - (void) setPackage:(Package *)package {
4595 if (package_ != nil) {
4596 [package_ autorelease];
4605 [buttons_ removeAllObjects];
4607 if (package != nil) {
4608 package_ = [package retain];
4609 name_ = [[package id] retain];
4610 commercial_ = [package isCommercial];
4612 if ([package_ mode] != nil)
4613 [buttons_ addObject:CYLocalize("CLEAR")];
4614 if ([package_ source] == nil);
4615 else if ([package_ upgradableAndEssential:NO])
4616 [buttons_ addObject:CYLocalize("UPGRADE")];
4617 else if ([package_ installed] == nil)
4618 [buttons_ addObject:CYLocalize("INSTALL")];
4620 [buttons_ addObject:CYLocalize("REINSTALL")];
4621 if ([package_ installed] != nil)
4622 [buttons_ addObject:CYLocalize("REMOVE")];
4624 if (special_ != NULL) {
4625 CGRect frame([webview_ frame]);
4626 frame.size.width = 320;
4627 frame.size.height = 0;
4628 [webview_ setFrame:frame];
4630 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
4633 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
4635 [self setButtonTitle:nil withStyle:nil toFunction:nil];
4637 [self setFinishHook:nil];
4638 [self setPopupHook:nil];
4641 [super callFunction:special_];
4645 [self reloadButtons];
4648 - (bool) isLoading {
4649 return commercial_ ? [super isLoading] : false;
4652 - (void) reloadData {
4653 [self setPackage:[database_ packageWithName:name_]];
4658 /* Package Table {{{ */
4659 @interface PackageTable : RVPage {
4660 _transient Database *database_;
4662 NSMutableArray *packages_;
4663 NSMutableArray *sections_;
4664 UISectionList *list_;
4667 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
4669 - (void) setDelegate:(id)delegate;
4671 - (void) reloadData;
4672 - (void) resetCursor;
4674 - (UISectionList *) list;
4676 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
4680 @implementation PackageTable
4683 [list_ setDataSource:nil];
4686 [packages_ release];
4687 [sections_ release];
4692 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
4693 return [sections_ count];
4696 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
4697 return [[sections_ objectAtIndex:section] name];
4700 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
4701 return [[sections_ objectAtIndex:section] row];
4704 - (int) numberOfRowsInTable:(UITable *)table {
4705 return [packages_ count];
4708 - (float) table:(UITable *)table heightForRow:(int)row {
4709 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
4712 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4714 reusing = [[[PackageCell alloc] init] autorelease];
4715 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
4719 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
4723 - (void) tableRowSelected:(NSNotification *)notification {
4724 int row = [[notification object] selectedRow];
4728 Package *package = [packages_ objectAtIndex:row];
4729 package = [database_ packageWithName:[package id]];
4730 PackageView *view([delegate_ packageView]);
4731 [view setPackage:package];
4732 [view setDelegate:delegate_];
4733 [book_ pushPage:view];
4736 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
4737 if ((self = [super initWithBook:book]) != nil) {
4738 database_ = database;
4739 title_ = [title retain];
4741 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
4742 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
4744 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
4745 [list_ setDataSource:self];
4747 UITableColumn *column = [[[UITableColumn alloc]
4748 initWithTitle:CYLocalize("NAME")
4750 width:[self frame].size.width
4753 UITable *table = [list_ table];
4754 [table setSeparatorStyle:1];
4755 [table addTableColumn:column];
4756 [table setDelegate:self];
4757 [table setReusesTableCells:YES];
4759 [self addSubview:list_];
4761 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
4762 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
4766 - (void) setDelegate:(id)delegate {
4767 delegate_ = delegate;
4770 - (bool) hasPackage:(Package *)package {
4774 - (void) reloadData {
4775 NSArray *packages = [database_ packages];
4777 [packages_ removeAllObjects];
4778 [sections_ removeAllObjects];
4780 _profile(PackageTable$reloadData$Filter)
4781 for (Package *package in packages)
4782 if ([self hasPackage:package])
4783 [packages_ addObject:package];
4786 Section *section = nil;
4788 _profile(PackageTable$reloadData$Section)
4789 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
4793 _profile(PackageTable$reloadData$Section$Package)
4794 package = [packages_ objectAtIndex:offset];
4795 index = [package index];
4798 if (section == nil || [section index] != index) {
4799 _profile(PackageTable$reloadData$Section$Allocate)
4800 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
4803 _profile(PackageTable$reloadData$Section$Add)
4804 [sections_ addObject:section];
4808 [section addToCount];
4812 _profile(PackageTable$reloadData$List)
4817 - (NSString *) title {
4821 - (void) resetViewAnimated:(BOOL)animated {
4822 [list_ resetViewAnimated:animated];
4825 - (void) resetCursor {
4826 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
4829 - (UISectionList *) list {
4833 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
4834 [list_ setShouldHideHeaderInShortLists:hide];
4839 /* Filtered Package Table {{{ */
4840 @interface FilteredPackageTable : PackageTable {
4846 - (void) setObject:(id)object;
4848 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
4852 @implementation FilteredPackageTable
4860 - (void) setObject:(id)object {
4866 object_ = [object retain];
4869 - (bool) hasPackage:(Package *)package {
4870 _profile(FilteredPackageTable$hasPackage)
4871 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
4875 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
4876 if ((self = [super initWithBook:book database:database title:title]) != nil) {
4878 object_ = object == nil ? nil : [object retain];
4880 /* XXX: this is an unsafe optimization of doomy hell */
4881 Method method = class_getInstanceMethod([Package class], filter);
4882 imp_ = method_getImplementation(method);
4883 _assert(imp_ != NULL);
4892 /* Add Source View {{{ */
4893 @interface AddSourceView : RVPage {
4894 _transient Database *database_;
4897 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4901 @implementation AddSourceView
4903 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4904 if ((self = [super initWithBook:book]) != nil) {
4905 database_ = database;
4911 /* Source Cell {{{ */
4912 @interface SourceCell : UITableCell {
4915 NSString *description_;
4921 - (SourceCell *) initWithSource:(Source *)source;
4925 @implementation SourceCell
4930 [description_ release];
4935 - (SourceCell *) initWithSource:(Source *)source {
4936 if ((self = [super init]) != nil) {
4938 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
4940 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
4941 icon_ = [icon_ retain];
4943 origin_ = [[source name] retain];
4944 label_ = [[source uri] retain];
4945 description_ = [[source description] retain];
4949 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4951 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
4958 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4962 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4966 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4968 [super drawContentInRect:rect selected:selected];
4973 /* Source Table {{{ */
4974 @interface SourceTable : RVPage {
4975 _transient Database *database_;
4976 UISectionList *list_;
4977 NSMutableArray *sources_;
4978 UIActionSheet *alert_;
4982 UIProgressHUD *hud_;
4985 //NSURLConnection *installer_;
4986 NSURLConnection *trivial_bz2_;
4987 NSURLConnection *trivial_gz_;
4988 //NSURLConnection *automatic_;
4993 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4997 @implementation SourceTable
4999 - (void) _deallocConnection:(NSURLConnection *)connection {
5000 if (connection != nil) {
5001 [connection cancel];
5002 //[connection setDelegate:nil];
5003 [connection release];
5008 [[list_ table] setDelegate:nil];
5009 [list_ setDataSource:nil];
5018 //[self _deallocConnection:installer_];
5019 [self _deallocConnection:trivial_gz_];
5020 [self _deallocConnection:trivial_bz2_];
5021 //[self _deallocConnection:automatic_];
5028 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5029 return offset_ == 0 ? 1 : 2;
5032 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5033 switch (section + (offset_ == 0 ? 1 : 0)) {
5034 case 0: return CYLocalize("ENTERED_BY_USER");
5035 case 1: return CYLocalize("INSTALLED_BY_PACKAGE");
5043 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5044 switch (section + (offset_ == 0 ? 1 : 0)) {
5046 case 1: return offset_;
5054 - (int) numberOfRowsInTable:(UITable *)table {
5055 return [sources_ count];
5058 - (float) table:(UITable *)table heightForRow:(int)row {
5059 Source *source = [sources_ objectAtIndex:row];
5060 return [source description] == nil ? 56 : 73;
5063 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5064 Source *source = [sources_ objectAtIndex:row];
5065 // XXX: weird warning, stupid selectors ;P
5066 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5069 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5073 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5077 - (void) tableRowSelected:(NSNotification*)notification {
5078 UITable *table([list_ table]);
5079 int row([table selectedRow]);
5083 Source *source = [sources_ objectAtIndex:row];
5085 PackageTable *packages = [[[FilteredPackageTable alloc]
5088 title:[source label]
5089 filter:@selector(isVisibleInSource:)
5093 [packages setDelegate:delegate_];
5095 [book_ pushPage:packages];
5098 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5099 Source *source = [sources_ objectAtIndex:row];
5100 return [source record] != nil;
5103 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5104 [[list_ table] setDeleteConfirmationRow:row];
5107 - (void) table:(UITable *)table deleteRow:(int)row {
5108 Source *source = [sources_ objectAtIndex:row];
5109 [Sources_ removeObjectForKey:[source key]];
5110 [delegate_ syncData];
5114 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5117 @"./", @"Distribution",
5118 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5120 [delegate_ syncData];
5123 - (NSString *) getWarning {
5124 NSString *href(href_);
5125 NSRange colon([href rangeOfString:@"://"]);
5126 if (colon.location != NSNotFound)
5127 href = [href substringFromIndex:(colon.location + 3)];
5128 href = [href stringByAddingPercentEscapes];
5129 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5130 href = [href stringByCachingURLWithCurrentCDN];
5132 NSURL *url([NSURL URLWithString:href]);
5134 NSStringEncoding encoding;
5135 NSError *error(nil);
5137 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5138 return [warning length] == 0 ? nil : warning;
5142 - (void) _endConnection:(NSURLConnection *)connection {
5143 NSURLConnection **field = NULL;
5144 if (connection == trivial_bz2_)
5145 field = &trivial_bz2_;
5146 else if (connection == trivial_gz_)
5147 field = &trivial_gz_;
5148 _assert(field != NULL);
5149 [connection release];
5153 trivial_bz2_ == nil &&
5159 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5162 UIActionSheet *sheet = [[[UIActionSheet alloc]
5163 initWithTitle:CYLocalize("SOURCE_WARNING")
5164 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_ANYWAY"), CYLocalize("CANCEL"), nil]
5165 defaultButtonIndex:0
5170 [sheet setNumberOfRows:1];
5172 [sheet setBodyText:warning];
5173 [sheet popupAlertAnimated:YES];
5176 } else if (error_ != nil) {
5177 UIActionSheet *sheet = [[[UIActionSheet alloc]
5178 initWithTitle:CYLocalize("VERIFICATION_ERROR")
5179 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5180 defaultButtonIndex:0
5185 [sheet setBodyText:[error_ localizedDescription]];
5186 [sheet popupAlertAnimated:YES];
5188 UIActionSheet *sheet = [[[UIActionSheet alloc]
5189 initWithTitle:CYLocalize("NOT_REPOSITORY")
5190 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5191 defaultButtonIndex:0
5196 [sheet setBodyText:CYLocalize("NOT_REPOSITORY_EX")];
5197 [sheet popupAlertAnimated:YES];
5200 [delegate_ setStatusBarShowsProgress:NO];
5201 [delegate_ removeProgressHUD:hud_];
5211 if (error_ != nil) {
5218 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5219 switch ([response statusCode]) {
5225 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5226 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5228 error_ = [error retain];
5229 [self _endConnection:connection];
5232 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5233 [self _endConnection:connection];
5236 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5237 NSMutableURLRequest *request = [NSMutableURLRequest
5238 requestWithURL:[NSURL URLWithString:href]
5239 cachePolicy:NSURLRequestUseProtocolCachePolicy
5240 timeoutInterval:20.0
5243 [request setHTTPMethod:method];
5245 if (Machine_ != NULL)
5246 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5247 if (UniqueID_ != nil)
5248 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5251 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5253 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5256 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5257 NSString *context([sheet context]);
5259 if ([context isEqualToString:@"source"]) {
5262 NSString *href = [[sheet textField] text];
5264 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5266 if (![href hasSuffix:@"/"])
5267 href_ = [href stringByAppendingString:@"/"];
5270 href_ = [href_ retain];
5272 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5273 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5274 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5278 hud_ = [[delegate_ addProgressHUD] retain];
5279 [hud_ setText:CYLocalize("VERIFYING_URL")];
5290 } else if ([context isEqualToString:@"trivial"])
5292 else if ([context isEqualToString:@"urlerror"])
5294 else if ([context isEqualToString:@"warning"]) {
5314 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5315 if ((self = [super initWithBook:book]) != nil) {
5316 database_ = database;
5317 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5319 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5320 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5321 [list_ setShouldHideHeaderInShortLists:NO];
5323 [self addSubview:list_];
5324 [list_ setDataSource:self];
5326 UITableColumn *column = [[UITableColumn alloc]
5327 initWithTitle:CYLocalize("NAME")
5329 width:[self frame].size.width
5332 UITable *table = [list_ table];
5333 [table setSeparatorStyle:1];
5334 [table addTableColumn:column];
5335 [table setDelegate:self];
5339 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5340 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5344 - (void) reloadData {
5346 _assert(list.ReadMainList());
5348 [sources_ removeAllObjects];
5349 [sources_ addObjectsFromArray:[database_ sources]];
5351 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5354 int count = [sources_ count];
5355 for (offset_ = 0; offset_ != count; ++offset_) {
5356 Source *source = [sources_ objectAtIndex:offset_];
5357 if ([source record] == nil)
5364 - (void) resetViewAnimated:(BOOL)animated {
5365 [list_ resetViewAnimated:animated];
5368 - (void) _leftButtonClicked {
5369 /*[book_ pushPage:[[[AddSourceView alloc]
5374 UIActionSheet *sheet = [[[UIActionSheet alloc]
5375 initWithTitle:CYLocalize("ENTER_APT_URL")
5376 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_SOURCE"), CYLocalize("CANCEL"), nil]
5377 defaultButtonIndex:0
5382 [sheet setNumberOfRows:1];
5384 [sheet addTextFieldWithValue:@"http://" label:@""];
5386 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5387 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5388 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5389 [traits setKeyboardType:UIKeyboardTypeURL];
5390 // XXX: UIReturnKeyDone
5391 [traits setReturnKeyType:UIReturnKeyNext];
5393 [sheet popupAlertAnimated:YES];
5396 - (void) _rightButtonClicked {
5397 UITable *table = [list_ table];
5398 BOOL editing = [table isRowDeletionEnabled];
5399 [table enableRowDeletion:!editing animated:YES];
5400 [book_ reloadButtonsForPage:self];
5403 - (NSString *) title {
5404 return CYLocalize("SOURCES");
5407 - (NSString *) leftButtonTitle {
5408 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("ADD") : nil;
5411 - (id) rightButtonTitle {
5412 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("DONE") : CYLocalize("EDIT");
5415 - (UINavigationButtonStyle) rightButtonStyle {
5416 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5422 /* Installed View {{{ */
5423 @interface InstalledView : RVPage {
5424 _transient Database *database_;
5425 FilteredPackageTable *packages_;
5429 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5433 @implementation InstalledView
5436 [packages_ release];
5440 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5441 if ((self = [super initWithBook:book]) != nil) {
5442 database_ = database;
5444 packages_ = [[FilteredPackageTable alloc]
5448 filter:@selector(isInstalledAndVisible:)
5449 with:[NSNumber numberWithBool:YES]
5452 [self addSubview:packages_];
5454 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5455 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5459 - (void) resetViewAnimated:(BOOL)animated {
5460 [packages_ resetViewAnimated:animated];
5463 - (void) reloadData {
5464 [packages_ reloadData];
5467 - (void) _rightButtonClicked {
5468 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5469 [packages_ reloadData];
5471 [book_ reloadButtonsForPage:self];
5474 - (NSString *) title {
5475 return CYLocalize("INSTALLED");
5478 - (NSString *) backButtonTitle {
5479 return CYLocalize("PACKAGES");
5482 - (id) rightButtonTitle {
5483 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? CYLocalize("EXPERT") : CYLocalize("SIMPLE");
5486 - (UINavigationButtonStyle) rightButtonStyle {
5487 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5490 - (void) setDelegate:(id)delegate {
5491 [super setDelegate:delegate];
5492 [packages_ setDelegate:delegate];
5499 @interface HomeView : BrowserView {
5504 @implementation HomeView
5506 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5507 NSString *context([sheet context]);
5509 if ([context isEqualToString:@"about"])
5512 [super alertSheet:sheet buttonClicked:button];
5515 - (void) _leftButtonClicked {
5516 UIActionSheet *sheet = [[[UIActionSheet alloc]
5517 initWithTitle:CYLocalize("ABOUT_CYDIA")
5518 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
5519 defaultButtonIndex:0
5525 @"Copyright (C) 2008-2009\n"
5526 "Jay Freeman (saurik)\n"
5527 "saurik@saurik.com\n"
5528 "http://www.saurik.com/\n"
5531 "http://www.theokorigroup.com/\n"
5533 "College of Creative Studies,\n"
5534 "University of California,\n"
5536 "http://www.ccs.ucsb.edu/"
5539 [sheet popupAlertAnimated:YES];
5542 - (NSString *) leftButtonTitle {
5543 return CYLocalize("ABOUT");
5548 /* Manage View {{{ */
5549 @interface ManageView : BrowserView {
5554 @implementation ManageView
5556 - (NSString *) title {
5557 return CYLocalize("MANAGE");
5560 - (void) _leftButtonClicked {
5561 [delegate_ askForSettings];
5564 - (NSString *) leftButtonTitle {
5565 return CYLocalize("SETTINGS");
5569 - (id) _rightButtonTitle {
5570 return Queuing_ ? CYLocalize("QUEUE") : nil;
5573 - (UINavigationButtonStyle) rightButtonStyle {
5574 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5577 - (void) _rightButtonClicked {
5582 - (bool) isLoading {
5589 #include <BrowserView.m>
5591 /* Cydia Book {{{ */
5592 @interface CYBook : RVBook <
5595 _transient Database *database_;
5596 UINavigationBar *overlay_;
5597 UINavigationBar *underlay_;
5598 UIProgressIndicator *indicator_;
5599 UITextLabel *prompt_;
5600 UIProgressBar *progress_;
5601 UINavigationButton *cancel_;
5605 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
5611 @implementation CYBook
5615 [indicator_ release];
5617 [progress_ release];
5622 - (NSString *) getTitleForPage:(RVPage *)page {
5623 return [super getTitleForPage:page];
5631 [UIView beginAnimations:nil context:NULL];
5633 CGRect ovrframe = [overlay_ frame];
5634 ovrframe.origin.y = 0;
5635 [overlay_ setFrame:ovrframe];
5637 CGRect barframe = [navbar_ frame];
5638 barframe.origin.y += ovrframe.size.height;
5639 [navbar_ setFrame:barframe];
5641 CGRect trnframe = [transition_ frame];
5642 trnframe.origin.y += ovrframe.size.height;
5643 trnframe.size.height -= ovrframe.size.height;
5644 [transition_ setFrame:trnframe];
5646 [UIView endAnimations];
5648 [indicator_ startAnimation];
5649 [prompt_ setText:CYLocalize("UPDATING_DATABASE")];
5650 [progress_ setProgress:0];
5653 [overlay_ addSubview:cancel_];
5656 detachNewThreadSelector:@selector(_update)
5665 [indicator_ stopAnimation];
5667 [UIView beginAnimations:nil context:NULL];
5669 CGRect ovrframe = [overlay_ frame];
5670 ovrframe.origin.y = -ovrframe.size.height;
5671 [overlay_ setFrame:ovrframe];
5673 CGRect barframe = [navbar_ frame];
5674 barframe.origin.y -= ovrframe.size.height;
5675 [navbar_ setFrame:barframe];
5677 CGRect trnframe = [transition_ frame];
5678 trnframe.origin.y -= ovrframe.size.height;
5679 trnframe.size.height += ovrframe.size.height;
5680 [transition_ setFrame:trnframe];
5682 [UIView commitAnimations];
5684 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
5687 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
5688 if ((self = [super initWithFrame:frame]) != nil) {
5689 database_ = database;
5691 CGRect ovrrect = [navbar_ bounds];
5692 ovrrect.size.height = [UINavigationBar defaultSize].height;
5693 ovrrect.origin.y = -ovrrect.size.height;
5695 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5696 [self addSubview:overlay_];
5698 ovrrect.origin.y = frame.size.height;
5699 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5700 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
5701 [self addSubview:underlay_];
5703 [overlay_ setBarStyle:1];
5704 [underlay_ setBarStyle:1];
5706 int barstyle = [overlay_ _barStyle:NO];
5707 bool ugly = barstyle == 0;
5709 UIProgressIndicatorStyle style = ugly ?
5710 UIProgressIndicatorStyleMediumBrown :
5711 UIProgressIndicatorStyleMediumWhite;
5713 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
5714 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
5715 CGRect indrect = {{indoffset, indoffset}, indsize};
5717 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
5718 [indicator_ setStyle:style];
5719 [overlay_ addSubview:indicator_];
5721 CGSize prmsize = {215, indsize.height + 4};
5724 indoffset * 2 + indsize.width,
5728 unsigned(ovrrect.size.height - prmsize.height) / 2
5731 UIFont *font = [UIFont systemFontOfSize:15];
5733 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
5735 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
5736 [prompt_ setBackgroundColor:[UIColor clearColor]];
5737 [prompt_ setFont:font];
5739 [overlay_ addSubview:prompt_];
5741 CGSize prgsize = {75, 100};
5744 ovrrect.size.width - prgsize.width - 10,
5745 (ovrrect.size.height - prgsize.height) / 2
5748 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
5749 [progress_ setStyle:0];
5750 [overlay_ addSubview:progress_];
5752 cancel_ = [[UINavigationButton alloc] initWithTitle:CYLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
5753 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
5755 CGRect frame = [cancel_ frame];
5756 frame.size.width = 65;
5757 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
5758 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
5759 [cancel_ setFrame:frame];
5761 [cancel_ setBarStyle:barstyle];
5765 - (void) _onCancel {
5767 [cancel_ removeFromSuperview];
5770 - (void) _update { _pooled
5772 status.setDelegate(self);
5774 [database_ updateWithStatus:status];
5777 performSelectorOnMainThread:@selector(_update_)
5783 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
5784 [prompt_ setText:[NSString stringWithFormat:CYLocalize("ERROR_MESSAGE"), error]];
5787 - (void) setProgressTitle:(NSString *)title {
5789 performSelectorOnMainThread:@selector(_setProgressTitle:)
5795 - (void) setProgressPercent:(float)percent {
5797 performSelectorOnMainThread:@selector(_setProgressPercent:)
5798 withObject:[NSNumber numberWithFloat:percent]
5803 - (void) startProgress {
5806 - (void) addProgressOutput:(NSString *)output {
5808 performSelectorOnMainThread:@selector(_addProgressOutput:)
5814 - (bool) isCancelling:(size_t)received {
5818 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5822 - (void) _setProgressTitle:(NSString *)title {
5823 [prompt_ setText:title];
5826 - (void) _setProgressPercent:(NSNumber *)percent {
5827 [progress_ setProgress:[percent floatValue]];
5830 - (void) _addProgressOutput:(NSString *)output {
5835 /* Cydia:// Protocol {{{ */
5836 @interface CydiaURLProtocol : NSURLProtocol {
5841 @implementation CydiaURLProtocol
5843 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
5844 NSURL *url([request URL]);
5847 NSString *scheme([[url scheme] lowercaseString]);
5848 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
5853 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
5857 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
5858 id<NSURLProtocolClient> client([self client]);
5860 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
5862 NSData *data(UIImagePNGRepresentation(icon));
5864 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
5865 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
5866 [client URLProtocol:self didLoadData:data];
5867 [client URLProtocolDidFinishLoading:self];
5871 - (void) startLoading {
5872 id<NSURLProtocolClient> client([self client]);
5873 NSURLRequest *request([self request]);
5875 NSURL *url([request URL]);
5876 NSString *href([url absoluteString]);
5878 NSString *path([href substringFromIndex:8]);
5879 NSRange slash([path rangeOfString:@"/"]);
5882 if (slash.location == NSNotFound) {
5886 command = [path substringToIndex:slash.location];
5887 path = [path substringFromIndex:(slash.location + 1)];
5890 Database *database([Database sharedInstance]);
5892 if ([command isEqualToString:@"package-icon"]) {
5895 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5896 Package *package([database packageWithName:path]);
5899 UIImage *icon([package icon]);
5900 [self _returnPNGWithImage:icon forRequest:request];
5901 } else if ([command isEqualToString:@"source-icon"]) {
5904 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5905 NSString *source(Simplify(path));
5906 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
5908 icon = [UIImage applicationImageNamed:@"unknown.png"];
5909 [self _returnPNGWithImage:icon forRequest:request];
5910 } else if ([command isEqualToString:@"uikit-image"]) {
5913 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5914 UIImage *icon(_UIImageWithName(path));
5915 [self _returnPNGWithImage:icon forRequest:request];
5916 } else if ([command isEqualToString:@"section-icon"]) {
5919 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5920 NSString *section(Simplify(path));
5921 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
5923 icon = [UIImage applicationImageNamed:@"unknown.png"];
5924 [self _returnPNGWithImage:icon forRequest:request];
5926 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
5930 - (void) stopLoading {
5936 /* Sections View {{{ */
5937 @interface SectionsView : RVPage {
5938 _transient Database *database_;
5939 NSMutableArray *sections_;
5940 NSMutableArray *filtered_;
5941 UITransitionView *transition_;
5947 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5948 - (void) reloadData;
5953 @implementation SectionsView
5956 [list_ setDataSource:nil];
5957 [list_ setDelegate:nil];
5959 [sections_ release];
5960 [filtered_ release];
5961 [transition_ release];
5963 [accessory_ release];
5967 - (int) numberOfRowsInTable:(UITable *)table {
5968 return editing_ ? [sections_ count] : [filtered_ count] + 1;
5971 - (float) table:(UITable *)table heightForRow:(int)row {
5975 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
5977 reusing = [[[SectionCell alloc] init] autorelease];
5978 [(SectionCell *)reusing setSection:(editing_ ?
5979 [sections_ objectAtIndex:row] :
5980 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
5981 ) editing:editing_];
5985 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5989 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5993 - (void) tableRowSelected:(NSNotification *)notification {
5994 int row = [[notification object] selectedRow];
6005 title = CYLocalize("ALL_PACKAGES");
6007 section = [filtered_ objectAtIndex:(row - 1)];
6008 name = [section name];
6011 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6014 title = CYLocalize("NO_SECTION");
6018 PackageTable *table = [[[FilteredPackageTable alloc]
6022 filter:@selector(isVisiblyUninstalledInSection:)
6026 [table setDelegate:delegate_];
6028 [book_ pushPage:table];
6031 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6032 if ((self = [super initWithBook:book]) != nil) {
6033 database_ = database;
6035 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6036 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6038 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6039 [self addSubview:transition_];
6041 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6042 [transition_ transition:0 toView:list_];
6044 UITableColumn *column = [[[UITableColumn alloc]
6045 initWithTitle:CYLocalize("NAME")
6047 width:[self frame].size.width
6050 [list_ setDataSource:self];
6051 [list_ setSeparatorStyle:1];
6052 [list_ addTableColumn:column];
6053 [list_ setDelegate:self];
6054 [list_ setReusesTableCells:YES];
6058 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6059 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6063 - (void) reloadData {
6064 NSArray *packages = [database_ packages];
6066 [sections_ removeAllObjects];
6067 [filtered_ removeAllObjects];
6070 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6071 SectionMap sections;
6072 sections.resize(64);
6074 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6078 for (Package *package in packages) {
6079 NSString *name([package section]);
6080 NSString *key(name == nil ? @"" : name);
6085 _profile(SectionsView$reloadData$Section)
6086 section = §ions[key];
6087 if (*section == nil) {
6088 _profile(SectionsView$reloadData$Section$Allocate)
6089 *section = [[[Section alloc] initWithName:name] autorelease];
6094 [*section addToCount];
6096 _profile(SectionsView$reloadData$Filter)
6097 if (![package valid] || [package installed] != nil || ![package visible])
6101 [*section addToRow];
6105 _profile(SectionsView$reloadData$Section)
6106 section = [sections objectForKey:key];
6107 if (section == nil) {
6108 _profile(SectionsView$reloadData$Section$Allocate)
6109 section = [[[Section alloc] initWithName:name] autorelease];
6110 [sections setObject:section forKey:key];
6115 [section addToCount];
6117 _profile(SectionsView$reloadData$Filter)
6118 if (![package valid] || [package installed] != nil || ![package visible])
6128 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6129 [sections_ addObject:i->second];
6131 [sections_ addObjectsFromArray:[sections allValues]];
6134 [sections_ sortUsingSelector:@selector(compareByName:)];
6136 for (Section *section in sections_) {
6137 size_t count([section row]);
6138 if ([section row] == 0)
6141 section = [[[Section alloc] initWithName:[section name]] autorelease];
6142 [section setCount:count];
6143 [filtered_ addObject:section];
6150 - (void) resetView {
6152 [self _rightButtonClicked];
6155 - (void) resetViewAnimated:(BOOL)animated {
6156 [list_ resetViewAnimated:animated];
6159 - (void) _rightButtonClicked {
6160 if ((editing_ = !editing_))
6163 [delegate_ updateData];
6164 [book_ reloadTitleForPage:self];
6165 [book_ reloadButtonsForPage:self];
6168 - (NSString *) title {
6169 return editing_ ? CYLocalize("SECTION_VISIBILITY") : CYLocalize("INSTALL_BY_SECTION");
6172 - (NSString *) backButtonTitle {
6173 return CYLocalize("SECTIONS");
6176 - (id) rightButtonTitle {
6177 return [sections_ count] == 0 ? nil : editing_ ? CYLocalize("DONE") : CYLocalize("EDIT");
6180 - (UINavigationButtonStyle) rightButtonStyle {
6181 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6184 - (UIView *) accessoryView {
6190 /* Changes View {{{ */
6191 @interface ChangesView : RVPage {
6192 _transient Database *database_;
6193 NSMutableArray *packages_;
6194 NSMutableArray *sections_;
6195 UISectionList *list_;
6199 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6200 - (void) reloadData;
6204 @implementation ChangesView
6207 [[list_ table] setDelegate:nil];
6208 [list_ setDataSource:nil];
6210 [packages_ release];
6211 [sections_ release];
6216 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6217 return [sections_ count];
6220 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6221 NSLog(@"titleForSection:%u", section);
6222 return [[sections_ objectAtIndex:section] name];
6225 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6226 return [[sections_ objectAtIndex:section] row];
6229 - (int) numberOfRowsInTable:(UITable *)table {
6230 return [packages_ count];
6233 - (float) table:(UITable *)table heightForRow:(int)row {
6234 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6237 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6239 reusing = [[[PackageCell alloc] init] autorelease];
6240 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6244 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6248 - (void) tableRowSelected:(NSNotification *)notification {
6249 int row = [[notification object] selectedRow];
6252 Package *package = [packages_ objectAtIndex:row];
6253 PackageView *view([delegate_ packageView]);
6254 [view setDelegate:delegate_];
6255 [view setPackage:package];
6256 [book_ pushPage:view];
6259 - (void) _leftButtonClicked {
6260 [(CYBook *)book_ update];
6261 [self reloadButtons];
6264 - (void) _rightButtonClicked {
6265 [delegate_ distUpgrade];
6268 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6269 if ((self = [super initWithBook:book]) != nil) {
6270 database_ = database;
6272 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6273 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6275 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6276 [self addSubview:list_];
6278 [list_ setShouldHideHeaderInShortLists:NO];
6279 [list_ setDataSource:self];
6280 //[list_ setSectionListStyle:1];
6282 UITableColumn *column = [[[UITableColumn alloc]
6283 initWithTitle:CYLocalize("NAME")
6285 width:[self frame].size.width
6288 UITable *table = [list_ table];
6289 [table setSeparatorStyle:1];
6290 [table addTableColumn:column];
6291 [table setDelegate:self];
6292 [table setReusesTableCells:YES];
6296 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6297 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6301 - (void) reloadData {
6302 NSArray *packages = [database_ packages];
6304 [packages_ removeAllObjects];
6305 [sections_ removeAllObjects];
6308 for (Package *package in packages)
6310 [package installed] == nil && [package valid] && [package visible] ||
6311 [package upgradableAndEssential:YES]
6313 [packages_ addObject:package];
6316 [packages_ radixSortUsingFunction:reinterpret_cast<uint32_t (*)(id, void *)>(&PackageChangesRadix) withArgument:NULL];
6319 Section *upgradable = [[[Section alloc] initWithName:CYLocalize("AVAILABLE_UPGRADES")] autorelease];
6320 Section *ignored = [[[Section alloc] initWithName:CYLocalize("IGNORED_UPGRADES")] autorelease];
6321 Section *section = nil;
6325 bool unseens = false;
6327 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
6330 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6331 Package *package = [packages_ objectAtIndex:offset];
6334 _profile(ChangesView$reloadData$Upgrade)
6335 uae = [package upgradableAndEssential:YES];
6342 _profile(ChangesView$reloadData$Remember)
6343 seen = [package seen];
6347 _profile(ChangesView$reloadData$Compare)
6348 different = section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame);
6356 name = CYLocalize("UNKNOWN");
6358 _profile(ChangesView$reloadData$Format)
6359 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6365 _profile(ChangesView$reloadData$Allocate)
6366 name = [NSString stringWithFormat:CYLocalize("NEW_AT"), name];
6367 section = [[[Section alloc] initWithName:name row:offset] autorelease];
6368 [sections_ addObject:section];
6372 [section addToCount];
6373 } else if ([package ignored])
6374 [ignored addToCount];
6377 [upgradable addToCount];
6382 CFRelease(formatter);
6385 Section *last = [sections_ lastObject];
6386 size_t count = [last count];
6387 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6388 [sections_ removeLastObject];
6391 if ([ignored count] != 0)
6392 [sections_ insertObject:ignored atIndex:0];
6394 [sections_ insertObject:upgradable atIndex:0];
6397 [self reloadButtons];
6400 - (void) resetViewAnimated:(BOOL)animated {
6401 [list_ resetViewAnimated:animated];
6404 - (NSString *) leftButtonTitle {
6405 return [(CYBook *)book_ updating] ? nil : CYLocalize("REFRESH");
6408 - (id) rightButtonTitle {
6409 return upgrades_ == 0 ? nil : [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6412 - (NSString *) title {
6413 return CYLocalize("CHANGES");
6418 /* Search View {{{ */
6419 @protocol SearchViewDelegate
6420 - (void) showKeyboard:(BOOL)show;
6423 @interface SearchView : RVPage {
6425 UISearchField *field_;
6426 UITransitionView *transition_;
6427 FilteredPackageTable *table_;
6428 UIPreferencesTable *advanced_;
6434 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6435 - (void) reloadData;
6439 @implementation SearchView
6442 [field_ setDelegate:nil];
6444 [accessory_ release];
6446 [transition_ release];
6448 [advanced_ release];
6453 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6457 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6459 case 0: return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("ADVANCED_SEARCH"), CYLocalize("COMING_SOON")];
6461 default: _assert(false);
6465 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6469 default: _assert(false);
6473 - (void) _showKeyboard:(BOOL)show {
6474 CGSize keysize = [UIKeyboard defaultSize];
6475 CGRect keydown = [book_ pageBounds];
6476 CGRect keyup = keydown;
6477 keyup.size.height -= keysize.height - ButtonBarHeight_;
6479 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6481 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6482 [animation setSignificantRectFields:8];
6485 [animation setStartFrame:keydown];
6486 [animation setEndFrame:keyup];
6488 [animation setStartFrame:keyup];
6489 [animation setEndFrame:keydown];
6492 UIAnimator *animator = [UIAnimator sharedAnimator];
6495 addAnimations:[NSArray arrayWithObjects:animation, nil]
6496 withDuration:(KeyboardTime_ - delay)
6501 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6503 [delegate_ showKeyboard:show];
6506 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6507 [self _showKeyboard:YES];
6510 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
6511 [self _showKeyboard:NO];
6514 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
6516 NSString *text([field_ text]);
6517 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6523 - (void) textFieldClearButtonPressed:(UITextField *)field {
6527 - (void) keyboardInputShouldDelete:(id)input {
6531 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
6532 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6536 [field_ resignFirstResponder];
6541 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6542 if ((self = [super initWithBook:book]) != nil) {
6543 CGRect pageBounds = [book_ pageBounds];
6545 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6546 [self addSubview:transition_];
6548 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6550 [advanced_ setReusesTableCells:YES];
6551 [advanced_ setDataSource:self];
6552 [advanced_ reloadData];
6554 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6555 CGColor dimmed(space_, 0, 0, 0, 0.5);
6556 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
6558 table_ = [[FilteredPackageTable alloc]
6562 filter:@selector(isUnfilteredAndSearchedForBy:)
6566 [table_ setShouldHideHeaderInShortLists:NO];
6567 [transition_ transition:0 toView:table_];
6576 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
6583 [self bounds].size.width - area.origin.x - 18;
6585 area.size.height = [UISearchField defaultHeight];
6587 field_ = [[UISearchField alloc] initWithFrame:area];
6589 UIFont *font = [UIFont systemFontOfSize:16];
6590 [field_ setFont:font];
6592 [field_ setPlaceholder:CYLocalize("SEARCH_EX")];
6593 [field_ setDelegate:self];
6595 [field_ setPaddingTop:5];
6597 UITextInputTraits *traits([field_ textInputTraits]);
6598 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6599 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6600 [traits setReturnKeyType:UIReturnKeySearch];
6602 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
6604 accessory_ = [[UIView alloc] initWithFrame:accrect];
6605 [accessory_ addSubview:field_];
6607 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
6608 [configure setShowPressFeedback:YES];
6609 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
6610 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
6611 [accessory_ addSubview:configure];*/
6613 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6614 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6620 LKAnimation *animation = [LKTransition animation];
6621 [animation setType:@"oglFlip"];
6622 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
6623 [animation setFillMode:@"extended"];
6624 [animation setTransitionFlags:3];
6625 [animation setDuration:10];
6626 [animation setSpeed:0.35];
6627 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
6628 [[transition_ _layer] addAnimation:animation forKey:0];
6629 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
6630 flipped_ = !flipped_;
6634 - (void) configurePushed {
6635 [field_ resignFirstResponder];
6639 - (void) resetViewAnimated:(BOOL)animated {
6642 [table_ resetViewAnimated:animated];
6645 - (void) _reloadData {
6648 - (void) reloadData {
6651 [table_ setObject:[field_ text]];
6652 _profile(SearchView$reloadData)
6653 [table_ reloadData];
6656 [table_ resetCursor];
6659 - (UIView *) accessoryView {
6663 - (NSString *) title {
6667 - (NSString *) backButtonTitle {
6668 return CYLocalize("SEARCH");
6671 - (void) setDelegate:(id)delegate {
6672 [table_ setDelegate:delegate];
6673 [super setDelegate:delegate];
6679 @interface SettingsView : RVPage {
6680 _transient Database *database_;
6683 UIPreferencesTable *table_;
6684 _UISwitchSlider *subscribedSwitch_;
6685 _UISwitchSlider *ignoredSwitch_;
6686 UIPreferencesControlTableCell *subscribedCell_;
6687 UIPreferencesControlTableCell *ignoredCell_;
6690 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6694 @implementation SettingsView
6697 [table_ setDataSource:nil];
6700 if (package_ != nil)
6703 [subscribedSwitch_ release];
6704 [ignoredSwitch_ release];
6705 [subscribedCell_ release];
6706 [ignoredCell_ release];
6710 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6711 if (package_ == nil)
6717 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6718 if (package_ == nil)
6725 default: _assert(false);
6731 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
6732 if (package_ == nil)
6739 default: _assert(false);
6745 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6746 if (package_ == nil)
6753 default: _assert(false);
6759 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
6760 if (package_ == nil)
6763 _UISwitchSlider *slider([cell control]);
6764 BOOL value([slider value] != 0);
6765 NSMutableDictionary *metadata([package_ metadata]);
6768 if (NSNumber *number = [metadata objectForKey:key])
6769 before = [number boolValue];
6773 if (value != before) {
6774 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
6776 [delegate_ updateData];
6780 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
6781 [self onSomething:cell withKey:@"IsSubscribed"];
6784 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
6785 [self onSomething:cell withKey:@"IsIgnored"];
6788 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
6789 if (package_ == nil)
6793 case 0: switch (row) {
6795 return subscribedCell_;
6797 return ignoredCell_;
6798 default: _assert(false);
6801 case 1: switch (row) {
6803 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
6804 [cell setShowSelection:NO];
6805 [cell setTitle:CYLocalize("SHOW_ALL_CHANGES_EX")];
6809 default: _assert(false);
6812 default: _assert(false);
6818 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
6819 if ((self = [super initWithBook:book])) {
6820 database_ = database;
6821 name_ = [package retain];
6823 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
6824 [self addSubview:table_];
6826 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
6827 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
6829 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
6830 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
6832 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
6833 [subscribedCell_ setShowSelection:NO];
6834 [subscribedCell_ setTitle:CYLocalize("SHOW_ALL_CHANGES")];
6835 [subscribedCell_ setControl:subscribedSwitch_];
6837 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
6838 [ignoredCell_ setShowSelection:NO];
6839 [ignoredCell_ setTitle:CYLocalize("IGNORE_UPGRADES")];
6840 [ignoredCell_ setControl:ignoredSwitch_];
6842 [table_ setDataSource:self];
6847 - (void) resetViewAnimated:(BOOL)animated {
6848 [table_ resetViewAnimated:animated];
6851 - (void) reloadData {
6852 if (package_ != nil)
6853 [package_ autorelease];
6854 package_ = [database_ packageWithName:name_];
6855 if (package_ != nil) {
6857 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
6858 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
6861 [table_ reloadData];
6864 - (NSString *) title {
6865 return CYLocalize("SETTINGS");
6870 /* Signature View {{{ */
6871 @interface SignatureView : BrowserView {
6872 _transient Database *database_;
6876 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6880 @implementation SignatureView
6887 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
6889 [super webView:sender didClearWindowObject:window forFrame:frame];
6892 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
6893 if ((self = [super initWithBook:book]) != nil) {
6894 database_ = database;
6895 package_ = [package retain];
6900 - (void) resetViewAnimated:(BOOL)animated {
6903 - (void) reloadData {
6904 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
6910 @interface Cydia : UIApplication <
6911 ConfirmationViewDelegate,
6912 ProgressViewDelegate,
6921 UIToolbar *buttonbar_;
6925 NSMutableArray *essential_;
6926 NSMutableArray *broken_;
6928 Database *database_;
6929 ProgressView *progress_;
6933 UIKeyboard *keyboard_;
6934 UIProgressHUD *hud_;
6936 SectionsView *sections_;
6937 ChangesView *changes_;
6938 ManageView *manage_;
6939 SearchView *search_;
6941 PackageView *package_;
6946 @implementation Cydia
6949 if ([broken_ count] != 0) {
6950 int count = [broken_ count];
6952 UIActionSheet *sheet = [[[UIActionSheet alloc]
6953 initWithTitle:(count == 1 ? CYLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:CYLocalize("HALFINSTALLED_PACKAGES"), count])
6954 buttons:[NSArray arrayWithObjects:
6955 CYLocalize("FORCIBLY_CLEAR"),
6956 CYLocalize("TEMPORARY_IGNORE"),
6958 defaultButtonIndex:0
6963 [sheet setBodyText:CYLocalize("HALFINSTALLED_PACKAGE_EX")];
6964 [sheet popupAlertAnimated:YES];
6965 } else if (!Ignored_ && [essential_ count] != 0) {
6966 int count = [essential_ count];
6968 UIActionSheet *sheet = [[[UIActionSheet alloc]
6969 initWithTitle:(count == 1 ? CYLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:CYLocalize("ESSENTIAL_UPGRADES"), count])
6970 buttons:[NSArray arrayWithObjects:
6971 CYLocalize("UPGRADE_ESSENTIAL"),
6972 CYLocalize("COMPLETE_UPGRADE"),
6973 CYLocalize("TEMPORARY_IGNORE"),
6975 defaultButtonIndex:0
6980 [sheet setBodyText:CYLocalize("ESSENTIAL_UPGRADE_EX")];
6981 [sheet popupAlertAnimated:YES];
6985 - (void) _reloadData {
6988 static bool loaded(false);
6989 UIProgressHUD *hud([self addProgressHUD]);
6990 [hud setText:(loaded ? CYLocalize("RELOADING_DATA") : CYLocalize("LOADING_DATA"))];
6993 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
6996 [self removeProgressHUD:hud];
7000 [essential_ removeAllObjects];
7001 [broken_ removeAllObjects];
7003 NSArray *packages = [database_ packages];
7004 for (Package *package in packages) {
7006 [broken_ addObject:package];
7007 if ([package upgradableAndEssential:NO]) {
7008 if ([package essential])
7009 [essential_ addObject:package];
7015 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7016 [buttonbar_ setBadgeValue:badge forButton:3];
7017 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7018 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7019 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7020 [self setApplicationBadge:badge];
7022 [self setApplicationBadgeString:badge];
7024 [buttonbar_ setBadgeValue:nil forButton:3];
7025 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7026 [buttonbar_ setBadgeAnimated:NO forButton:3];
7027 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7028 [self removeApplicationBadge];
7029 else // XXX: maybe use setApplicationBadgeString also?
7030 [self setApplicationIconBadgeNumber:0];
7034 [buttonbar_ setBadgeValue:nil forButton:4];
7038 // XXX: what is this line of code for?
7039 if ([packages count] == 0);
7040 else if (Loaded_ || ManualRefresh) loaded:
7045 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7046 NSTimeInterval interval([update timeIntervalSinceNow]);
7047 if (interval <= 0 && interval > -600)
7055 - (void) _saveConfig {
7058 NSString *error(nil);
7059 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7061 NSError *error(nil);
7062 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7063 NSLog(@"failure to save metadata data: %@", error);
7066 NSLog(@"failure to serialize metadata: %@", error);
7074 - (void) updateData {
7077 /* XXX: this is just stupid */
7078 if (tag_ != 2 && sections_ != nil)
7079 [sections_ reloadData];
7080 if (tag_ != 3 && changes_ != nil)
7081 [changes_ reloadData];
7082 if (tag_ != 5 && search_ != nil)
7083 [search_ reloadData];
7093 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7094 _assert(file != NULL);
7096 NSArray *keys = [Sources_ allKeys];
7098 for (NSString *key in keys) {
7099 NSDictionary *source = [Sources_ objectForKey:key];
7101 fprintf(file, "%s %s %s\n",
7102 [[source objectForKey:@"Type"] UTF8String],
7103 [[source objectForKey:@"URI"] UTF8String],
7104 [[source objectForKey:@"Distribution"] UTF8String]
7113 detachNewThreadSelector:@selector(update_)
7116 title:CYLocalize("UPDATING_SOURCES")
7120 - (void) reloadData {
7121 @synchronized (self) {
7122 if (confirm_ == nil)
7128 pkgProblemResolver *resolver = [database_ resolver];
7130 resolver->InstallProtect();
7131 if (!resolver->Resolve(true))
7135 - (void) popUpBook:(RVBook *)book {
7136 [underlay_ popSubview:book];
7139 - (CGRect) popUpBounds {
7140 return [underlay_ bounds];
7144 [database_ prepare];
7146 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7147 [confirm_ setDelegate:self];
7149 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7150 [page setDelegate:self];
7152 [confirm_ setPage:page];
7153 [self popUpBook:confirm_];
7157 @synchronized (self) {
7162 - (void) clearPackage:(Package *)package {
7163 @synchronized (self) {
7170 - (void) installPackage:(Package *)package {
7171 @synchronized (self) {
7178 - (void) removePackage:(Package *)package {
7179 @synchronized (self) {
7186 - (void) distUpgrade {
7187 @synchronized (self) {
7188 [database_ upgrade];
7194 [self slideUp:[[[UIActionSheet alloc]
7196 buttons:[NSArray arrayWithObjects:CYLocalize("CONTINUE_QUEUING"), CYLocalize("CANCEL_CLEAR"), nil]
7197 defaultButtonIndex:1
7204 @synchronized (self) {
7207 if (confirm_ != nil) {
7215 [overlay_ removeFromSuperview];
7219 detachNewThreadSelector:@selector(perform)
7222 title:CYLocalize("RUNNING")
7226 - (void) bootstrap_ {
7228 [database_ upgrade];
7229 [database_ prepare];
7230 [database_ perform];
7233 /* XXX: replace and localize */
7234 - (void) bootstrap {
7236 detachNewThreadSelector:@selector(bootstrap_)
7239 title:@"Bootstrap Install"
7243 - (void) progressViewIsComplete:(ProgressView *)progress {
7244 if (confirm_ != nil) {
7245 [underlay_ addSubview:overlay_];
7246 [confirm_ popFromSuperviewAnimated:NO];
7252 - (void) setPage:(RVPage *)page {
7253 [page resetViewAnimated:NO];
7254 [page setDelegate:self];
7255 [book_ setPage:page];
7258 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7259 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7260 [browser loadURL:url];
7264 - (void) _setHomePage {
7265 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7268 - (SectionsView *) sectionsView {
7269 if (sections_ == nil)
7270 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7274 - (void) buttonBarItemTapped:(id)sender {
7275 unsigned tag = [sender tag];
7277 [book_ resetViewAnimated:YES];
7279 } else if (tag_ == 2 && tag != 2)
7280 [[self sectionsView] resetView];
7283 case 1: [self _setHomePage]; break;
7285 case 2: [self setPage:[self sectionsView]]; break;
7286 case 3: [self setPage:changes_]; break;
7287 case 4: [self setPage:manage_]; break;
7288 case 5: [self setPage:search_]; break;
7290 default: _assert(false);
7296 - (void) applicationWillSuspend {
7298 [super applicationWillSuspend];
7301 - (void) askForSettings {
7302 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
7304 UIActionSheet *role = [[[UIActionSheet alloc]
7305 initWithTitle:CYLocalize("WHO_ARE_YOU")
7306 buttons:[NSArray arrayWithObjects:
7307 [NSString stringWithFormat:parenthetical, CYLocalize("USER"), CYLocalize("USER_EX")],
7308 [NSString stringWithFormat:parenthetical, CYLocalize("HACKER"), CYLocalize("HACKER_EX")],
7309 [NSString stringWithFormat:parenthetical, CYLocalize("DEVELOPER"), CYLocalize("DEVELOPER_EX")],
7311 defaultButtonIndex:-1
7316 [role setBodyText:CYLocalize("ROLE_EX")];
7317 [role popupAlertAnimated:YES];
7320 - (void) setPackageView:(PackageView *)view {
7321 if (package_ == nil)
7322 package_ = [view retain];
7323 NSLog(@"packageView: %@", package_);
7326 - (PackageView *) packageView {
7329 if (package_ == nil)
7330 view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7333 view = [package_ autorelease];
7342 [self setStatusBarShowsProgress:NO];
7343 [self removeProgressHUD:hud_];
7348 pid_t pid = ExecFork();
7350 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7351 perror("launchctl stop");
7358 [self askForSettings];
7363 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7365 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7366 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7367 0, 0, screenrect.size.width, screenrect.size.height - 48
7368 ) database:database_];
7370 [book_ setDelegate:self];
7372 [overlay_ addSubview:book_];
7374 NSArray *buttonitems = [NSArray arrayWithObjects:
7375 [NSDictionary dictionaryWithObjectsAndKeys:
7376 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7377 @"home-up.png", kUIButtonBarButtonInfo,
7378 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7379 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7380 self, kUIButtonBarButtonTarget,
7381 CYLocalize("HOME"), kUIButtonBarButtonTitle,
7382 @"0", kUIButtonBarButtonType,
7385 [NSDictionary dictionaryWithObjectsAndKeys:
7386 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7387 @"install-up.png", kUIButtonBarButtonInfo,
7388 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7389 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7390 self, kUIButtonBarButtonTarget,
7391 CYLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7392 @"0", kUIButtonBarButtonType,
7395 [NSDictionary dictionaryWithObjectsAndKeys:
7396 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7397 @"changes-up.png", kUIButtonBarButtonInfo,
7398 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7399 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7400 self, kUIButtonBarButtonTarget,
7401 CYLocalize("CHANGES"), kUIButtonBarButtonTitle,
7402 @"0", kUIButtonBarButtonType,
7405 [NSDictionary dictionaryWithObjectsAndKeys:
7406 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7407 @"manage-up.png", kUIButtonBarButtonInfo,
7408 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7409 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7410 self, kUIButtonBarButtonTarget,
7411 CYLocalize("MANAGE"), kUIButtonBarButtonTitle,
7412 @"0", kUIButtonBarButtonType,
7415 [NSDictionary dictionaryWithObjectsAndKeys:
7416 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7417 @"search-up.png", kUIButtonBarButtonInfo,
7418 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7419 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7420 self, kUIButtonBarButtonTarget,
7421 CYLocalize("SEARCH"), kUIButtonBarButtonTitle,
7422 @"0", kUIButtonBarButtonType,
7426 buttonbar_ = [[UIToolbar alloc]
7428 withFrame:CGRectMake(
7429 0, screenrect.size.height - ButtonBarHeight_,
7430 screenrect.size.width, ButtonBarHeight_
7432 withItemList:buttonitems
7435 [buttonbar_ setDelegate:self];
7436 [buttonbar_ setBarStyle:1];
7437 [buttonbar_ setButtonBarTrackingMode:2];
7439 int buttons[5] = {1, 2, 3, 4, 5};
7440 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7441 [buttonbar_ showButtonGroup:0 withDuration:0];
7443 for (int i = 0; i != 5; ++i)
7444 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7445 i * 64 + 2, 1, 60, ButtonBarHeight_
7448 [buttonbar_ showSelectionForButton:1];
7449 [overlay_ addSubview:buttonbar_];
7451 [UIKeyboard initImplementationNow];
7452 CGSize keysize = [UIKeyboard defaultSize];
7453 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7454 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7455 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
7456 [overlay_ addSubview:keyboard_];
7459 [underlay_ addSubview:overlay_];
7463 [self sectionsView];
7464 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7465 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7467 manage_ = (ManageView *) [[self
7468 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7469 withClass:[ManageView class]
7472 [self setPackageView:[self packageView]];
7479 [self _setHomePage];
7482 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7483 NSString *context([sheet context]);
7485 if ([context isEqualToString:@"missing"])
7487 else if ([context isEqualToString:@"cancel"]) {
7505 @synchronized (self) {
7510 [buttonbar_ setBadgeValue:CYLocalize("Q_D") forButton:4];
7514 if (confirm_ != nil) {
7519 } else if ([context isEqualToString:@"fixhalf"]) {
7522 @synchronized (self) {
7523 for (Package *broken in broken_) {
7526 NSString *id = [broken id];
7527 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7528 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7529 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7530 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7539 [broken_ removeAllObjects];
7548 } else if ([context isEqualToString:@"role"]) {
7550 case 1: Role_ = @"User"; break;
7551 case 2: Role_ = @"Hacker"; break;
7552 case 3: Role_ = @"Developer"; break;
7559 bool reset = Settings_ != nil;
7561 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7565 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7575 } else if ([context isEqualToString:@"upgrade"]) {
7578 @synchronized (self) {
7579 for (Package *essential in essential_)
7580 [essential install];
7603 - (void) reorganize { _pooled
7604 system("/usr/libexec/cydia/free.sh");
7605 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
7608 - (void) applicationSuspend:(__GSEvent *)event {
7609 if (hud_ == nil && ![progress_ isRunning])
7610 [super applicationSuspend:event];
7613 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7615 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7618 - (void) _setSuspended:(BOOL)value {
7620 [super _setSuspended:value];
7623 - (UIProgressHUD *) addProgressHUD {
7624 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
7625 [window_ setUserInteractionEnabled:NO];
7627 [progress_ addSubview:hud];
7631 - (void) removeProgressHUD:(UIProgressHUD *)hud {
7633 [hud removeFromSuperview];
7634 [window_ setUserInteractionEnabled:YES];
7637 - (void) openMailToURL:(NSURL *)url {
7638 // XXX: this makes me sad
7640 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
7642 [UIApp openURL:url];// asPanel:YES];
7646 - (void) clearFirstResponder {
7647 if (id responder = [window_ firstResponder])
7648 [responder resignFirstResponder];
7651 - (RVPage *) pageForPackage:(NSString *)name {
7652 if (Package *package = [database_ packageWithName:name]) {
7653 PackageView *view([self packageView]);
7654 [view setPackage:package];
7657 UIActionSheet *sheet = [[[UIActionSheet alloc]
7658 initWithTitle:CYLocalize("CANNOT_LOCATE_PACKAGE")
7659 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
7660 defaultButtonIndex:0
7665 [sheet setBodyText:[NSString stringWithFormat:CYLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
7667 [sheet popupAlertAnimated:YES];
7672 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
7676 NSString *scheme([[url scheme] lowercaseString]);
7677 if (![scheme isEqualToString:@"cydia"])
7679 NSString *path([url absoluteString]);
7680 if ([path length] < 8)
7682 path = [path substringFromIndex:8];
7683 if (![path hasPrefix:@"/"])
7684 path = [@"/" stringByAppendingString:path];
7686 if ([path isEqualToString:@"/add-source"])
7687 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
7688 else if ([path isEqualToString:@"/storage"])
7689 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[BrowserView class]];
7690 else if ([path isEqualToString:@"/sources"])
7691 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
7692 else if ([path isEqualToString:@"/packages"])
7693 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
7694 else if ([path hasPrefix:@"/url/"])
7695 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[BrowserView class]];
7696 else if ([path hasPrefix:@"/launch/"])
7697 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
7698 else if ([path hasPrefix:@"/package-settings/"])
7699 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
7700 else if ([path hasPrefix:@"/package-signature/"])
7701 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
7702 else if ([path hasPrefix:@"/package/"])
7703 return [self pageForPackage:[path substringFromIndex:9]];
7704 else if ([path hasPrefix:@"/files/"]) {
7705 NSString *name = [path substringFromIndex:7];
7707 if (Package *package = [database_ packageWithName:name]) {
7708 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
7709 [files setPackage:package];
7717 - (void) applicationOpenURL:(NSURL *)url {
7718 [super applicationOpenURL:url];
7720 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
7721 [self setPage:page];
7722 [buttonbar_ showSelectionForButton:tag];
7727 - (void) applicationDidFinishLaunching:(id)unused {
7729 Font12_ = [[UIFont systemFontOfSize:12] retain];
7730 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
7731 Font14_ = [[UIFont systemFontOfSize:14] retain];
7732 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
7733 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
7735 _assert(pkgInitConfig(*_config));
7736 _assert(pkgInitSystem(*_config, _system));
7740 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
7741 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
7743 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
7745 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7746 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
7748 [window_ orderFront:self];
7749 [window_ makeKey:self];
7750 [window_ setHidden:NO];
7752 database_ = [Database sharedInstance];
7753 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
7754 [database_ setDelegate:progress_];
7755 [window_ setContentView:progress_];
7757 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
7758 [progress_ setContentView:underlay_];
7760 [progress_ resetView];
7763 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
7764 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
7765 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
7766 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
7767 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
7768 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
7769 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
7771 [self setIdleTimerDisabled:YES];
7773 hud_ = [[self addProgressHUD] retain];
7774 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
7776 [self setStatusBarShowsProgress:YES];
7779 detachNewThreadSelector:@selector(reorganize)
7787 - (void) showKeyboard:(BOOL)show {
7788 CGSize keysize = [UIKeyboard defaultSize];
7789 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
7790 CGRect keyup = keydown;
7791 keyup.origin.y -= keysize.height;
7793 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
7794 [animation setSignificantRectFields:2];
7797 [animation setStartFrame:keydown];
7798 [animation setEndFrame:keyup];
7799 [keyboard_ activate];
7801 [animation setStartFrame:keyup];
7802 [animation setEndFrame:keydown];
7803 [keyboard_ deactivate];
7806 [[UIAnimator sharedAnimator]
7807 addAnimations:[NSArray arrayWithObjects:animation, nil]
7808 withDuration:KeyboardTime_
7813 - (void) slideUp:(UIActionSheet *)alert {
7815 [alert presentSheetFromButtonBar:buttonbar_];
7817 [alert presentSheetInView:overlay_];
7822 void AddPreferences(NSString *plist) { _pooled
7823 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
7824 _assert(settings != NULL);
7825 NSMutableArray *items = [settings objectForKey:@"items"];
7829 for (NSMutableDictionary *item in items) {
7830 NSString *label = [item objectForKey:@"label"];
7831 if (label != nil && [label isEqualToString:@"Cydia"]) {
7838 for (size_t i(0); i != [items count]; ++i) {
7839 NSDictionary *item([items objectAtIndex:i]);
7840 NSString *label = [item objectForKey:@"label"];
7841 if (label != nil && [label isEqualToString:@"General"]) {
7842 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
7843 @"CydiaSettings", @"bundle",
7844 @"PSLinkCell", @"cell",
7845 [NSNumber numberWithBool:YES], @"hasIcon",
7846 [NSNumber numberWithBool:YES], @"isController",
7848 nil] atIndex:(i + 1)];
7854 _assert([settings writeToFile:plist atomically:YES] == YES);
7859 id Alloc_(id self, SEL selector) {
7860 id object = alloc_(self, selector);
7861 lprintf("[%s]A-%p\n", self->isa->name, object);
7866 id Dealloc_(id self, SEL selector) {
7867 id object = dealloc_(self, selector);
7868 lprintf("[%s]D-%p\n", self->isa->name, object);
7872 Class $WebDefaultUIKitDelegate;
7874 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
7876 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
7877 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
7878 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
7879 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
7882 int main(int argc, char *argv[]) { _pooled
7885 Locale_ = CFLocaleCopyCurrent();
7887 CFStringRef locale(CFLocaleGetIdentifier(Locale_));
7888 setenv("LANG", [(NSString *) locale UTF8String], true);
7890 // XXX: apr_app_initialize?
7893 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
7895 bool substrate(false);
7901 for (int argi(1); argi != argc; ++argi)
7902 if (strcmp(argv[argi], "--") == 0) {
7904 argv[argi] = argv[0];
7910 for (int argi(1); argi != arge; ++argi)
7911 if (strcmp(args[argi], "--bootstrap") == 0)
7913 else if (strcmp(args[argi], "--substrate") == 0)
7916 fprintf(stderr, "unknown argument: %s\n", args[argi]);
7919 App_ = [[NSBundle mainBundle] bundlePath];
7920 Home_ = NSHomeDirectory();
7923 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
7924 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
7925 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
7926 Sounds_Keyboard_ = [keyboard boolValue];
7932 #if 1 /* XXX: this costs 1.4s of startup performance */
7933 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
7934 _assert(errno == ENOENT);
7935 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
7936 _assert(errno == ENOENT);
7939 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
7940 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
7941 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
7942 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
7943 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
7946 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
7947 alloc_ = alloc->method_imp;
7948 alloc->method_imp = (IMP) &Alloc_;*/
7950 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
7951 dealloc_ = dealloc->method_imp;
7952 dealloc->method_imp = (IMP) &Dealloc_;*/
7957 size = sizeof(maxproc);
7958 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
7959 perror("sysctlbyname(\"kern.maxproc\", ?)");
7960 else if (maxproc < 64) {
7962 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
7963 perror("sysctlbyname(\"kern.maxproc\", #)");
7966 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
7967 char *machine = new char[size];
7968 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
7969 perror("sysctlbyname(\"hw.machine\", ?)");
7973 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
7975 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
7976 Build_ = [system objectForKey:@"ProductBuildVersion"];
7977 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
7978 Product_ = [info objectForKey:@"SafariProductVersion"];
7979 Safari_ = [info objectForKey:@"CFBundleVersion"];
7982 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
7983 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
7986 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
7988 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
7991 if (Metadata_ == NULL)
7992 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
7994 Settings_ = [Metadata_ objectForKey:@"Settings"];
7996 Packages_ = [Metadata_ objectForKey:@"Packages"];
7997 Sections_ = [Metadata_ objectForKey:@"Sections"];
7998 Sources_ = [Metadata_ objectForKey:@"Sources"];
8001 if (Settings_ != nil)
8002 Role_ = [Settings_ objectForKey:@"Role"];
8004 if (Packages_ == nil) {
8005 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8006 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8009 if (Sections_ == nil) {
8010 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8011 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8014 if (Sources_ == nil) {
8015 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8016 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8020 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8023 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8024 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8025 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8026 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8028 if (access("/User", F_OK) != 0) {
8030 system("/usr/libexec/cydia/firmware.sh");
8034 _assert([[NSFileManager defaultManager]
8035 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8036 withIntermediateDirectories:YES
8041 space_ = CGColorSpaceCreateDeviceRGB();
8043 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8044 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8045 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8046 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8047 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8048 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8049 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8050 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8051 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8052 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8053 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8054 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8055 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8056 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8057 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8060 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8061 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8063 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8065 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8066 if ($GSFontSetUseLegacyFontMetrics != NULL)
8067 $GSFontSetUseLegacyFontMetrics(YES);
8069 UIKeyboardDisableAutomaticAppearance();
8072 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8074 CGColorSpaceRelease(space_);