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/debindexfile.h>
71 #include <apt-pkg/debmetaindex.h>
72 #include <apt-pkg/error.h>
73 #include <apt-pkg/init.h>
74 #include <apt-pkg/mmap.h>
75 #include <apt-pkg/pkgrecords.h>
76 #include <apt-pkg/sha1.h>
77 #include <apt-pkg/sourcelist.h>
78 #include <apt-pkg/sptr.h>
79 #include <apt-pkg/strutl.h>
81 #include <apr-1/apr_pools.h>
83 #include <sys/types.h>
85 #include <sys/sysctl.h>
86 #include <sys/param.h>
87 #include <sys/mount.h>
93 #include <mach-o/nlist.h>
103 #include <ext/hash_map>
105 #import "BrowserView.h"
106 #import "ResetView.h"
108 #import "substrate.h"
111 //#define _finline __attribute__((force_inline))
112 #define _finline inline
117 #define _limit(count) do { \
118 static size_t _count(0); \
119 if (++_count == count) \
124 #define _timestamp ({ \
126 gettimeofday(&tv, NULL); \
127 tv.tv_sec * 1000000 + tv.tv_usec; \
130 typedef std::vector<class ProfileTime *> TimeList;
140 ProfileTime(const char *name) :
144 times_.push_back(this);
147 void AddTime(uint64_t time) {
154 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
166 ProfileTimer(ProfileTime &time) :
173 time_.AddTime(_timestamp - start_);
178 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
180 std::cerr << "========" << std::endl;
183 #define _profile(name) { \
184 static ProfileTime name(#name); \
185 ProfileTimer _ ## name(name);
189 /* Objective-C Handle<> {{{ */
190 template <typename Type_>
192 typedef _H<Type_> This_;
197 _finline void Retain_() {
202 _finline void Clear_() {
208 _finline _H(Type_ *value = NULL, bool mended = false) :
219 _finline This_ &operator =(Type_ *value) {
220 if (value_ != value) {
229 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
231 void NSLogPoint(const char *fix, const CGPoint &point) {
232 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
235 void NSLogRect(const char *fix, const CGRect &rect) {
236 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
239 @interface NSObject (Cydia)
240 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
241 - (id) yieldToSelector:(SEL)selector;
244 @implementation NSObject (Cydia)
249 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
250 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
251 id object([[context objectAtIndex:1] nonretainedObjectValue]);
252 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
254 /* XXX: deal with exceptions */
255 id value([self performSelector:selector withObject:object]);
257 [context removeAllObjects];
259 [context addObject:value];
264 performSelectorOnMainThread:@selector(doNothing)
270 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
271 /*return [self performSelector:selector withObject:object];*/
273 volatile bool stopped(false);
275 NSMutableArray *context([NSMutableArray arrayWithObjects:
276 [NSValue valueWithPointer:selector],
277 [NSValue valueWithNonretainedObject:object],
278 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
281 NSThread *thread([[[NSThread alloc]
283 selector:@selector(_yieldToContext:)
289 NSRunLoop *loop([NSRunLoop currentRunLoop]);
290 NSDate *future([NSDate distantFuture]);
292 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
294 return [context count] == 0 ? nil : [context objectAtIndex:0];
297 - (id) yieldToSelector:(SEL)selector {
298 return [self yieldToSelector:selector withObject:nil];
303 /* NSForcedOrderingSearch doesn't work on the iPhone */
304 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
305 static const NSStringCompareOptions BaseCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch;
306 static const NSStringCompareOptions ForcedCompareOptions_ = BaseCompareOptions_;
307 static const NSStringCompareOptions LaxCompareOptions_ = BaseCompareOptions_ | NSCaseInsensitiveSearch;
309 /* iPhoneOS 2.0 Compatibility {{{ */
311 @interface UITextView (iPhoneOS)
312 - (void) setTextSize:(float)size;
315 @implementation UITextView (iPhoneOS)
317 - (void) setTextSize:(float)size {
318 [self setFont:[[self font] fontWithSize:size]];
325 extern NSString * const kCAFilterNearest;
327 /* Information Dictionaries {{{ */
328 @interface NSMutableArray (Cydia)
329 - (void) addInfoDictionary:(NSDictionary *)info;
332 @implementation NSMutableArray (Cydia)
334 - (void) addInfoDictionary:(NSDictionary *)info {
335 [self addObject:info];
340 @interface NSMutableDictionary (Cydia)
341 - (void) addInfoDictionary:(NSDictionary *)info;
344 @implementation NSMutableDictionary (Cydia)
346 - (void) addInfoDictionary:(NSDictionary *)info {
347 NSString *bundle = [info objectForKey:@"CFBundleIdentifier"];
348 [self setObject:info forKey:bundle];
353 /* Pop Transitions {{{ */
354 @interface PopTransitionView : UITransitionView {
359 @implementation PopTransitionView
361 - (void) transitionViewDidComplete:(UITransitionView *)view fromView:(UIView *)from toView:(UIView *)to {
362 if (from != nil && to == nil)
363 [self removeFromSuperview];
368 @implementation UIView (PopUpView)
370 - (void) popFromSuperviewAnimated:(BOOL)animated {
371 [[self superview] transition:(animated ? UITransitionPushFromTop : UITransitionNone) toView:nil];
374 - (void) popSubview:(UIView *)view {
375 UITransitionView *transition([[[PopTransitionView alloc] initWithFrame:[self bounds]] autorelease]);
376 [transition setDelegate:transition];
377 [self addSubview:transition];
379 UIView *blank = [[[UIView alloc] initWithFrame:[transition bounds]] autorelease];
380 [transition transition:UITransitionNone toView:blank];
381 [transition transition:UITransitionPushFromBottom toView:view];
387 #define lprintf(args...) fprintf(stderr, args)
390 #define ForSaurik (0 && !ForRelease)
391 #define LogBrowser (1 && !ForRelease)
392 #define ManualRefresh (1 && !ForRelease)
393 #define ShowInternals (0 && !ForRelease)
394 #define IgnoreInstall (0 && !ForRelease)
395 #define RecycleWebViews 0
396 #define AlwaysReload (1 && !ForRelease)
400 #define _trace(args...)
402 #define _profile(name) {
405 #define PrintTimes() do {} while (false)
409 @interface NSMutableArray (Radix)
410 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object;
411 - (void) radixSortUsingFunction:(uint32_t (*)(id, void *))function withArgument:(void *)argument;
419 static void RadixSort_(NSMutableArray *self, size_t count, struct RadixItem_ *swap) {
420 struct RadixItem_ *lhs(swap), *rhs(swap + count);
422 static const size_t width = 32;
423 static const size_t bits = 11;
424 static const size_t slots = 1 << bits;
425 static const size_t passes = (width + (bits - 1)) / bits;
427 size_t *hist(new size_t[slots]);
429 for (size_t pass(0); pass != passes; ++pass) {
430 memset(hist, 0, sizeof(size_t) * slots);
432 for (size_t i(0); i != count; ++i) {
433 uint32_t key(lhs[i].key);
435 key &= _not(uint32_t) >> width - bits;
440 for (size_t i(0); i != slots; ++i) {
441 size_t local(offset);
446 for (size_t i(0); i != count; ++i) {
447 uint32_t key(lhs[i].key);
449 key &= _not(uint32_t) >> width - bits;
450 rhs[hist[key]++] = lhs[i];
453 RadixItem_ *tmp(lhs);
460 NSMutableArray *values([NSMutableArray arrayWithCapacity:count]);
461 for (size_t i(0); i != count; ++i)
462 [values addObject:[self objectAtIndex:lhs[i].index]];
463 [self setArray:values];
468 @implementation NSMutableArray (Radix)
470 - (void) radixSortUsingSelector:(SEL)selector withObject:(id)object {
471 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:"L12@0:4@8"]]);
472 [invocation setSelector:selector];
473 [invocation setArgument:&object atIndex:2];
475 size_t count([self count]);
476 struct RadixItem_ *swap(new RadixItem_[count * 2]);
478 for (size_t i(0); i != count; ++i) {
479 RadixItem_ &item(swap[i]);
482 id object([self objectAtIndex:i]);
483 [invocation setTarget:object];
486 [invocation getReturnValue:&item.key];
489 RadixSort_(self, count, swap);
492 - (void) radixSortUsingFunction:(uint32_t (*)(id, void *))function withArgument:(void *)argument {
493 size_t count([self count]);
494 struct RadixItem_ *swap(new RadixItem_[count * 2]);
496 for (size_t i(0); i != count; ++i) {
497 RadixItem_ &item(swap[i]);
500 id object([self objectAtIndex:i]);
501 item.key = function(object, argument);
504 RadixSort_(self, count, swap);
510 /* Apple Bug Fixes {{{ */
511 @implementation UIWebDocumentView (Cydia)
513 - (void) _setScrollerOffset:(CGPoint)offset {
514 UIScroller *scroller([self _scroller]);
516 CGSize size([scroller contentSize]);
517 CGSize bounds([scroller bounds].size);
520 max.x = size.width - bounds.width;
521 max.y = size.height - bounds.height;
529 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
530 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
532 [scroller setOffset:offset];
539 kUIControlEventMouseDown = 1 << 0,
540 kUIControlEventMouseMovedInside = 1 << 2, // mouse moved inside control target
541 kUIControlEventMouseMovedOutside = 1 << 3, // mouse moved outside control target
542 kUIControlEventMouseUpInside = 1 << 6, // mouse up inside control target
543 kUIControlEventMouseUpOutside = 1 << 7, // mouse up outside control target
544 kUIControlAllEvents = (kUIControlEventMouseDown | kUIControlEventMouseMovedInside | kUIControlEventMouseMovedOutside | kUIControlEventMouseUpInside | kUIControlEventMouseUpOutside)
545 } UIControlEventMasks;
547 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
548 size_t length([self length] - state->state);
551 else if (length > count)
553 for (size_t i(0); i != length; ++i)
554 objects[i] = [self item:state->state++];
555 state->itemsPtr = objects;
556 state->mutationsPtr = (unsigned long *) self;
560 @interface NSString (UIKit)
561 - (NSString *) stringByAddingPercentEscapes;
562 - (NSString *) stringByReplacingCharacter:(unsigned short)arg0 withCharacter:(unsigned short)arg1;
565 @interface NSString (Cydia)
566 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
567 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
568 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
569 - (NSComparisonResult) compareByPath:(NSString *)other;
570 - (NSString *) stringByCachingURLWithCurrentCDN;
571 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
574 @implementation NSString (Cydia)
576 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
577 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
580 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
581 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
582 memcpy(data, bytes, length);
583 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
586 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
587 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
590 - (NSComparisonResult) compareByPath:(NSString *)other {
591 NSString *prefix = [self commonPrefixWithString:other options:0];
592 size_t length = [prefix length];
594 NSRange lrange = NSMakeRange(length, [self length] - length);
595 NSRange rrange = NSMakeRange(length, [other length] - length);
597 lrange = [self rangeOfString:@"/" options:0 range:lrange];
598 rrange = [other rangeOfString:@"/" options:0 range:rrange];
600 NSComparisonResult value;
602 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
603 value = NSOrderedSame;
604 else if (lrange.location == NSNotFound)
605 value = NSOrderedAscending;
606 else if (rrange.location == NSNotFound)
607 value = NSOrderedDescending;
609 value = NSOrderedSame;
611 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
612 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
613 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
614 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
616 NSComparisonResult result = [lpath compare:rpath];
617 return result == NSOrderedSame ? value : result;
620 - (NSString *) stringByCachingURLWithCurrentCDN {
622 stringByReplacingOccurrencesOfString:@"://"
623 withString:@"://ne.edgecastcdn.net/8003A4/"
625 /* XXX: this is somewhat inaccurate */
626 range:NSMakeRange(0, 10)
630 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
631 return [(id)CFURLCreateStringByAddingPercentEscapes(
636 kCFStringEncodingUTF8
642 static inline NSString *CYLocalizeEx(NSString *key, NSString *value = nil) {
643 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:nil];
646 #define CYLocalize(key) CYLocalizeEx(@ key)
654 _finline void clear_() {
660 _finline bool empty() const {
664 _finline size_t size() const {
668 _finline char *data() const {
672 _finline void clear() {
677 _finline CYString() :
684 _finline ~CYString() {
688 void operator =(const CYString &rhs) {
692 if (rhs.cache_ == nil)
695 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
698 void set(apr_pool_t *pool, const char *data, size_t size) {
704 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size)));
705 memcpy(temp, data, size);
711 _finline void set(apr_pool_t *pool, const char *data) {
712 set(pool, data, data == NULL ? 0 : strlen(data));
715 _finline void set(apr_pool_t *pool, const std::string &rhs) {
716 set(pool, rhs.data(), rhs.size());
719 bool operator ==(const CYString &rhs) const {
720 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
724 if (cache_ == NULL) {
727 cache_ = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<uint8_t *>(data_), size_, kCFStringEncodingUTF8, NO, kCFAllocatorNull);
728 } return (id) cache_;
733 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
736 struct NSStringMapHash :
737 std::unary_function<NSString *, size_t>
739 _finline size_t operator ()(NSString *value) const {
740 return CFStringHashNSString((CFStringRef) value);
744 struct NSStringMapLess :
745 std::binary_function<NSString *, NSString *, bool>
747 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
748 return [lhs compare:rhs] == NSOrderedAscending;
752 struct NSStringMapEqual :
753 std::binary_function<NSString *, NSString *, bool>
755 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
756 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
757 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
758 //[lhs isEqualToString:rhs];
762 /* Perl-Compatible RegEx {{{ */
772 Pcre(const char *regex) :
777 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
780 lprintf("%d:%s\n", offset, error);
784 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
785 matches_ = new int[(capture_ + 1) * 3];
793 NSString *operator [](size_t match) {
794 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
797 bool operator ()(NSString *data) {
798 // XXX: length is for characters, not for bytes
799 return operator ()([data UTF8String], [data length]);
802 bool operator ()(const char *data, size_t size) {
804 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
808 /* Mime Addresses {{{ */
809 @interface Address : NSObject {
815 - (NSString *) address;
817 - (void) setAddress:(NSString *)address;
819 + (Address *) addressWithString:(NSString *)string;
820 - (Address *) initWithString:(NSString *)string;
823 @implementation Address
832 - (NSString *) name {
836 - (NSString *) address {
840 - (void) setAddress:(NSString *)address {
842 [address_ autorelease];
846 address_ = [address retain];
849 + (Address *) addressWithString:(NSString *)string {
850 return [[[Address alloc] initWithString:string] autorelease];
853 + (NSArray *) _attributeKeys {
854 return [NSArray arrayWithObjects:@"address", @"name", nil];
857 - (NSArray *) attributeKeys {
858 return [[self class] _attributeKeys];
861 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
862 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
865 - (Address *) initWithString:(NSString *)string {
866 if ((self = [super init]) != nil) {
867 const char *data = [string UTF8String];
868 size_t size = [string length];
870 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
872 if (address_r(data, size)) {
873 name_ = [address_r[1] retain];
874 address_ = [address_r[2] retain];
876 name_ = [string retain];
884 /* CoreGraphics Primitives {{{ */
895 CGColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
898 Set(space, red, green, blue, alpha);
903 CGColorRelease(color_);
910 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
912 float color[] = {red, green, blue, alpha};
913 color_ = CGColorCreate(space, color);
916 operator CGColorRef() {
922 extern "C" void UISetColor(CGColorRef color);
924 /* Random Global Variables {{{ */
925 static const int PulseInterval_ = 50000;
926 static const int ButtonBarHeight_ = 48;
927 static const float KeyboardTime_ = 0.3f;
929 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
930 #define SandboxTemplate_ "/usr/share/sandbox/SandboxTemplate.sb"
931 #define NotifyConfig_ "/etc/notify.conf"
933 static bool Queuing_;
935 static CGColor Blue_;
936 static CGColor Blueish_;
937 static CGColor Black_;
939 static CGColor White_;
940 static CGColor Gray_;
941 static CGColor Green_;
942 static CGColor Purple_;
943 static CGColor Purplish_;
945 static UIColor *InstallingColor_;
946 static UIColor *RemovingColor_;
948 static NSString *App_;
949 static NSString *Home_;
950 static BOOL Sounds_Keyboard_;
952 static BOOL Advanced_;
954 static BOOL Ignored_;
956 static UIFont *Font12_;
957 static UIFont *Font12Bold_;
958 static UIFont *Font14_;
959 static UIFont *Font18Bold_;
960 static UIFont *Font22Bold_;
962 static const char *Machine_ = NULL;
963 static const NSString *UniqueID_ = nil;
964 static const NSString *Build_ = nil;
965 static const NSString *Product_ = nil;
966 static const NSString *Safari_ = nil;
969 CGColorSpaceRef space_;
974 static NSDictionary *SectionMap_;
975 static NSMutableDictionary *Metadata_;
976 static _transient NSMutableDictionary *Settings_;
977 static _transient NSString *Role_;
978 static _transient NSMutableDictionary *Packages_;
979 static _transient NSMutableDictionary *Sections_;
980 static _transient NSMutableDictionary *Sources_;
981 static bool Changed_;
985 static NSMutableArray *Documents_;
988 NSString *GetLastUpdate() {
989 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
992 return CYLocalize("NEVER_OR_UNKNOWN");
994 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
995 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
997 CFRelease(formatter);
999 return [(NSString *) formatted autorelease];
1002 /* Display Helpers {{{ */
1003 inline float Interpolate(float begin, float end, float fraction) {
1004 return (end - begin) * fraction + begin;
1007 /* XXX: localize this! */
1008 NSString *SizeString(double size) {
1009 bool negative = size < 0;
1014 while (size > 1024) {
1019 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1021 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1024 NSString *StripVersion(NSString *version) {
1025 NSRange colon = [version rangeOfString:@":"];
1026 if (colon.location != NSNotFound)
1027 version = [version substringFromIndex:(colon.location + 1)];
1031 NSString *LocalizeSection(NSString *section) {
1035 NSString *Simplify(NSString *title) {
1036 const char *data = [title UTF8String];
1037 size_t size = [title length];
1039 static Pcre square_r("^\\[(.*)\\]$");
1040 if (square_r(data, size))
1041 return Simplify(square_r[1]);
1043 static Pcre paren_r("^\\((.*)\\)$");
1044 if (paren_r(data, size))
1045 return Simplify(paren_r[1]);
1047 static Pcre title_r("^(.*?) \\(.*\\)$");
1048 if (title_r(data, size))
1049 return Simplify(title_r[1]);
1055 bool isSectionVisible(NSString *section) {
1056 NSDictionary *metadata = [Sections_ objectForKey:section];
1057 NSNumber *hidden = metadata == nil ? nil : [metadata objectForKey:@"Hidden"];
1058 return hidden == nil || ![hidden boolValue];
1061 /* Delegate Prototypes {{{ */
1065 @interface NSObject (ProgressDelegate)
1068 @implementation NSObject(ProgressDelegate)
1070 - (void) _setProgressError:(NSArray *)args {
1071 [self performSelector:@selector(setProgressError:forPackage:)
1072 withObject:[args objectAtIndex:0]
1073 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1079 @protocol ProgressDelegate
1080 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id;
1081 - (void) setProgressTitle:(NSString *)title;
1082 - (void) setProgressPercent:(float)percent;
1083 - (void) startProgress;
1084 - (void) addProgressOutput:(NSString *)output;
1085 - (bool) isCancelling:(size_t)received;
1088 @protocol ConfigurationDelegate
1089 - (void) repairWithSelector:(SEL)selector;
1090 - (void) setConfigurationData:(NSString *)data;
1095 @protocol CydiaDelegate
1096 - (void) setPackageView:(PackageView *)view;
1097 - (void) clearPackage:(Package *)package;
1098 - (void) installPackage:(Package *)package;
1099 - (void) removePackage:(Package *)package;
1100 - (void) slideUp:(UIActionSheet *)alert;
1101 - (void) distUpgrade;
1102 - (void) updateData;
1104 - (void) askForSettings;
1105 - (UIProgressHUD *) addProgressHUD;
1106 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1107 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag;
1108 - (RVPage *) pageForPackage:(NSString *)name;
1109 - (void) openMailToURL:(NSURL *)url;
1110 - (void) clearFirstResponder;
1111 - (PackageView *) packageView;
1115 /* Status Delegation {{{ */
1117 public pkgAcquireStatus
1120 _transient NSObject<ProgressDelegate> *delegate_;
1128 void setDelegate(id delegate) {
1129 delegate_ = delegate;
1132 virtual bool MediaChange(std::string media, std::string drive) {
1136 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1139 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1140 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1141 [delegate_ setProgressTitle:[NSString stringWithUTF8String:("Downloading " + item.ShortDesc).c_str()]];
1144 virtual void Done(pkgAcquire::ItemDesc &item) {
1147 virtual void Fail(pkgAcquire::ItemDesc &item) {
1149 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1150 item.Owner->Status == pkgAcquire::Item::StatDone
1154 std::string &error(item.Owner->ErrorText);
1158 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1159 NSArray *fields([description componentsSeparatedByString:@" "]);
1160 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1162 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
1163 withObject:[NSArray arrayWithObjects:
1164 [NSString stringWithUTF8String:error.c_str()],
1171 virtual bool Pulse(pkgAcquire *Owner) {
1172 bool value = pkgAcquireStatus::Pulse(Owner);
1175 double(CurrentBytes + CurrentItems) /
1176 double(TotalBytes + TotalItems)
1179 [delegate_ setProgressPercent:percent];
1180 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1183 virtual void Start() {
1184 [delegate_ startProgress];
1187 virtual void Stop() {
1191 /* Progress Delegation {{{ */
1196 _transient id<ProgressDelegate> delegate_;
1199 virtual void Update() {
1200 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1201 [delegate_ setProgressPercent:(Percent / 100)];*/
1210 void setDelegate(id delegate) {
1211 delegate_ = delegate;
1214 virtual void Done() {
1215 //[delegate_ setProgressPercent:1];
1220 /* Database Interface {{{ */
1221 @interface Database : NSObject {
1227 pkgCacheFile cache_;
1228 pkgDepCache::Policy *policy_;
1229 pkgRecords *records_;
1230 pkgProblemResolver *resolver_;
1231 pkgAcquire *fetcher_;
1233 SPtr<pkgPackageManager> manager_;
1234 pkgSourceList *list_;
1236 NSMutableDictionary *sources_;
1237 NSMutableArray *packages_;
1239 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1248 + (Database *) sharedInstance;
1251 - (void) _readCydia:(NSNumber *)fd;
1252 - (void) _readStatus:(NSNumber *)fd;
1253 - (void) _readOutput:(NSNumber *)fd;
1257 - (Package *) packageWithName:(NSString *)name;
1259 - (pkgCacheFile &) cache;
1260 - (pkgDepCache::Policy *) policy;
1261 - (pkgRecords *) records;
1262 - (pkgProblemResolver *) resolver;
1263 - (pkgAcquire &) fetcher;
1264 - (pkgSourceList &) list;
1265 - (NSArray *) packages;
1266 - (NSArray *) sources;
1267 - (void) reloadData;
1275 - (void) updateWithStatus:(Status &)status;
1277 - (void) setDelegate:(id)delegate;
1278 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1282 /* Source Class {{{ */
1283 @interface Source : NSObject {
1284 NSString *description_;
1290 NSString *distribution_;
1294 NSString *defaultIcon_;
1296 NSDictionary *record_;
1300 - (Source *) initWithMetaIndex:(metaIndex *)index;
1302 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1304 - (NSString *) supportForPackage:(NSString *)package;
1306 - (NSDictionary *) record;
1310 - (NSString *) distribution;
1311 - (NSString *) type;
1313 - (NSString *) host;
1315 - (NSString *) name;
1316 - (NSString *) description;
1317 - (NSString *) label;
1318 - (NSString *) origin;
1319 - (NSString *) version;
1321 - (NSString *) defaultIcon;
1325 @implementation Source
1327 #define _clear(field) \
1334 _clear(distribution_)
1337 _clear(description_)
1342 _clear(defaultIcon_)
1351 + (NSArray *) _attributeKeys {
1352 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1355 - (NSArray *) attributeKeys {
1356 return [[self class] _attributeKeys];
1359 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1360 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1363 - (void) setMetaIndex:(metaIndex *)index {
1366 trusted_ = index->IsTrusted();
1368 uri_ = [[NSString stringWithUTF8String:index->GetURI().c_str()] retain];
1369 distribution_ = [[NSString stringWithUTF8String:index->GetDist().c_str()] retain];
1370 type_ = [[NSString stringWithUTF8String:index->GetType()] retain];
1372 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1373 if (dindex != NULL) {
1374 std::ifstream release(dindex->MetaIndexFile("Release").c_str());
1376 while (std::getline(release, line)) {
1377 std::string::size_type colon(line.find(':'));
1378 if (colon == std::string::npos)
1381 std::string name(line.substr(0, colon));
1382 std::string value(line.substr(colon + 1));
1383 while (!value.empty() && value[0] == ' ')
1384 value = value.substr(1);
1386 if (name == "Default-Icon")
1387 defaultIcon_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1388 else if (name == "Description")
1389 description_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1390 else if (name == "Label")
1391 label_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1392 else if (name == "Origin")
1393 origin_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1394 else if (name == "Support")
1395 support_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1396 else if (name == "Version")
1397 version_ = [[NSString stringWithUTF8String:value.c_str()] retain];
1401 record_ = [Sources_ objectForKey:[self key]];
1403 record_ = [record_ retain];
1406 - (Source *) initWithMetaIndex:(metaIndex *)index {
1407 if ((self = [super init]) != nil) {
1408 [self setMetaIndex:index];
1412 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1413 NSDictionary *lhr = [self record];
1414 NSDictionary *rhr = [source record];
1417 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1419 NSString *lhs = [self name];
1420 NSString *rhs = [source name];
1422 if ([lhs length] != 0 && [rhs length] != 0) {
1423 unichar lhc = [lhs characterAtIndex:0];
1424 unichar rhc = [rhs characterAtIndex:0];
1426 if (isalpha(lhc) && !isalpha(rhc))
1427 return NSOrderedAscending;
1428 else if (!isalpha(lhc) && isalpha(rhc))
1429 return NSOrderedDescending;
1432 return [lhs compare:rhs options:LaxCompareOptions_];
1435 - (NSString *) supportForPackage:(NSString *)package {
1436 return support_ == nil ? nil : [support_ stringByReplacingOccurrencesOfString:@"*" withString:package];
1439 - (NSDictionary *) record {
1447 - (NSString *) uri {
1451 - (NSString *) distribution {
1452 return distribution_;
1455 - (NSString *) type {
1459 - (NSString *) key {
1460 return [NSString stringWithFormat:@"%@:%@:%@", type_, uri_, distribution_];
1463 - (NSString *) host {
1464 return [[[NSURL URLWithString:[self uri]] host] lowercaseString];
1467 - (NSString *) name {
1468 return origin_ == nil ? [self host] : origin_;
1471 - (NSString *) description {
1472 return description_;
1475 - (NSString *) label {
1476 return label_ == nil ? [self host] : label_;
1479 - (NSString *) origin {
1483 - (NSString *) version {
1487 - (NSString *) defaultIcon {
1488 return defaultIcon_;
1493 /* Relationship Class {{{ */
1494 @interface Relationship : NSObject {
1499 - (NSString *) type;
1501 - (NSString *) name;
1505 @implementation Relationship
1513 - (NSString *) type {
1521 - (NSString *) name {
1528 /* Package Class {{{ */
1529 @interface Package : NSObject {
1532 pkgCache::VerIterator version_;
1533 pkgCache::PkgIterator iterator_;
1534 _transient Database *database_;
1535 pkgCache::VerFileIterator file_;
1541 NSString *section$_;
1545 NSString *installed_;
1551 CYString depiction_;
1564 NSArray *relationships_;
1565 NSMutableDictionary *metadata_;
1568 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1569 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1571 - (pkgCache::PkgIterator) iterator;
1573 - (NSString *) section;
1574 - (NSString *) simpleSection;
1576 - (NSString *) longSection;
1577 - (NSString *) shortSection;
1581 - (Address *) maintainer;
1583 - (NSString *) description;
1586 - (NSMutableDictionary *) metadata;
1588 - (BOOL) subscribed;
1591 - (NSString *) latest;
1592 - (NSString *) installed;
1595 - (BOOL) upgradableAndEssential:(BOOL)essential;
1598 - (BOOL) unfiltered;
1602 - (BOOL) halfConfigured;
1603 - (BOOL) halfInstalled;
1605 - (NSString *) mode;
1608 - (NSString *) name;
1609 - (NSString *) tagline;
1611 - (NSString *) homepage;
1612 - (NSString *) depiction;
1613 - (Address *) author;
1615 - (NSString *) support;
1617 - (NSArray *) files;
1618 - (NSArray *) relationships;
1619 - (NSArray *) warnings;
1620 - (NSArray *) applications;
1622 - (Source *) source;
1623 - (NSString *) role;
1625 - (BOOL) matches:(NSString *)text;
1627 - (bool) hasSupportingRole;
1628 - (BOOL) hasTag:(NSString *)tag;
1629 - (NSString *) primaryPurpose;
1630 - (NSArray *) purposes;
1631 - (bool) isCommercial;
1633 - (uint32_t) compareByPrefix;
1634 - (NSComparisonResult) compareByName:(Package *)package;
1635 - (uint32_t) compareBySection:(NSArray *)sections;
1637 - (uint32_t) compareForChanges;
1642 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1643 - (bool) isInstalledAndVisible:(NSNumber *)number;
1644 - (bool) isVisiblyUninstalledInSection:(NSString *)section;
1645 - (bool) isVisibleInSource:(Source *)source;
1649 uint32_t PackageChangesRadix(Package *self, void *) {
1654 uint32_t timestamp : 30;
1655 uint32_t ignored : 1;
1656 uint32_t upgradable : 1;
1660 bool upgradable([self upgradableAndEssential:YES]);
1661 value.bits.upgradable = upgradable ? 1 : 0;
1664 value.bits.timestamp = 0;
1665 value.bits.ignored = [self ignored] ? 0 : 1;
1666 value.bits.upgradable = 1;
1668 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1669 value.bits.ignored = 0;
1670 value.bits.upgradable = 0;
1673 return _not(uint32_t) - value.key;
1676 @implementation Package
1681 if (section$_ != nil)
1682 [section$_ release];
1686 if (installed_ != nil)
1687 [installed_ release];
1691 if (sponsor$_ != nil)
1692 [sponsor$_ release];
1693 if (author$_ != nil)
1700 if (relationships_ != nil)
1701 [relationships_ release];
1702 if (metadata_ != nil)
1703 [metadata_ release];
1708 + (NSString *) webScriptNameForSelector:(SEL)selector {
1709 if (selector == @selector(hasTag:))
1715 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1716 return [self webScriptNameForSelector:selector] == nil;
1719 + (NSArray *) _attributeKeys {
1720 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];
1723 - (NSArray *) attributeKeys {
1724 return [[self class] _attributeKeys];
1727 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1728 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1731 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
1732 if ((self = [super init]) != nil) {
1733 _profile(Package$initWithVersion)
1734 @synchronized (database) {
1735 era_ = [database era];
1738 iterator_ = version.ParentPkg();
1739 database_ = database;
1741 _profile(Package$initWithVersion$Latest)
1742 latest_ = [StripVersion([NSString stringWithUTF8String:version_.VerStr()]) retain];
1745 pkgCache::VerIterator current;
1746 NSString *installed;
1748 _profile(Package$initWithVersion$Current)
1749 current = iterator_.CurrentVer();
1750 installed = current.end() ? nil : [NSString stringWithUTF8String:current.VerStr()];
1753 _profile(Package$initWithVersion$Installed)
1754 installed_ = [StripVersion(installed) retain];
1757 _profile(Package$initWithVersion$File)
1758 if (!version_.end())
1759 file_ = version_.FileList();
1761 pkgCache &cache([database_ cache]);
1762 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
1766 _profile(Package$initWithVersion$Name)
1767 id_ = [[NSString stringWithUTF8String:iterator_.Name()] retain];
1771 source_ = [database_ getSource:file_.File()];
1776 _profile(Package$initWithVersion$Parse)
1777 pkgRecords::Parser *parser;
1779 _profile(Package$initWithVersion$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$initWithVersion$Parse$Value)
1829 value.set(pool, colon, stop - colon);
1841 _profile(Package$initWithVersion$Parse$Tagline)
1842 tagline_.set(pool, parser->ShortDesc());
1845 _profile(Package$initWithVersion$Parse$Retain)
1846 if (!homepage_.empty())
1847 homepage_ = website;
1848 if (homepage_ == depiction_)
1851 tags_ = [[tag componentsSeparatedByString:@", "] retain];
1855 _profile(Package$initWithVersion$Tags)
1857 for (NSString *tag in tags_)
1858 if ([tag hasPrefix:@"role::"]) {
1859 role_ = [[tag substringFromIndex:6] retain];
1864 bool changed(false);
1865 NSString *key([id_ lowercaseString]);
1867 _profile(Package$initWithVersion$Metadata)
1868 metadata_ = [Packages_ objectForKey:key];
1869 if (metadata_ == nil) {
1870 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
1874 [metadata_ setObject:latest_ forKey:@"LastVersion"];
1877 NSDate *first([metadata_ objectForKey:@"FirstSeen"]);
1878 NSDate *last([metadata_ objectForKey:@"LastSeen"]);
1879 NSString *version([metadata_ objectForKey:@"LastVersion"]);
1882 first = last == nil ? now_ : last;
1883 [metadata_ setObject:first forKey:@"FirstSeen"];
1887 if (version == nil) {
1888 [metadata_ setObject:latest_ forKey:@"LastVersion"];
1890 } else if (![version isEqualToString:latest_]) {
1891 [metadata_ setObject:latest_ forKey:@"LastVersion"];
1893 [metadata_ setObject:last forKey:@"LastSeen"];
1898 metadata_ = [metadata_ retain];
1901 [Packages_ setObject:metadata_ forKey:key];
1906 _profile(Package$initWithVersion$Section)
1907 section_.set(pool, iterator_.Section());
1910 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
1911 } _end } return self;
1914 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
1915 pkgCache::VerIterator version([database policy]->GetCandidateVer(iterator));
1918 return [[[Package alloc]
1919 initWithVersion:version
1926 - (pkgCache::PkgIterator) iterator {
1930 - (NSString *) section {
1931 if (section$_ == nil) {
1932 if (section_.empty())
1935 std::replace(section_.data(), section_.data() + section_.size(), ' ', '_');
1936 NSString *name(section_);
1939 if (NSDictionary *value = [SectionMap_ objectForKey:name])
1940 if (NSString *rename = [value objectForKey:@"Rename"]) {
1945 section$_ = [[name stringByReplacingCharacter:'_' withCharacter:' '] retain];
1949 - (NSString *) simpleSection {
1950 if (NSString *section = [self section])
1951 return Simplify(section);
1956 - (NSString *) longSection {
1957 return LocalizeSection(section_);
1960 - (NSString *) shortSection {
1961 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
1964 - (NSString *) uri {
1967 pkgIndexFile *index;
1968 pkgCache::PkgFileIterator file(file_.File());
1969 if (![database_ list].FindIndex(file, index))
1971 return [NSString stringWithUTF8String:iterator_->Path];
1972 //return [NSString stringWithUTF8String:file.Site()];
1973 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
1977 - (Address *) maintainer {
1980 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
1981 const std::string &maintainer(parser->Maintainer());
1982 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
1986 return version_.end() ? 0 : version_->InstalledSize;
1989 - (NSString *) description {
1992 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
1993 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
1995 NSArray *lines = [description componentsSeparatedByString:@"\n"];
1996 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
1997 if ([lines count] < 2)
2000 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2001 for (size_t i(1), e([lines count]); i != e; ++i) {
2002 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2003 [trimmed addObject:trim];
2006 return [trimmed componentsJoinedByString:@"\n"];
2010 _profile(Package$index)
2011 NSString *name([self name]);
2012 if ([name length] == 0)
2014 unichar character([name characterAtIndex:0]);
2015 if (!isalpha(character))
2017 return toupper(character);
2021 - (NSMutableDictionary *) metadata {
2022 if (metadata_ == nil)
2023 metadata_ = [[Packages_ objectForKey:[id_ lowercaseString]] retain];
2028 NSDictionary *metadata([self metadata]);
2029 if ([self subscribed])
2030 if (NSDate *last = [metadata objectForKey:@"LastSeen"])
2032 return [metadata objectForKey:@"FirstSeen"];
2035 - (BOOL) subscribed {
2036 NSDictionary *metadata([self metadata]);
2037 if (NSNumber *subscribed = [metadata objectForKey:@"IsSubscribed"])
2038 return [subscribed boolValue];
2044 NSDictionary *metadata([self metadata]);
2045 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2046 return [ignored boolValue];
2051 - (NSString *) latest {
2055 - (NSString *) installed {
2060 return !version_.end();
2063 - (BOOL) upgradableAndEssential:(BOOL)essential {
2064 pkgCache::VerIterator current = iterator_.CurrentVer();
2068 value = essential && [self essential] && [self visible];
2070 value = !version_.end() && version_ != current;// && (!essential || ![database_ cache][iterator_].Keep());
2074 - (BOOL) essential {
2079 return [database_ cache][iterator_].InstBroken();
2082 - (BOOL) unfiltered {
2083 NSString *section = [self section];
2084 return section == nil || isSectionVisible(section);
2088 return [self hasSupportingRole] && [self unfiltered];
2092 unsigned char current = iterator_->CurrentState;
2093 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2096 - (BOOL) halfConfigured {
2097 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2100 - (BOOL) halfInstalled {
2101 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2105 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2106 return state.Mode != pkgDepCache::ModeKeep;
2109 - (NSString *) mode {
2110 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2112 switch (state.Mode) {
2113 case pkgDepCache::ModeDelete:
2114 if ((state.iFlags & pkgDepCache::Purge) != 0)
2118 case pkgDepCache::ModeKeep:
2119 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2120 return @"REINSTALL";
2121 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2125 case pkgDepCache::ModeInstall:
2126 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2127 return @"REINSTALL";
2128 else*/ switch (state.Status) {
2130 return @"DOWNGRADE";
2136 return @"NEW_INSTALL";
2149 - (NSString *) name {
2150 return name_ == nil ? id_ : name_;
2153 - (NSString *) tagline {
2157 - (UIImage *) icon {
2158 NSString *section = [self simpleSection];
2162 if ([icon_ hasPrefix:@"file:///"])
2163 icon = [UIImage imageAtPath:[icon_ substringFromIndex:7]];
2164 if (icon == nil) if (section != nil)
2165 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2166 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2167 if ([dicon hasPrefix:@"file:///"])
2168 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2170 icon = [UIImage applicationImageNamed:@"unknown.png"];
2174 - (NSString *) homepage {
2178 - (NSString *) depiction {
2182 - (Address *) sponsor {
2183 if (sponsor$_ == nil) {
2184 if (sponsor_.empty())
2186 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2190 - (Address *) author {
2191 if (author$_ == nil) {
2192 if (author_.empty())
2194 author$_ = [[Address addressWithString:author_] retain];
2198 - (NSString *) support {
2199 return support_ != nil ? support_ : [[self source] supportForPackage:id_];
2202 - (NSArray *) files {
2203 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", id_];
2204 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2207 fin.open([path UTF8String]);
2212 while (std::getline(fin, line))
2213 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2218 - (NSArray *) relationships {
2219 return relationships_;
2222 - (NSArray *) warnings {
2223 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2224 const char *name(iterator_.Name());
2226 size_t length(strlen(name));
2227 if (length < 2) invalid:
2228 [warnings addObject:CYLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2229 else for (size_t i(0); i != length; ++i)
2231 /* XXX: technically this is not allowed */
2232 (name[i] < 'A' || name[i] > 'Z') &&
2233 (name[i] < 'a' || name[i] > 'z') &&
2234 (name[i] < '0' || name[i] > '9') &&
2235 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2238 if (strcmp(name, "cydia") != 0) {
2240 bool _private = false;
2243 bool repository = [[self section] isEqualToString:@"Repositories"];
2245 if (NSArray *files = [self files])
2246 for (NSString *file in files)
2247 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2249 else if (!_private && [file isEqualToString:@"/private"])
2251 else if (!stash && [file isEqualToString:@"/var/stash"])
2254 /* XXX: this is not sensitive enough. only some folders are valid. */
2255 if (cydia && !repository)
2256 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2258 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/private"]];
2260 [warnings addObject:[NSString stringWithFormat:CYLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2263 return [warnings count] == 0 ? nil : warnings;
2266 - (NSArray *) applications {
2267 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2269 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2271 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2272 if (NSArray *files = [self files])
2273 for (NSString *file in files)
2274 if (application_r(file)) {
2275 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2276 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2277 if ([id isEqualToString:me])
2280 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2282 display = application_r[1];
2284 NSString *bundle([file stringByDeletingLastPathComponent]);
2285 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2286 if (icon == nil || [icon length] == 0)
2288 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2290 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2291 [applications addObject:application];
2293 [application addObject:id];
2294 [application addObject:display];
2295 [application addObject:url];
2298 return [applications count] == 0 ? nil : applications;
2301 - (Source *) source {
2303 @synchronized (database_) {
2304 if ([database_ era] != era_ || file_.end())
2307 source_ = [database_ getSource:file_.File()];
2319 - (NSString *) role {
2323 - (BOOL) matches:(NSString *)text {
2329 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2330 if (range.location != NSNotFound)
2333 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2334 if (range.location != NSNotFound)
2337 range = [[self tagline] rangeOfString:text options:MatchCompareOptions_];
2338 if (range.location != NSNotFound)
2344 - (bool) hasSupportingRole {
2347 if ([role_ isEqualToString:@"enduser"])
2349 if ([Role_ isEqualToString:@"User"])
2351 if ([role_ isEqualToString:@"hacker"])
2353 if ([Role_ isEqualToString:@"Hacker"])
2355 if ([role_ isEqualToString:@"developer"])
2357 if ([Role_ isEqualToString:@"Developer"])
2362 - (BOOL) hasTag:(NSString *)tag {
2363 return tags_ == nil ? NO : [tags_ containsObject:tag];
2366 - (NSString *) primaryPurpose {
2367 for (NSString *tag in tags_)
2368 if ([tag hasPrefix:@"purpose::"])
2369 return [tag substringFromIndex:9];
2373 - (NSArray *) purposes {
2374 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2375 for (NSString *tag in tags_)
2376 if ([tag hasPrefix:@"purpose::"])
2377 [purposes addObject:[tag substringFromIndex:9]];
2378 return [purposes count] == 0 ? nil : purposes;
2381 - (bool) isCommercial {
2382 return [self hasTag:@"cydia::commercial"];
2385 - (uint32_t) compareByPrefix {
2389 - (NSComparisonResult) compareByName:(Package *)package {
2390 NSString *lhs = [self name];
2391 NSString *rhs = [package name];
2393 if ([lhs length] != 0 && [rhs length] != 0) {
2394 unichar lhc = [lhs characterAtIndex:0];
2395 unichar rhc = [rhs characterAtIndex:0];
2397 if (isalpha(lhc) && !isalpha(rhc))
2398 return NSOrderedAscending;
2399 else if (!isalpha(lhc) && isalpha(rhc))
2400 return NSOrderedDescending;
2403 return [lhs compare:rhs options:LaxCompareOptions_];
2406 - (uint32_t) compareBySection:(NSArray *)sections {
2407 NSString *section([self section]);
2408 for (size_t i(0), e([sections count]); i != e; ++i) {
2409 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2413 return _not(uint32_t);
2416 - (uint32_t) compareForChanges {
2421 uint32_t timestamp : 30;
2422 uint32_t ignored : 1;
2423 uint32_t upgradable : 1;
2427 bool upgradable([self upgradableAndEssential:YES]);
2428 value.bits.upgradable = upgradable ? 1 : 0;
2431 value.bits.timestamp = 0;
2432 value.bits.ignored = [self ignored] ? 0 : 1;
2433 value.bits.upgradable = 1;
2435 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2436 value.bits.ignored = 0;
2437 value.bits.upgradable = 0;
2440 return _not(uint32_t) - value.key;
2444 pkgProblemResolver *resolver = [database_ resolver];
2445 resolver->Clear(iterator_);
2446 resolver->Protect(iterator_);
2450 pkgProblemResolver *resolver = [database_ resolver];
2451 resolver->Clear(iterator_);
2452 resolver->Protect(iterator_);
2453 pkgCacheFile &cache([database_ cache]);
2454 cache->MarkInstall(iterator_, false);
2455 pkgDepCache::StateCache &state((*cache)[iterator_]);
2456 if (!state.Install())
2457 cache->SetReInstall(iterator_, true);
2461 pkgProblemResolver *resolver = [database_ resolver];
2462 resolver->Clear(iterator_);
2463 resolver->Protect(iterator_);
2464 resolver->Remove(iterator_);
2465 [database_ cache]->MarkDelete(iterator_, true);
2468 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2469 _profile(Package$isUnfilteredAndSearchedForBy)
2472 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2473 value &= [self unfiltered];
2476 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2477 value &= [self matches:search];
2484 - (bool) isInstalledAndVisible:(NSNumber *)number {
2485 return (![number boolValue] || [self visible]) && [self installed] != nil;
2488 - (bool) isVisiblyUninstalledInSection:(NSString *)name {
2489 NSString *section = [self section];
2493 [self installed] == nil && (
2495 section == nil && [name length] == 0 ||
2496 [name isEqualToString:section]
2500 - (bool) isVisibleInSource:(Source *)source {
2501 return [self source] == source && [self visible];
2506 /* Section Class {{{ */
2507 @interface Section : NSObject {
2512 NSString *localized_;
2515 - (NSComparisonResult) compareByName:(Section *)section;
2516 - (Section *) initWithName:(NSString *)name;
2517 - (Section *) initWithName:(NSString *)name row:(size_t)row;
2518 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2519 - (NSString *) name;
2526 - (void) addToCount;
2528 - (void) setCount:(size_t)count;
2532 @implementation Section
2536 if (localized_ != nil)
2537 [localized_ release];
2541 - (NSComparisonResult) compareByName:(Section *)section {
2542 NSString *lhs = [self name];
2543 NSString *rhs = [section name];
2545 if ([lhs length] != 0 && [rhs length] != 0) {
2546 unichar lhc = [lhs characterAtIndex:0];
2547 unichar rhc = [rhs characterAtIndex:0];
2549 if (isalpha(lhc) && !isalpha(rhc))
2550 return NSOrderedAscending;
2551 else if (!isalpha(lhc) && isalpha(rhc))
2552 return NSOrderedDescending;
2555 return [lhs compare:rhs options:LaxCompareOptions_];
2558 - (Section *) initWithName:(NSString *)name {
2559 return [self initWithName:name row:0];
2562 - (Section *) initWithName:(NSString *)name row:(size_t)row {
2563 if ((self = [super init]) != nil) {
2564 name_ = [name retain];
2567 localized_ = [LocalizeSection(name_) retain];
2571 /* XXX: localize the index thingees */
2572 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2573 if ((self = [super init]) != nil) {
2574 name_ = [(index == '#' ? @"123" : [NSString stringWithCharacters:&index length:1]) retain];
2580 - (NSString *) name {
2600 - (void) addToCount {
2604 - (void) setCount:(size_t)count {
2608 - (NSString *) localized {
2616 static NSArray *Finishes_;
2618 /* Database Implementation {{{ */
2619 @implementation Database
2621 + (Database *) sharedInstance {
2622 static Database *instance;
2623 if (instance == nil)
2624 instance = [[Database alloc] init];
2634 NSRecycleZone(zone_);
2635 // XXX: malloc_destroy_zone(zone_);
2636 apr_pool_destroy(pool_);
2640 - (void) _readCydia:(NSNumber *)fd { _pooled
2641 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2642 std::istream is(&ib);
2645 static Pcre finish_r("^finish:([^:]*)$");
2647 while (std::getline(is, line)) {
2648 const char *data(line.c_str());
2649 size_t size = line.size();
2650 lprintf("C:%s\n", data);
2652 if (finish_r(data, size)) {
2653 NSString *finish = finish_r[1];
2654 int index = [Finishes_ indexOfObject:finish];
2655 if (index != INT_MAX && index > Finish_)
2663 - (void) _readStatus:(NSNumber *)fd { _pooled
2664 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2665 std::istream is(&ib);
2668 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2669 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2671 while (std::getline(is, line)) {
2672 const char *data(line.c_str());
2673 size_t size = line.size();
2674 lprintf("S:%s\n", data);
2676 if (conffile_r(data, size)) {
2677 [delegate_ setConfigurationData:conffile_r[1]];
2678 } else if (strncmp(data, "status: ", 8) == 0) {
2679 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2680 [delegate_ setProgressTitle:string];
2681 } else if (pmstatus_r(data, size)) {
2682 std::string type([pmstatus_r[1] UTF8String]);
2683 NSString *id = pmstatus_r[2];
2685 float percent([pmstatus_r[3] floatValue]);
2686 [delegate_ setProgressPercent:(percent / 100)];
2688 NSString *string = pmstatus_r[4];
2690 if (type == "pmerror")
2691 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
2692 withObject:[NSArray arrayWithObjects:string, id, nil]
2695 else if (type == "pmstatus") {
2696 [delegate_ setProgressTitle:string];
2697 } else if (type == "pmconffile")
2698 [delegate_ setConfigurationData:string];
2699 else _assert(false);
2700 } else _assert(false);
2706 - (void) _readOutput:(NSNumber *)fd { _pooled
2707 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2708 std::istream is(&ib);
2711 while (std::getline(is, line)) {
2712 lprintf("O:%s\n", line.c_str());
2713 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
2723 - (Package *) packageWithName:(NSString *)name {
2724 if (static_cast<pkgDepCache *>(cache_) == NULL)
2726 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
2727 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
2730 - (Database *) init {
2731 if ((self = [super init]) != nil) {
2738 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
2739 apr_pool_create(&pool_, NULL);
2741 sources_ = [[NSMutableDictionary dictionaryWithCapacity:16] retain];
2742 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
2746 _assert(pipe(fds) != -1);
2749 _config->Set("APT::Keep-Fds::", cydiafd_);
2750 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
2753 detachNewThreadSelector:@selector(_readCydia:)
2755 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2758 _assert(pipe(fds) != -1);
2762 detachNewThreadSelector:@selector(_readStatus:)
2764 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2767 _assert(pipe(fds) != -1);
2768 _assert(dup2(fds[0], 0) != -1);
2769 _assert(close(fds[0]) != -1);
2771 input_ = fdopen(fds[1], "a");
2773 _assert(pipe(fds) != -1);
2774 _assert(dup2(fds[1], 1) != -1);
2775 _assert(close(fds[1]) != -1);
2778 detachNewThreadSelector:@selector(_readOutput:)
2780 withObject:[[NSNumber numberWithInt:fds[0]] retain]
2785 - (pkgCacheFile &) cache {
2789 - (pkgDepCache::Policy *) policy {
2793 - (pkgRecords *) records {
2797 - (pkgProblemResolver *) resolver {
2801 - (pkgAcquire &) fetcher {
2805 - (pkgSourceList &) list {
2809 - (NSArray *) packages {
2813 - (NSArray *) sources {
2814 return [sources_ allValues];
2817 - (NSArray *) issues {
2818 if (cache_->BrokenCount() == 0)
2821 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
2823 for (Package *package in packages_) {
2824 if (![package broken])
2826 pkgCache::PkgIterator pkg([package iterator]);
2828 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
2829 [entry addObject:[package name]];
2830 [issues addObject:entry];
2832 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
2836 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
2837 pkgCache::DepIterator start;
2838 pkgCache::DepIterator end;
2839 dep.GlobOr(start, end); // ++dep
2841 if (!cache_->IsImportantDep(end))
2843 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
2846 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
2847 [entry addObject:failure];
2848 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
2850 Package *package([self packageWithName:[NSString stringWithUTF8String:start.TargetPkg().Name()]]);
2851 [failure addObject:[package name]];
2853 pkgCache::PkgIterator target(start.TargetPkg());
2854 if (target->ProvidesList != 0)
2855 [failure addObject:@"?"];
2857 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
2859 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
2860 else if (!cache_[target].CandidateVerIter(cache_).end())
2861 [failure addObject:@"-"];
2862 else if (target->ProvidesList == 0)
2863 [failure addObject:@"!"];
2865 [failure addObject:@"%"];
2869 if (start.TargetVer() != 0)
2870 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
2881 - (void) reloadData { _pooled
2882 @synchronized (self) {
2904 apr_pool_clear(pool_);
2905 NSRecycleZone(zone_);
2907 int chk(creat("/tmp/cydia.chk", 0644));
2912 if (!cache_.Open(progress_, true)) {
2914 if (!_error->PopMessage(error))
2917 lprintf("cache_.Open():[%s]\n", error.c_str());
2919 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
2920 [delegate_ repairWithSelector:@selector(configure)];
2921 else if (error == "The package lists or status file could not be parsed or opened.")
2922 [delegate_ repairWithSelector:@selector(update)];
2923 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
2924 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
2925 // else if (error == "The list of sources could not be read.")
2926 else _assert(false);
2932 unlink("/tmp/cydia.chk");
2934 now_ = [[NSDate date] retain];
2936 policy_ = new pkgDepCache::Policy();
2937 records_ = new pkgRecords(cache_);
2938 resolver_ = new pkgProblemResolver(cache_);
2939 fetcher_ = new pkgAcquire(&status_);
2942 list_ = new pkgSourceList();
2943 _assert(list_->ReadMainList());
2945 _assert(cache_->DelCount() == 0 && cache_->InstCount() == 0);
2946 _assert(pkgApplyStatus(cache_));
2948 if (cache_->BrokenCount() != 0) {
2949 _assert(pkgFixBroken(cache_));
2950 _assert(cache_->BrokenCount() == 0);
2951 _assert(pkgMinimizeUpgrade(cache_));
2956 std::string lists(_config->FindDir("Dir::State::lists"));
2958 [sources_ removeAllObjects];
2959 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
2960 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
2961 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
2962 if (debPackagesIndex *packages = dynamic_cast<debPackagesIndex *>(*index))
2964 setObject:[[[Source alloc] initWithMetaIndex:*source] autorelease]
2965 forKey:[NSString stringWithFormat:@"%s%s",
2967 URItoFileName(packages->IndexURI("Packages")).c_str()
2974 [packages_ removeAllObjects];
2976 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
2977 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
2978 [packages_ addObject:package];
2980 [packages_ sortUsingSelector:@selector(compareByName:)];
2983 _config->Set("Acquire::http::Timeout", 15);
2984 _config->Set("Acquire::http::MaxParallel", 4);
2987 - (void) configure {
2988 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
2989 system([dpkg UTF8String]);
2997 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
2998 _assert(!_error->PendingError());
3001 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3004 public pkgArchiveCleaner
3007 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3012 if (!cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)) {
3014 while (_error->PopMessage(error))
3015 lprintf("ArchiveCleaner: %s\n", error.c_str());
3020 pkgRecords records(cache_);
3022 lock_ = new FileFd();
3023 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3024 _assert(!_error->PendingError());
3027 // XXX: explain this with an error message
3028 _assert(list.ReadMainList());
3030 manager_ = (_system->CreatePM(cache_));
3031 _assert(manager_->GetArchives(fetcher_, &list, &records));
3032 _assert(!_error->PendingError());
3036 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3038 _assert(list.ReadMainList());
3039 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3040 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3043 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3048 bool failed = false;
3049 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3050 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3053 std::string uri = (*item)->DescURI();
3054 std::string error = (*item)->ErrorText;
3056 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3059 [delegate_ performSelectorOnMainThread:@selector(_setProgressError:)
3060 withObject:[NSArray arrayWithObjects:
3061 [NSString stringWithUTF8String:error.c_str()],
3073 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3075 if (_error->PendingError()) {
3080 if (result == pkgPackageManager::Failed) {
3085 if (result != pkgPackageManager::Completed) {
3090 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3092 _assert(list.ReadMainList());
3093 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3094 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3097 if (![before isEqualToArray:after])
3102 _assert(pkgDistUpgrade(cache_));
3106 [self updateWithStatus:status_];
3109 - (void) updateWithStatus:(Status &)status {
3111 _assert(list.ReadMainList());
3114 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3115 _assert(!_error->PendingError());
3117 pkgAcquire fetcher(&status);
3118 _assert(list.GetIndexes(&fetcher));
3120 if (fetcher.Run(PulseInterval_) != pkgAcquire::Failed) {
3121 bool failed = false;
3122 for (pkgAcquire::ItemIterator item = fetcher.ItemsBegin(); item != fetcher.ItemsEnd(); item++)
3123 if ((*item)->Status != pkgAcquire::Item::StatDone) {
3124 (*item)->Finished();
3128 if (!failed && _config->FindB("APT::Get::List-Cleanup", true) == true) {
3129 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists")));
3130 _assert(fetcher.Clean(_config->FindDir("Dir::State::lists") + "partial/"));
3133 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3138 - (void) setDelegate:(id)delegate {
3139 delegate_ = delegate;
3140 status_.setDelegate(delegate);
3141 progress_.setDelegate(delegate);
3144 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3145 if (const char *name = file.FileName())
3146 if (Source *source = [sources_ objectForKey:[NSString stringWithUTF8String:name]])
3154 /* PopUp Windows {{{ */
3155 @interface PopUpView : UIView {
3156 _transient id delegate_;
3157 UITransitionView *transition_;
3162 - (id) initWithView:(UIView *)view delegate:(id)delegate;
3166 @implementation PopUpView
3169 [transition_ setDelegate:nil];
3170 [transition_ release];
3176 [transition_ transition:UITransitionPushFromTop toView:nil];
3179 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3180 if (from != nil && to == nil)
3181 [self removeFromSuperview];
3184 - (id) initWithView:(UIView *)view delegate:(id)delegate {
3185 if ((self = [super initWithFrame:[view bounds]]) != nil) {
3186 delegate_ = delegate;
3188 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3189 [self addSubview:transition_];
3191 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3193 [view addSubview:self];
3195 [transition_ setDelegate:self];
3197 UIView *blank = [[[UIView alloc] initWithFrame:[transition_ bounds]] autorelease];
3198 [transition_ transition:UITransitionNone toView:blank];
3199 [transition_ transition:UITransitionPushFromBottom toView:overlay_];
3207 /* Mail Composition {{{ */
3208 @interface MailToView : PopUpView {
3209 MailComposeController *controller_;
3212 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url;
3216 @implementation MailToView
3219 [controller_ release];
3223 - (void) mailComposeControllerWillAttemptToSend:(MailComposeController *)controller {
3227 - (void) mailComposeControllerDidAttemptToSend:(MailComposeController *)controller mailDelivery:(id)delivery {
3228 NSLog(@"did:%@", delivery);
3229 // [UIApp setStatusBarShowsProgress:NO];
3230 if ([controller error]){
3231 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3232 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3233 [mailAlertSheet setBodyText:[controller error]];
3234 [mailAlertSheet popupAlertAnimated:YES];
3238 - (void) showError {
3239 NSLog(@"%@", [controller_ error]);
3240 NSArray *buttons = [NSArray arrayWithObjects:CYLocalize("OK"), nil];
3241 UIActionSheet *mailAlertSheet = [[UIActionSheet alloc] initWithTitle:CYLocalize("ERROR") buttons:buttons defaultButtonIndex:0 delegate:self context:self];
3242 [mailAlertSheet setBodyText:[controller_ error]];
3243 [mailAlertSheet popupAlertAnimated:YES];
3246 - (void) deliverMessage { _pooled
3250 if (![controller_ deliverMessage])
3251 [self performSelectorOnMainThread:@selector(showError) withObject:nil waitUntilDone:NO];
3254 - (void) mailComposeControllerCompositionFinished:(MailComposeController *)controller {
3255 if ([controller_ needsDelivery])
3256 [NSThread detachNewThreadSelector:@selector(deliverMessage) toTarget:self withObject:nil];
3261 - (id) initWithView:(UIView *)view delegate:(id)delegate url:(NSURL *)url {
3262 if ((self = [super initWithView:view delegate:delegate]) != nil) {
3263 controller_ = [[MailComposeController alloc] initForContentSize:[overlay_ bounds].size];
3264 [controller_ setDelegate:self];
3265 [controller_ initializeUI];
3266 [controller_ setupForURL:url];
3268 UIView *view([controller_ view]);
3269 [overlay_ addSubview:view];
3277 /* Confirmation View {{{ */
3278 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3279 if (!iterator.end())
3280 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3281 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3283 pkgCache::PkgIterator package(dep.TargetPkg());
3286 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3293 @protocol ConfirmationViewDelegate
3299 @interface ConfirmationView : BrowserView {
3300 _transient Database *database_;
3301 UIActionSheet *essential_;
3308 - (id) initWithBook:(RVBook *)book database:(Database *)database;
3312 @implementation ConfirmationView
3319 if (essential_ != nil)
3320 [essential_ release];
3326 [book_ popFromSuperviewAnimated:YES];
3329 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3330 NSString *context([sheet context]);
3332 if ([context isEqualToString:@"remove"]) {
3340 [delegate_ confirm];
3347 } else if ([context isEqualToString:@"unable"]) {
3351 [super alertSheet:sheet buttonClicked:button];
3354 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3355 [super webView:sender didClearWindowObject:window forFrame:frame];
3356 [window setValue:changes_ forKey:@"changes"];
3357 [window setValue:issues_ forKey:@"issues"];
3358 [window setValue:sizes_ forKey:@"sizes"];
3361 - (id) initWithBook:(RVBook *)book database:(Database *)database {
3362 if ((self = [super initWithBook:book]) != nil) {
3363 database_ = database;
3365 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3366 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3367 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3368 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3369 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
3373 pkgDepCache::Policy *policy([database_ policy]);
3375 pkgCacheFile &cache([database_ cache]);
3376 NSArray *packages = [database_ packages];
3377 for (Package *package in packages) {
3378 pkgCache::PkgIterator iterator = [package iterator];
3379 pkgDepCache::StateCache &state(cache[iterator]);
3381 NSString *name([package name]);
3383 if (state.NewInstall())
3384 [installing addObject:name];
3385 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
3386 [reinstalling addObject:name];
3387 else if (state.Upgrade())
3388 [upgrading addObject:name];
3389 else if (state.Downgrade())
3390 [downgrading addObject:name];
3391 else if (state.Delete()) {
3392 if ([package essential])
3394 [removing addObject:name];
3397 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
3398 substrate_ |= DepSubstrate(iterator.CurrentVer());
3403 else if (Advanced_ || true) {
3404 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
3406 essential_ = [[UIActionSheet alloc]
3407 initWithTitle:CYLocalize("REMOVING_ESSENTIALS")
3408 buttons:[NSArray arrayWithObjects:
3409 [NSString stringWithFormat:parenthetical, CYLocalize("CANCEL_OPERATION"), CYLocalize("SAFE")],
3410 [NSString stringWithFormat:parenthetical, CYLocalize("FORCE_REMOVAL"), CYLocalize("UNSAFE")],
3412 defaultButtonIndex:0
3418 [essential_ setDestructiveButton:[[essential_ buttons] objectAtIndex:0]];
3420 [essential_ setBodyText:CYLocalize("REMOVING_ESSENTIALS_EX")];
3422 essential_ = [[UIActionSheet alloc]
3423 initWithTitle:CYLocalize("UNABLE_TO_COMPLY")
3424 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3425 defaultButtonIndex:0
3430 [essential_ setBodyText:CYLocalize("UNABLE_TO_COMPLY_EX")];
3433 changes_ = [[NSArray alloc] initWithObjects:
3441 issues_ = [database_ issues];
3443 issues_ = [issues_ retain];
3445 sizes_ = [[NSArray alloc] initWithObjects:
3446 SizeString([database_ fetcher].FetchNeeded()),
3447 SizeString([database_ fetcher].PartialPresent()),
3448 SizeString([database_ cache]->UsrSize()),
3451 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
3455 - (NSString *) backButtonTitle {
3456 return CYLocalize("CONFIRM");
3459 - (NSString *) leftButtonTitle {
3460 return [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("CANCEL"), CYLocalize("QUEUE")];
3463 - (id) rightButtonTitle {
3464 return issues_ != nil ? nil : [super rightButtonTitle];
3467 - (id) _rightButtonTitle {
3468 #if AlwaysReload || IgnoreInstall
3469 return [super _rightButtonTitle];
3471 return CYLocalize("CONFIRM");
3475 - (void) _leftButtonClicked {
3480 - (void) _rightButtonClicked {
3482 return [super _rightButtonClicked];
3484 if (essential_ != nil)
3485 [essential_ popupAlertAnimated:YES];
3489 [delegate_ confirm];
3497 /* Progress Data {{{ */
3498 @interface ProgressData : NSObject {
3504 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
3511 @implementation ProgressData
3513 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
3514 if ((self = [super init]) != nil) {
3515 selector_ = selector;
3535 /* Progress View {{{ */
3536 @interface ProgressView : UIView <
3537 ConfigurationDelegate,
3540 _transient Database *database_;
3542 UIView *background_;
3543 UITransitionView *transition_;
3545 UINavigationBar *navbar_;
3546 UIProgressBar *progress_;
3547 UITextView *output_;
3548 UITextLabel *status_;
3549 UIPushButton *close_;
3552 SHA1SumValue springlist_;
3553 SHA1SumValue notifyconf_;
3554 SHA1SumValue sandplate_;
3557 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to;
3559 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate;
3560 - (void) setContentView:(UIView *)view;
3563 - (void) _retachThread;
3564 - (void) _detachNewThreadData:(ProgressData *)data;
3565 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
3571 @protocol ProgressViewDelegate
3572 - (void) progressViewIsComplete:(ProgressView *)sender;
3575 @implementation ProgressView
3578 [transition_ setDelegate:nil];
3579 [navbar_ setDelegate:nil];
3582 if (background_ != nil)
3583 [background_ release];
3584 [transition_ release];
3587 [progress_ release];
3594 - (void) transitionViewDidComplete:(UITransitionView*)view fromView:(UIView*)from toView:(UIView*)to {
3595 if (bootstrap_ && from == overlay_ && to == view_)
3599 - (id) initWithFrame:(struct CGRect)frame database:(Database *)database delegate:(id)delegate {
3600 if ((self = [super initWithFrame:frame]) != nil) {
3601 database_ = database;
3602 delegate_ = delegate;
3604 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
3605 [transition_ setDelegate:self];
3607 overlay_ = [[UIView alloc] initWithFrame:[transition_ bounds]];
3610 [overlay_ setBackgroundColor:[UIColor blackColor]];
3612 background_ = [[UIView alloc] initWithFrame:[self bounds]];
3613 [background_ setBackgroundColor:[UIColor blackColor]];
3614 [self addSubview:background_];
3617 [self addSubview:transition_];
3619 CGSize navsize = [UINavigationBar defaultSize];
3620 CGRect navrect = {{0, 0}, navsize};
3622 navbar_ = [[UINavigationBar alloc] initWithFrame:navrect];
3623 [overlay_ addSubview:navbar_];
3625 [navbar_ setBarStyle:1];
3626 [navbar_ setDelegate:self];
3628 UINavigationItem *navitem = [[[UINavigationItem alloc] initWithTitle:nil] autorelease];
3629 [navbar_ pushNavigationItem:navitem];
3631 CGRect bounds = [overlay_ bounds];
3632 CGSize prgsize = [UIProgressBar defaultSize];
3635 (bounds.size.width - prgsize.width) / 2,
3636 bounds.size.height - prgsize.height - 20
3639 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
3640 [progress_ setStyle:0];
3642 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(
3644 bounds.size.height - prgsize.height - 50,
3645 bounds.size.width - 20,
3649 [status_ setColor:[UIColor whiteColor]];
3650 [status_ setBackgroundColor:[UIColor clearColor]];
3652 [status_ setCentersHorizontally:YES];
3653 //[status_ setFont:font];
3656 output_ = [[UITextView alloc] initWithFrame:CGRectMake(
3658 navrect.size.height + 20,
3659 bounds.size.width - 20,
3660 bounds.size.height - navsize.height - 62 - navrect.size.height
3664 //[output_ setTextFont:@"Courier New"];
3665 [output_ setTextSize:12];
3667 [output_ setTextColor:[UIColor whiteColor]];
3668 [output_ setBackgroundColor:[UIColor clearColor]];
3670 [output_ setMarginTop:0];
3671 [output_ setAllowsRubberBanding:YES];
3672 [output_ setEditable:NO];
3674 [overlay_ addSubview:output_];
3676 close_ = [[UIPushButton alloc] initWithFrame:CGRectMake(
3678 bounds.size.height - prgsize.height - 50,
3679 bounds.size.width - 20,
3683 [close_ setAutosizesToFit:NO];
3684 [close_ setDrawsShadow:YES];
3685 [close_ setStretchBackground:YES];
3686 [close_ setEnabled:YES];
3688 UIFont *bold = [UIFont boldSystemFontOfSize:22];
3689 [close_ setTitleFont:bold];
3691 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:kUIControlEventMouseUpInside];
3692 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
3693 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
3697 - (void) setContentView:(UIView *)view {
3698 view_ = [view retain];
3701 - (void) resetView {
3702 [transition_ transition:6 toView:view_];
3705 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
3706 NSString *context([sheet context]);
3708 if ([context isEqualToString:@"error"])
3710 else if ([context isEqualToString:@"conffile"]) {
3711 FILE *input = [database_ input];
3715 fprintf(input, "N\n");
3719 fprintf(input, "Y\n");
3730 - (void) closeButtonPushed {
3739 [delegate_ suspendWithAnimation:YES];
3743 system("launchctl stop com.apple.SpringBoard");
3747 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
3756 - (void) _retachThread {
3757 UINavigationItem *item = [navbar_ topItem];
3758 [item setTitle:CYLocalize("COMPLETE")];
3760 [overlay_ addSubview:close_];
3761 [progress_ removeFromSuperview];
3762 [status_ removeFromSuperview];
3764 [delegate_ progressViewIsComplete:self];
3767 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
3768 MMap mmap(file, MMap::ReadOnly);
3770 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3771 if (!(sandplate_ == sha1.Result()))
3776 FileFd file(NotifyConfig_, FileFd::ReadOnly);
3777 MMap mmap(file, MMap::ReadOnly);
3779 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3780 if (!(notifyconf_ == sha1.Result()))
3785 FileFd file(SpringBoard_, FileFd::ReadOnly);
3786 MMap mmap(file, MMap::ReadOnly);
3788 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3789 if (!(springlist_ == sha1.Result()))
3794 case 0: [close_ setTitle:CYLocalize("RETURN_TO_CYDIA")]; break;
3795 case 1: [close_ setTitle:CYLocalize("CLOSE_CYDIA")]; break;
3796 case 2: [close_ setTitle:CYLocalize("RESTART_SPRINGBOARD")]; break;
3797 case 3: [close_ setTitle:CYLocalize("RELOAD_SPRINGBOARD")]; break;
3798 case 4: [close_ setTitle:CYLocalize("REBOOT_DEVICE")]; break;
3801 #define Cache_ "/User/Library/Caches/com.apple.mobile.installation.plist"
3803 if (NSMutableDictionary *cache = [[NSMutableDictionary alloc] initWithContentsOfFile:@ Cache_]) {
3804 [cache autorelease];
3806 NSFileManager *manager = [NSFileManager defaultManager];
3807 NSError *error = nil;
3809 id system = [cache objectForKey:@"System"];
3814 if (stat(Cache_, &info) == -1)
3817 [system removeAllObjects];
3819 if (NSArray *apps = [manager contentsOfDirectoryAtPath:@"/Applications" error:&error]) {
3820 for (NSString *app in apps)
3821 if ([app hasSuffix:@".app"]) {
3822 NSString *path = [@"/Applications" stringByAppendingPathComponent:app];
3823 NSString *plist = [path stringByAppendingPathComponent:@"Info.plist"];
3824 if (NSMutableDictionary *info = [[NSMutableDictionary alloc] initWithContentsOfFile:plist]) {
3826 if ([info objectForKey:@"CFBundleIdentifier"] != nil) {
3827 [info setObject:path forKey:@"Path"];
3828 [info setObject:@"System" forKey:@"ApplicationType"];
3829 [system addInfoDictionary:info];
3835 [cache writeToFile:@Cache_ atomically:YES];
3837 if (chown(Cache_, info.st_uid, info.st_gid) == -1)
3839 if (chmod(Cache_, info.st_mode) == -1)
3843 lprintf("%s\n", error == nil ? strerror(errno) : [[error localizedDescription] UTF8String]);
3846 notify_post("com.apple.mobile.application_installed");
3848 [delegate_ setStatusBarShowsProgress:NO];
3851 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
3852 [[data target] performSelector:[data selector] withObject:[data object]];
3855 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
3858 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
3859 UINavigationItem *item = [navbar_ topItem];
3860 [item setTitle:title];
3862 [status_ setText:nil];
3863 [output_ setText:@""];
3864 [progress_ setProgress:0];
3866 [close_ removeFromSuperview];
3867 [overlay_ addSubview:progress_];
3868 [overlay_ addSubview:status_];
3870 [delegate_ setStatusBarShowsProgress:YES];
3874 FileFd file(SandboxTemplate_, FileFd::ReadOnly);
3875 MMap mmap(file, MMap::ReadOnly);
3877 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3878 sandplate_ = sha1.Result();
3882 FileFd file(NotifyConfig_, FileFd::ReadOnly);
3883 MMap mmap(file, MMap::ReadOnly);
3885 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3886 notifyconf_ = sha1.Result();
3890 FileFd file(SpringBoard_, FileFd::ReadOnly);
3891 MMap mmap(file, MMap::ReadOnly);
3893 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
3894 springlist_ = sha1.Result();
3897 [transition_ transition:6 toView:overlay_];
3900 detachNewThreadSelector:@selector(_detachNewThreadData:)
3902 withObject:[[ProgressData alloc]
3903 initWithSelector:selector
3910 - (void) repairWithSelector:(SEL)selector {
3912 detachNewThreadSelector:selector
3915 title:CYLocalize("REPAIRING")
3919 - (void) setConfigurationData:(NSString *)data {
3921 performSelectorOnMainThread:@selector(_setConfigurationData:)
3927 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
3928 Package *package = id == nil ? nil : [database_ packageWithName:id];
3930 UIActionSheet *sheet = [[[UIActionSheet alloc]
3931 initWithTitle:(package == nil ? id : [package name])
3932 buttons:[NSArray arrayWithObjects:CYLocalize("OKAY"), nil]
3933 defaultButtonIndex:0
3938 [sheet setBodyText:error];
3939 [sheet popupAlertAnimated:YES];
3942 - (void) setProgressTitle:(NSString *)title {
3944 performSelectorOnMainThread:@selector(_setProgressTitle:)
3950 - (void) setProgressPercent:(float)percent {
3952 performSelectorOnMainThread:@selector(_setProgressPercent:)
3953 withObject:[NSNumber numberWithFloat:percent]
3958 - (void) startProgress {
3961 - (void) addProgressOutput:(NSString *)output {
3963 performSelectorOnMainThread:@selector(_addProgressOutput:)
3969 - (bool) isCancelling:(size_t)received {
3973 - (void) _setConfigurationData:(NSString *)data {
3974 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
3976 _assert(conffile_r(data));
3978 NSString *ofile = conffile_r[1];
3979 //NSString *nfile = conffile_r[2];
3981 UIActionSheet *sheet = [[[UIActionSheet alloc]
3982 initWithTitle:CYLocalize("CONFIGURATION_UPGRADE")
3983 buttons:[NSArray arrayWithObjects:
3984 CYLocalize("KEEP_OLD_COPY"),
3985 CYLocalize("ACCEPT_NEW_COPY"),
3986 // XXX: CYLocalize("SEE_WHAT_CHANGED"),
3988 defaultButtonIndex:0
3993 [sheet setBodyText:[NSString stringWithFormat:@"%@\n\n%@", CYLocalize("CONFIGURATION_UPGRADE_EX"), ofile]];
3994 [sheet popupAlertAnimated:YES];
3997 - (void) _setProgressTitle:(NSString *)title {
3998 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
3999 for (size_t i(0), e([words count]); i != e; ++i) {
4000 NSString *word([words objectAtIndex:i]);
4001 if (Package *package = [database_ packageWithName:word])
4002 [words replaceObjectAtIndex:i withObject:[package name]];
4005 [status_ setText:[words componentsJoinedByString:@" "]];
4008 - (void) _setProgressPercent:(NSNumber *)percent {
4009 [progress_ setProgress:[percent floatValue]];
4012 - (void) _addProgressOutput:(NSString *)output {
4013 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4014 CGSize size = [output_ contentSize];
4015 CGRect rect = {{0, size.height}, {size.width, 0}};
4016 [output_ scrollRectToVisible:rect animated:YES];
4019 - (BOOL) isRunning {
4026 /* Package Cell {{{ */
4027 @interface PackageCell : UITableCell {
4030 NSString *description_;
4037 UITextLabel *status_;
4041 - (PackageCell *) init;
4042 - (void) setPackage:(Package *)package;
4044 + (int) heightForPackage:(Package *)package;
4048 @implementation PackageCell
4050 - (void) clearPackage {
4061 if (description_ != nil) {
4062 [description_ release];
4066 if (source_ != nil) {
4071 if (badge_ != nil) {
4081 [self clearPackage];
4088 - (PackageCell *) init {
4089 if ((self = [super init]) != nil) {
4091 status_ = [[UITextLabel alloc] initWithFrame:CGRectMake(48, 68, 280, 20)];
4092 [status_ setBackgroundColor:[UIColor clearColor]];
4093 [status_ setFont:small];
4098 - (void) setPackage:(Package *)package {
4099 [self clearPackage];
4101 Source *source = [package source];
4103 icon_ = [[package icon] retain];
4104 name_ = [[package name] retain];
4105 description_ = [[package tagline] retain];
4106 commercial_ = [package isCommercial];
4108 package_ = [package retain];
4110 NSString *label = nil;
4111 bool trusted = false;
4113 if (source != nil) {
4114 label = [source label];
4115 trusted = [source trusted];
4116 } else if ([[package id] isEqualToString:@"firmware"])
4117 label = CYLocalize("APPLE");
4119 label = [NSString stringWithFormat:CYLocalize("SLASH_DELIMITED"), CYLocalize("UNKNOWN"), CYLocalize("LOCAL")];
4121 NSString *from(label);
4123 NSString *section = [package simpleSection];
4124 if (section != nil && ![section isEqualToString:label]) {
4125 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4126 from = [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), from, section];
4129 from = [NSString stringWithFormat:CYLocalize("FROM"), from];
4130 source_ = [from retain];
4132 if (NSString *purpose = [package primaryPurpose])
4133 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4134 badge_ = [badge_ retain];
4137 if (NSString *mode = [package mode]) {
4138 [badge_ setImage:[UIImage applicationImageNamed:
4139 [mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"] ? @"removing.png" : @"installing.png"
4142 [status_ setText:[NSString stringWithFormat:CYLocalize("QUEUED_FOR"), CYLocalize(mode)]];
4143 [status_ setColor:[UIColor colorWithCGColor:Blueish_]];
4144 } else if ([package half]) {
4145 [badge_ setImage:[UIImage applicationImageNamed:@"damaged.png"]];
4146 [status_ setText:CYLocalize("PACKAGE_DAMAGED")];
4147 [status_ setColor:[UIColor redColor]];
4149 [badge_ setImage:nil];
4150 [status_ setText:nil];
4157 - (void) drawRect:(CGRect)rect {
4161 if (NSString *mode = [package_ mode]) {
4162 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4163 color = remove ? RemovingColor_ : InstallingColor_;
4165 color = [UIColor whiteColor];
4167 [self setBackgroundColor:color];
4171 [super drawRect:rect];
4174 - (void) drawBackgroundInRect:(CGRect)rect withFade:(float)fade {
4176 CGContextRef context(UIGraphicsGetCurrentContext());
4177 [[self backgroundColor] set];
4179 back.size.height -= 1;
4180 CGContextFillRect(context, back);
4183 [super drawBackgroundInRect:rect withFade:fade];
4186 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4189 rect.size = [icon_ size];
4191 rect.size.width /= 2;
4192 rect.size.height /= 2;
4194 rect.origin.x = 25 - rect.size.width / 2;
4195 rect.origin.y = 25 - rect.size.height / 2;
4197 [icon_ drawInRect:rect];
4200 if (badge_ != nil) {
4201 CGSize size = [badge_ size];
4203 [badge_ drawAtPoint:CGPointMake(
4204 36 - size.width / 2,
4205 36 - size.height / 2
4213 UISetColor(commercial_ ? Purple_ : Black_);
4214 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4215 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4218 UISetColor(commercial_ ? Purplish_ : Gray_);
4219 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4221 [super drawContentInRect:rect selected:selected];
4224 - (void) setSelected:(BOOL)selected withFade:(BOOL)fade {
4226 [super setSelected:selected withFade:fade];
4229 + (int) heightForPackage:(Package *)package {
4230 NSString *tagline([package tagline]);
4231 int height = tagline == nil || [tagline length] == 0 ? -17 : 0;
4233 if ([package hasMode] || [package half])
4242 /* Section Cell {{{ */
4243 @interface SectionCell : UISimpleTableCell {
4248 _UISwitchSlider *switch_;
4253 - (void) setSection:(Section *)section editing:(BOOL)editing;
4257 @implementation SectionCell
4259 - (void) clearSection {
4260 if (section_ != nil) {
4270 if (count_ != nil) {
4277 [self clearSection];
4284 if ((self = [super init]) != nil) {
4285 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4287 switch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4288 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:kUIControlEventMouseUpInside];
4292 - (void) onSwitch:(id)sender {
4293 NSMutableDictionary *metadata = [Sections_ objectForKey:section_];
4294 if (metadata == nil) {
4295 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4296 [Sections_ setObject:metadata forKey:section_];
4300 [metadata setObject:[NSNumber numberWithBool:([switch_ value] == 0)] forKey:@"Hidden"];
4303 - (void) setSection:(Section *)section editing:(BOOL)editing {
4304 if (editing != editing_) {
4306 [switch_ removeFromSuperview];
4308 [self addSubview:switch_];
4312 [self clearSection];
4314 if (section == nil) {
4315 name_ = [CYLocalize("ALL_PACKAGES") retain];
4318 section_ = [section name];
4319 if (section_ != nil)
4320 section_ = [section_ retain];
4321 name_ = [(section_ == nil ? CYLocalize("NO_SECTION") : section_) retain];
4322 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4325 [switch_ setValue:(isSectionVisible(section_) ? 1 : 0) animated:NO];
4329 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4330 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4337 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(editing_ ? 164 : 250) withFont:Font22Bold_ ellipsis:2];
4339 CGSize size = [count_ sizeWithFont:Font14_];
4343 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4345 [super drawContentInRect:rect selected:selected];
4351 /* File Table {{{ */
4352 @interface FileTable : RVPage {
4353 _transient Database *database_;
4356 NSMutableArray *files_;
4360 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4361 - (void) setPackage:(Package *)package;
4365 @implementation FileTable
4368 if (package_ != nil)
4377 - (int) numberOfRowsInTable:(UITable *)table {
4378 return files_ == nil ? 0 : [files_ count];
4381 - (float) table:(UITable *)table heightForRow:(int)row {
4385 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4386 if (reusing == nil) {
4387 reusing = [[[UIImageAndTextTableCell alloc] init] autorelease];
4388 UIFont *font = [UIFont systemFontOfSize:16];
4389 [[(UIImageAndTextTableCell *)reusing titleTextLabel] setFont:font];
4391 [(UIImageAndTextTableCell *)reusing setTitle:[files_ objectAtIndex:row]];
4395 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
4399 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4400 if ((self = [super initWithBook:book]) != nil) {
4401 database_ = database;
4403 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
4405 list_ = [[UITable alloc] initWithFrame:[self bounds]];
4406 [self addSubview:list_];
4408 UITableColumn *column = [[[UITableColumn alloc]
4409 initWithTitle:CYLocalize("NAME")
4411 width:[self frame].size.width
4414 [list_ setDataSource:self];
4415 [list_ setSeparatorStyle:1];
4416 [list_ addTableColumn:column];
4417 [list_ setDelegate:self];
4418 [list_ setReusesTableCells:YES];
4422 - (void) setPackage:(Package *)package {
4423 if (package_ != nil) {
4424 [package_ autorelease];
4433 [files_ removeAllObjects];
4435 if (package != nil) {
4436 package_ = [package retain];
4437 name_ = [[package id] retain];
4439 if (NSArray *files = [package files])
4440 [files_ addObjectsFromArray:files];
4442 if ([files_ count] != 0) {
4443 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
4444 [files_ removeObjectAtIndex:0];
4445 [files_ sortUsingSelector:@selector(compareByPath:)];
4447 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
4448 [stack addObject:@"/"];
4450 for (int i(0), e([files_ count]); i != e; ++i) {
4451 NSString *file = [files_ objectAtIndex:i];
4452 while (![file hasPrefix:[stack lastObject]])
4453 [stack removeLastObject];
4454 NSString *directory = [stack lastObject];
4455 [stack addObject:[file stringByAppendingString:@"/"]];
4456 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
4457 ([stack count] - 2) * 3, "",
4458 [file substringFromIndex:[directory length]]
4467 - (void) resetViewAnimated:(BOOL)animated {
4468 [list_ resetViewAnimated:animated];
4471 - (void) reloadData {
4472 [self setPackage:[database_ packageWithName:name_]];
4473 [self reloadButtons];
4476 - (NSString *) title {
4477 return CYLocalize("INSTALLED_FILES");
4480 - (NSString *) backButtonTitle {
4481 return CYLocalize("FILES");
4486 /* Package View {{{ */
4487 @interface PackageView : BrowserView {
4488 _transient Database *database_;
4492 NSMutableArray *buttons_;
4495 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4496 - (void) setPackage:(Package *)package;
4500 @implementation PackageView
4503 if (package_ != nil)
4512 if ([self retainCount] == 1)
4513 [delegate_ setPackageView:self];
4517 /* XXX: this is not safe at all... localization of /fail/ */
4518 - (void) _clickButtonWithName:(NSString *)name {
4519 if ([name isEqualToString:CYLocalize("CLEAR")])
4520 [delegate_ clearPackage:package_];
4521 else if ([name isEqualToString:CYLocalize("INSTALL")])
4522 [delegate_ installPackage:package_];
4523 else if ([name isEqualToString:CYLocalize("REINSTALL")])
4524 [delegate_ installPackage:package_];
4525 else if ([name isEqualToString:CYLocalize("REMOVE")])
4526 [delegate_ removePackage:package_];
4527 else if ([name isEqualToString:CYLocalize("UPGRADE")])
4528 [delegate_ installPackage:package_];
4529 else _assert(false);
4532 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
4533 NSString *context([sheet context]);
4535 if ([context isEqualToString:@"modify"]) {
4536 int count = [buttons_ count];
4537 _assert(count != 0);
4538 _assert(button <= count + 1);
4540 if (count != button - 1)
4541 [self _clickButtonWithName:[buttons_ objectAtIndex:(button - 1)]];
4545 [super alertSheet:sheet buttonClicked:button];
4548 - (void) webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
4549 return [super webView:sender didFinishLoadForFrame:frame];
4552 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4553 [super webView:sender didClearWindowObject:window forFrame:frame];
4554 [window setValue:package_ forKey:@"package"];
4557 - (bool) _allowJavaScriptPanel {
4562 - (void) __rightButtonClicked {
4563 int count = [buttons_ count];
4564 _assert(count != 0);
4567 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
4569 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:(count + 1)];
4570 [buttons addObjectsFromArray:buttons_];
4571 [buttons addObject:CYLocalize("CANCEL")];
4573 [delegate_ slideUp:[[[UIActionSheet alloc]
4576 defaultButtonIndex:([buttons count] - 1)
4583 - (void) _rightButtonClicked {
4585 [super _rightButtonClicked];
4587 [self __rightButtonClicked];
4591 - (id) _rightButtonTitle {
4592 int count = [buttons_ count];
4593 return count == 0 ? nil : count != 1 ? CYLocalize("MODIFY") : [buttons_ objectAtIndex:0];
4596 - (NSString *) backButtonTitle {
4600 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4601 if ((self = [super initWithBook:book]) != nil) {
4602 database_ = database;
4603 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
4604 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
4608 - (void) setPackage:(Package *)package {
4609 if (package_ != nil) {
4610 [package_ autorelease];
4619 [buttons_ removeAllObjects];
4621 if (package != nil) {
4622 package_ = [package retain];
4623 name_ = [[package id] retain];
4624 commercial_ = [package isCommercial];
4626 if ([package_ mode] != nil)
4627 [buttons_ addObject:CYLocalize("CLEAR")];
4628 if ([package_ source] == nil);
4629 else if ([package_ upgradableAndEssential:NO])
4630 [buttons_ addObject:CYLocalize("UPGRADE")];
4631 else if ([package_ installed] == nil)
4632 [buttons_ addObject:CYLocalize("INSTALL")];
4634 [buttons_ addObject:CYLocalize("REINSTALL")];
4635 if ([package_ installed] != nil)
4636 [buttons_ addObject:CYLocalize("REMOVE")];
4638 if (special_ != NULL) {
4639 CGRect frame([webview_ frame]);
4640 frame.size.width = 320;
4641 frame.size.height = 0;
4642 [webview_ setFrame:frame];
4644 [scroller_ scrollPointVisibleAtTopLeft:CGPointZero];
4647 [[[webview_ webView] windowScriptObject] setValue:package_ forKey:@"package"];
4649 [self setButtonTitle:nil withStyle:nil toFunction:nil];
4651 [self setFinishHook:nil];
4652 [self setPopupHook:nil];
4655 [super callFunction:special_];
4659 [self reloadButtons];
4662 - (bool) isLoading {
4663 return commercial_ ? [super isLoading] : false;
4666 - (void) reloadData {
4667 [self setPackage:[database_ packageWithName:name_]];
4672 /* Package Table {{{ */
4673 @interface PackageTable : RVPage {
4674 _transient Database *database_;
4676 NSMutableArray *packages_;
4677 NSMutableArray *sections_;
4678 UISectionList *list_;
4681 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title;
4683 - (void) setDelegate:(id)delegate;
4685 - (void) reloadData;
4686 - (void) resetCursor;
4688 - (UISectionList *) list;
4690 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
4694 @implementation PackageTable
4697 [list_ setDataSource:nil];
4700 [packages_ release];
4701 [sections_ release];
4706 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
4707 return [sections_ count];
4710 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
4711 return [[sections_ objectAtIndex:section] name];
4714 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
4715 return [[sections_ objectAtIndex:section] row];
4718 - (int) numberOfRowsInTable:(UITable *)table {
4719 return [packages_ count];
4722 - (float) table:(UITable *)table heightForRow:(int)row {
4723 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
4726 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
4728 reusing = [[[PackageCell alloc] init] autorelease];
4729 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
4733 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
4737 - (void) tableRowSelected:(NSNotification *)notification {
4738 int row = [[notification object] selectedRow];
4742 Package *package = [packages_ objectAtIndex:row];
4743 package = [database_ packageWithName:[package id]];
4744 PackageView *view([delegate_ packageView]);
4745 [view setPackage:package];
4746 [view setDelegate:delegate_];
4747 [book_ pushPage:view];
4750 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title {
4751 if ((self = [super initWithBook:book]) != nil) {
4752 database_ = database;
4753 title_ = [title retain];
4755 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
4756 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
4758 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:YES];
4759 [list_ setDataSource:self];
4761 UITableColumn *column = [[[UITableColumn alloc]
4762 initWithTitle:CYLocalize("NAME")
4764 width:[self frame].size.width
4767 UITable *table = [list_ table];
4768 [table setSeparatorStyle:1];
4769 [table addTableColumn:column];
4770 [table setDelegate:self];
4771 [table setReusesTableCells:YES];
4773 [self addSubview:list_];
4775 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
4776 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
4780 - (void) setDelegate:(id)delegate {
4781 delegate_ = delegate;
4784 - (bool) hasPackage:(Package *)package {
4788 - (void) reloadData {
4789 NSArray *packages = [database_ packages];
4791 [packages_ removeAllObjects];
4792 [sections_ removeAllObjects];
4794 _profile(PackageTable$reloadData$Filter)
4795 for (Package *package in packages)
4796 if ([self hasPackage:package])
4797 [packages_ addObject:package];
4800 Section *section = nil;
4802 _profile(PackageTable$reloadData$Section)
4803 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
4807 _profile(PackageTable$reloadData$Section$Package)
4808 package = [packages_ objectAtIndex:offset];
4809 index = [package index];
4812 if (section == nil || [section index] != index) {
4813 _profile(PackageTable$reloadData$Section$Allocate)
4814 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
4817 _profile(PackageTable$reloadData$Section$Add)
4818 [sections_ addObject:section];
4822 [section addToCount];
4826 _profile(PackageTable$reloadData$List)
4831 - (NSString *) title {
4835 - (void) resetViewAnimated:(BOOL)animated {
4836 [list_ resetViewAnimated:animated];
4839 - (void) resetCursor {
4840 [[list_ table] scrollPointVisibleAtTopLeft:CGPointMake(0, 0) animated:NO];
4843 - (UISectionList *) list {
4847 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
4848 [list_ setShouldHideHeaderInShortLists:hide];
4853 /* Filtered Package Table {{{ */
4854 @interface FilteredPackageTable : PackageTable {
4860 - (void) setObject:(id)object;
4862 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
4866 @implementation FilteredPackageTable
4874 - (void) setObject:(id)object {
4880 object_ = [object retain];
4883 - (bool) hasPackage:(Package *)package {
4884 _profile(FilteredPackageTable$hasPackage)
4885 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
4889 - (id) initWithBook:(RVBook *)book database:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
4890 if ((self = [super initWithBook:book database:database title:title]) != nil) {
4892 object_ = object == nil ? nil : [object retain];
4894 /* XXX: this is an unsafe optimization of doomy hell */
4895 Method method = class_getInstanceMethod([Package class], filter);
4896 imp_ = method_getImplementation(method);
4897 _assert(imp_ != NULL);
4906 /* Add Source View {{{ */
4907 @interface AddSourceView : RVPage {
4908 _transient Database *database_;
4911 - (id) initWithBook:(RVBook *)book database:(Database *)database;
4915 @implementation AddSourceView
4917 - (id) initWithBook:(RVBook *)book database:(Database *)database {
4918 if ((self = [super initWithBook:book]) != nil) {
4919 database_ = database;
4925 /* Source Cell {{{ */
4926 @interface SourceCell : UITableCell {
4929 NSString *description_;
4935 - (SourceCell *) initWithSource:(Source *)source;
4939 @implementation SourceCell
4944 [description_ release];
4949 - (SourceCell *) initWithSource:(Source *)source {
4950 if ((self = [super init]) != nil) {
4952 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
4954 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
4955 icon_ = [icon_ retain];
4957 origin_ = [[source name] retain];
4958 label_ = [[source uri] retain];
4959 description_ = [[source description] retain];
4963 - (void) drawContentInRect:(CGRect)rect selected:(BOOL)selected {
4965 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
4972 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:240 withFont:Font18Bold_ ellipsis:2];
4976 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:225 withFont:Font12_ ellipsis:2];
4980 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:280 withFont:Font14_ ellipsis:2];
4982 [super drawContentInRect:rect selected:selected];
4987 /* Source Table {{{ */
4988 @interface SourceTable : RVPage {
4989 _transient Database *database_;
4990 UISectionList *list_;
4991 NSMutableArray *sources_;
4992 UIActionSheet *alert_;
4996 UIProgressHUD *hud_;
4999 //NSURLConnection *installer_;
5000 NSURLConnection *trivial_bz2_;
5001 NSURLConnection *trivial_gz_;
5002 //NSURLConnection *automatic_;
5007 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5011 @implementation SourceTable
5013 - (void) _deallocConnection:(NSURLConnection *)connection {
5014 if (connection != nil) {
5015 [connection cancel];
5016 //[connection setDelegate:nil];
5017 [connection release];
5022 [[list_ table] setDelegate:nil];
5023 [list_ setDataSource:nil];
5032 //[self _deallocConnection:installer_];
5033 [self _deallocConnection:trivial_gz_];
5034 [self _deallocConnection:trivial_bz2_];
5035 //[self _deallocConnection:automatic_];
5042 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
5043 return offset_ == 0 ? 1 : 2;
5046 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
5047 switch (section + (offset_ == 0 ? 1 : 0)) {
5048 case 0: return CYLocalize("ENTERED_BY_USER");
5049 case 1: return CYLocalize("INSTALLED_BY_PACKAGE");
5057 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
5058 switch (section + (offset_ == 0 ? 1 : 0)) {
5060 case 1: return offset_;
5068 - (int) numberOfRowsInTable:(UITable *)table {
5069 return [sources_ count];
5072 - (float) table:(UITable *)table heightForRow:(int)row {
5073 Source *source = [sources_ objectAtIndex:row];
5074 return [source description] == nil ? 56 : 73;
5077 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col {
5078 Source *source = [sources_ objectAtIndex:row];
5079 // XXX: weird warning, stupid selectors ;P
5080 return [[[SourceCell alloc] initWithSource:(id)source] autorelease];
5083 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
5087 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
5091 - (void) tableRowSelected:(NSNotification*)notification {
5092 UITable *table([list_ table]);
5093 int row([table selectedRow]);
5097 Source *source = [sources_ objectAtIndex:row];
5099 PackageTable *packages = [[[FilteredPackageTable alloc]
5102 title:[source label]
5103 filter:@selector(isVisibleInSource:)
5107 [packages setDelegate:delegate_];
5109 [book_ pushPage:packages];
5112 - (BOOL) table:(UITable *)table canDeleteRow:(int)row {
5113 Source *source = [sources_ objectAtIndex:row];
5114 return [source record] != nil;
5117 - (void) table:(UITable *)table willSwipeToDeleteRow:(int)row {
5118 [[list_ table] setDeleteConfirmationRow:row];
5121 - (void) table:(UITable *)table deleteRow:(int)row {
5122 Source *source = [sources_ objectAtIndex:row];
5123 [Sources_ removeObjectForKey:[source key]];
5124 [delegate_ syncData];
5128 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5131 @"./", @"Distribution",
5132 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5134 [delegate_ syncData];
5137 - (NSString *) getWarning {
5138 NSString *href(href_);
5139 NSRange colon([href rangeOfString:@"://"]);
5140 if (colon.location != NSNotFound)
5141 href = [href substringFromIndex:(colon.location + 3)];
5142 href = [href stringByAddingPercentEscapes];
5143 href = [@"http://cydia.saurik.com/api/repotag/" stringByAppendingString:href];
5144 href = [href stringByCachingURLWithCurrentCDN];
5146 NSURL *url([NSURL URLWithString:href]);
5148 NSStringEncoding encoding;
5149 NSError *error(nil);
5151 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5152 return [warning length] == 0 ? nil : warning;
5156 - (void) _endConnection:(NSURLConnection *)connection {
5157 NSURLConnection **field = NULL;
5158 if (connection == trivial_bz2_)
5159 field = &trivial_bz2_;
5160 else if (connection == trivial_gz_)
5161 field = &trivial_gz_;
5162 _assert(field != NULL);
5163 [connection release];
5167 trivial_bz2_ == nil &&
5173 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5176 UIActionSheet *sheet = [[[UIActionSheet alloc]
5177 initWithTitle:CYLocalize("SOURCE_WARNING")
5178 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_ANYWAY"), CYLocalize("CANCEL"), nil]
5179 defaultButtonIndex:0
5184 [sheet setNumberOfRows:1];
5186 [sheet setBodyText:warning];
5187 [sheet popupAlertAnimated:YES];
5190 } else if (error_ != nil) {
5191 UIActionSheet *sheet = [[[UIActionSheet alloc]
5192 initWithTitle:CYLocalize("VERIFICATION_ERROR")
5193 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5194 defaultButtonIndex:0
5199 [sheet setBodyText:[error_ localizedDescription]];
5200 [sheet popupAlertAnimated:YES];
5202 UIActionSheet *sheet = [[[UIActionSheet alloc]
5203 initWithTitle:CYLocalize("NOT_REPOSITORY")
5204 buttons:[NSArray arrayWithObjects:CYLocalize("OK"), nil]
5205 defaultButtonIndex:0
5210 [sheet setBodyText:CYLocalize("NOT_REPOSITORY_EX")];
5211 [sheet popupAlertAnimated:YES];
5214 [delegate_ setStatusBarShowsProgress:NO];
5215 [delegate_ removeProgressHUD:hud_];
5225 if (error_ != nil) {
5232 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5233 switch ([response statusCode]) {
5239 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5240 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
5242 error_ = [error retain];
5243 [self _endConnection:connection];
5246 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
5247 [self _endConnection:connection];
5250 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
5251 NSMutableURLRequest *request = [NSMutableURLRequest
5252 requestWithURL:[NSURL URLWithString:href]
5253 cachePolicy:NSURLRequestUseProtocolCachePolicy
5254 timeoutInterval:20.0
5257 [request setHTTPMethod:method];
5259 if (Machine_ != NULL)
5260 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5261 if (UniqueID_ != nil)
5262 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5265 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
5267 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
5270 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5271 NSString *context([sheet context]);
5273 if ([context isEqualToString:@"source"]) {
5276 NSString *href = [[sheet textField] text];
5278 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
5280 if (![href hasSuffix:@"/"])
5281 href_ = [href stringByAppendingString:@"/"];
5284 href_ = [href_ retain];
5286 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
5287 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
5288 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
5292 hud_ = [[delegate_ addProgressHUD] retain];
5293 [hud_ setText:CYLocalize("VERIFYING_URL")];
5304 } else if ([context isEqualToString:@"trivial"])
5306 else if ([context isEqualToString:@"urlerror"])
5308 else if ([context isEqualToString:@"warning"]) {
5328 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5329 if ((self = [super initWithBook:book]) != nil) {
5330 database_ = database;
5331 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
5333 //list_ = [[UITable alloc] initWithFrame:[self bounds]];
5334 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
5335 [list_ setShouldHideHeaderInShortLists:NO];
5337 [self addSubview:list_];
5338 [list_ setDataSource:self];
5340 UITableColumn *column = [[UITableColumn alloc]
5341 initWithTitle:CYLocalize("NAME")
5343 width:[self frame].size.width
5346 UITable *table = [list_ table];
5347 [table setSeparatorStyle:1];
5348 [table addTableColumn:column];
5349 [table setDelegate:self];
5353 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5354 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5358 - (void) reloadData {
5360 _assert(list.ReadMainList());
5362 [sources_ removeAllObjects];
5363 [sources_ addObjectsFromArray:[database_ sources]];
5365 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
5368 int count = [sources_ count];
5369 for (offset_ = 0; offset_ != count; ++offset_) {
5370 Source *source = [sources_ objectAtIndex:offset_];
5371 if ([source record] == nil)
5378 - (void) resetViewAnimated:(BOOL)animated {
5379 [list_ resetViewAnimated:animated];
5382 - (void) _leftButtonClicked {
5383 /*[book_ pushPage:[[[AddSourceView alloc]
5388 UIActionSheet *sheet = [[[UIActionSheet alloc]
5389 initWithTitle:CYLocalize("ENTER_APT_URL")
5390 buttons:[NSArray arrayWithObjects:CYLocalize("ADD_SOURCE"), CYLocalize("CANCEL"), nil]
5391 defaultButtonIndex:0
5396 [sheet setNumberOfRows:1];
5398 [sheet addTextFieldWithValue:@"http://" label:@""];
5400 UITextInputTraits *traits = [[sheet textField] textInputTraits];
5401 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
5402 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
5403 [traits setKeyboardType:UIKeyboardTypeURL];
5404 // XXX: UIReturnKeyDone
5405 [traits setReturnKeyType:UIReturnKeyNext];
5407 [sheet popupAlertAnimated:YES];
5410 - (void) _rightButtonClicked {
5411 UITable *table = [list_ table];
5412 BOOL editing = [table isRowDeletionEnabled];
5413 [table enableRowDeletion:!editing animated:YES];
5414 [book_ reloadButtonsForPage:self];
5417 - (NSString *) title {
5418 return CYLocalize("SOURCES");
5421 - (NSString *) leftButtonTitle {
5422 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("ADD") : nil;
5425 - (id) rightButtonTitle {
5426 return [[list_ table] isRowDeletionEnabled] ? CYLocalize("DONE") : CYLocalize("EDIT");
5429 - (UINavigationButtonStyle) rightButtonStyle {
5430 return [[list_ table] isRowDeletionEnabled] ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5436 /* Installed View {{{ */
5437 @interface InstalledView : RVPage {
5438 _transient Database *database_;
5439 FilteredPackageTable *packages_;
5443 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5447 @implementation InstalledView
5450 [packages_ release];
5454 - (id) initWithBook:(RVBook *)book database:(Database *)database {
5455 if ((self = [super initWithBook:book]) != nil) {
5456 database_ = database;
5458 packages_ = [[FilteredPackageTable alloc]
5462 filter:@selector(isInstalledAndVisible:)
5463 with:[NSNumber numberWithBool:YES]
5466 [self addSubview:packages_];
5468 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5469 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
5473 - (void) resetViewAnimated:(BOOL)animated {
5474 [packages_ resetViewAnimated:animated];
5477 - (void) reloadData {
5478 [packages_ reloadData];
5481 - (void) _rightButtonClicked {
5482 [packages_ setObject:[NSNumber numberWithBool:expert_]];
5483 [packages_ reloadData];
5485 [book_ reloadButtonsForPage:self];
5488 - (NSString *) title {
5489 return CYLocalize("INSTALLED");
5492 - (NSString *) backButtonTitle {
5493 return CYLocalize("PACKAGES");
5496 - (id) rightButtonTitle {
5497 return Role_ != nil && [Role_ isEqualToString:@"Developer"] ? nil : expert_ ? CYLocalize("EXPERT") : CYLocalize("SIMPLE");
5500 - (UINavigationButtonStyle) rightButtonStyle {
5501 return expert_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5504 - (void) setDelegate:(id)delegate {
5505 [super setDelegate:delegate];
5506 [packages_ setDelegate:delegate];
5513 @interface HomeView : BrowserView {
5518 @implementation HomeView
5520 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5521 NSString *context([sheet context]);
5523 if ([context isEqualToString:@"about"])
5526 [super alertSheet:sheet buttonClicked:button];
5529 - (void) _leftButtonClicked {
5530 UIActionSheet *sheet = [[[UIActionSheet alloc]
5531 initWithTitle:CYLocalize("ABOUT_CYDIA")
5532 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
5533 defaultButtonIndex:0
5539 @"Copyright (C) 2008-2009\n"
5540 "Jay Freeman (saurik)\n"
5541 "saurik@saurik.com\n"
5542 "http://www.saurik.com/\n"
5545 "http://www.theokorigroup.com/\n"
5547 "College of Creative Studies,\n"
5548 "University of California,\n"
5550 "http://www.ccs.ucsb.edu/"
5553 [sheet popupAlertAnimated:YES];
5556 - (NSString *) leftButtonTitle {
5557 return CYLocalize("ABOUT");
5562 /* Manage View {{{ */
5563 @interface ManageView : BrowserView {
5568 @implementation ManageView
5570 - (NSString *) title {
5571 return CYLocalize("MANAGE");
5574 - (void) _leftButtonClicked {
5575 [delegate_ askForSettings];
5578 - (NSString *) leftButtonTitle {
5579 return CYLocalize("SETTINGS");
5583 - (id) _rightButtonTitle {
5584 return Queuing_ ? CYLocalize("QUEUE") : nil;
5587 - (UINavigationButtonStyle) rightButtonStyle {
5588 return Queuing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
5591 - (void) _rightButtonClicked {
5596 - (bool) isLoading {
5603 #include <BrowserView.m>
5605 /* Cydia Book {{{ */
5606 @interface CYBook : RVBook <
5609 _transient Database *database_;
5610 UINavigationBar *overlay_;
5611 UINavigationBar *underlay_;
5612 UIProgressIndicator *indicator_;
5613 UITextLabel *prompt_;
5614 UIProgressBar *progress_;
5615 UINavigationButton *cancel_;
5619 - (id) initWithFrame:(CGRect)frame database:(Database *)database;
5625 @implementation CYBook
5629 [indicator_ release];
5631 [progress_ release];
5636 - (NSString *) getTitleForPage:(RVPage *)page {
5637 return [super getTitleForPage:page];
5645 [UIView beginAnimations:nil context:NULL];
5647 CGRect ovrframe = [overlay_ frame];
5648 ovrframe.origin.y = 0;
5649 [overlay_ setFrame:ovrframe];
5651 CGRect barframe = [navbar_ frame];
5652 barframe.origin.y += ovrframe.size.height;
5653 [navbar_ setFrame:barframe];
5655 CGRect trnframe = [transition_ frame];
5656 trnframe.origin.y += ovrframe.size.height;
5657 trnframe.size.height -= ovrframe.size.height;
5658 [transition_ setFrame:trnframe];
5660 [UIView endAnimations];
5662 [indicator_ startAnimation];
5663 [prompt_ setText:CYLocalize("UPDATING_DATABASE")];
5664 [progress_ setProgress:0];
5667 [overlay_ addSubview:cancel_];
5670 detachNewThreadSelector:@selector(_update)
5679 [indicator_ stopAnimation];
5681 [UIView beginAnimations:nil context:NULL];
5683 CGRect ovrframe = [overlay_ frame];
5684 ovrframe.origin.y = -ovrframe.size.height;
5685 [overlay_ setFrame:ovrframe];
5687 CGRect barframe = [navbar_ frame];
5688 barframe.origin.y -= ovrframe.size.height;
5689 [navbar_ setFrame:barframe];
5691 CGRect trnframe = [transition_ frame];
5692 trnframe.origin.y -= ovrframe.size.height;
5693 trnframe.size.height += ovrframe.size.height;
5694 [transition_ setFrame:trnframe];
5696 [UIView commitAnimations];
5698 [delegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
5701 - (id) initWithFrame:(CGRect)frame database:(Database *)database {
5702 if ((self = [super initWithFrame:frame]) != nil) {
5703 database_ = database;
5705 CGRect ovrrect = [navbar_ bounds];
5706 ovrrect.size.height = [UINavigationBar defaultSize].height;
5707 ovrrect.origin.y = -ovrrect.size.height;
5709 overlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5710 [self addSubview:overlay_];
5712 ovrrect.origin.y = frame.size.height;
5713 underlay_ = [[UINavigationBar alloc] initWithFrame:ovrrect];
5714 [underlay_ setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
5715 [self addSubview:underlay_];
5717 [overlay_ setBarStyle:1];
5718 [underlay_ setBarStyle:1];
5720 int barstyle = [overlay_ _barStyle:NO];
5721 bool ugly = barstyle == 0;
5723 UIProgressIndicatorStyle style = ugly ?
5724 UIProgressIndicatorStyleMediumBrown :
5725 UIProgressIndicatorStyleMediumWhite;
5727 CGSize indsize = [UIProgressIndicator defaultSizeForStyle:style];
5728 unsigned indoffset = (ovrrect.size.height - indsize.height) / 2;
5729 CGRect indrect = {{indoffset, indoffset}, indsize};
5731 indicator_ = [[UIProgressIndicator alloc] initWithFrame:indrect];
5732 [indicator_ setStyle:style];
5733 [overlay_ addSubview:indicator_];
5735 CGSize prmsize = {215, indsize.height + 4};
5738 indoffset * 2 + indsize.width,
5742 unsigned(ovrrect.size.height - prmsize.height) / 2
5745 UIFont *font = [UIFont systemFontOfSize:15];
5747 prompt_ = [[UITextLabel alloc] initWithFrame:prmrect];
5749 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
5750 [prompt_ setBackgroundColor:[UIColor clearColor]];
5751 [prompt_ setFont:font];
5753 [overlay_ addSubview:prompt_];
5755 CGSize prgsize = {75, 100};
5758 ovrrect.size.width - prgsize.width - 10,
5759 (ovrrect.size.height - prgsize.height) / 2
5762 progress_ = [[UIProgressBar alloc] initWithFrame:prgrect];
5763 [progress_ setStyle:0];
5764 [overlay_ addSubview:progress_];
5766 cancel_ = [[UINavigationButton alloc] initWithTitle:CYLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
5767 [cancel_ addTarget:self action:@selector(_onCancel) forControlEvents:UIControlEventTouchUpInside];
5769 CGRect frame = [cancel_ frame];
5770 frame.size.width = 65;
5771 frame.origin.x = ovrrect.size.width - frame.size.width - 5;
5772 frame.origin.y = (ovrrect.size.height - frame.size.height) / 2;
5773 [cancel_ setFrame:frame];
5775 [cancel_ setBarStyle:barstyle];
5779 - (void) _onCancel {
5781 [cancel_ removeFromSuperview];
5784 - (void) _update { _pooled
5786 status.setDelegate(self);
5788 [database_ updateWithStatus:status];
5791 performSelectorOnMainThread:@selector(_update_)
5797 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
5798 [prompt_ setText:[NSString stringWithFormat:CYLocalize("ERROR_MESSAGE"), error]];
5801 - (void) setProgressTitle:(NSString *)title {
5803 performSelectorOnMainThread:@selector(_setProgressTitle:)
5809 - (void) setProgressPercent:(float)percent {
5811 performSelectorOnMainThread:@selector(_setProgressPercent:)
5812 withObject:[NSNumber numberWithFloat:percent]
5817 - (void) startProgress {
5820 - (void) addProgressOutput:(NSString *)output {
5822 performSelectorOnMainThread:@selector(_addProgressOutput:)
5828 - (bool) isCancelling:(size_t)received {
5832 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
5836 - (void) _setProgressTitle:(NSString *)title {
5837 [prompt_ setText:title];
5840 - (void) _setProgressPercent:(NSNumber *)percent {
5841 [progress_ setProgress:[percent floatValue]];
5844 - (void) _addProgressOutput:(NSString *)output {
5849 /* Cydia:// Protocol {{{ */
5850 @interface CydiaURLProtocol : NSURLProtocol {
5855 @implementation CydiaURLProtocol
5857 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
5858 NSURL *url([request URL]);
5861 NSString *scheme([[url scheme] lowercaseString]);
5862 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
5867 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
5871 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
5872 id<NSURLProtocolClient> client([self client]);
5874 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
5876 NSData *data(UIImagePNGRepresentation(icon));
5878 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
5879 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
5880 [client URLProtocol:self didLoadData:data];
5881 [client URLProtocolDidFinishLoading:self];
5885 - (void) startLoading {
5886 id<NSURLProtocolClient> client([self client]);
5887 NSURLRequest *request([self request]);
5889 NSURL *url([request URL]);
5890 NSString *href([url absoluteString]);
5892 NSString *path([href substringFromIndex:8]);
5893 NSRange slash([path rangeOfString:@"/"]);
5896 if (slash.location == NSNotFound) {
5900 command = [path substringToIndex:slash.location];
5901 path = [path substringFromIndex:(slash.location + 1)];
5904 Database *database([Database sharedInstance]);
5906 if ([command isEqualToString:@"package-icon"]) {
5909 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5910 Package *package([database packageWithName:path]);
5913 UIImage *icon([package icon]);
5914 [self _returnPNGWithImage:icon forRequest:request];
5915 } else if ([command isEqualToString:@"source-icon"]) {
5918 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5919 NSString *source(Simplify(path));
5920 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
5922 icon = [UIImage applicationImageNamed:@"unknown.png"];
5923 [self _returnPNGWithImage:icon forRequest:request];
5924 } else if ([command isEqualToString:@"uikit-image"]) {
5927 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5928 UIImage *icon(_UIImageWithName(path));
5929 [self _returnPNGWithImage:icon forRequest:request];
5930 } else if ([command isEqualToString:@"section-icon"]) {
5933 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5934 NSString *section(Simplify(path));
5935 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
5937 icon = [UIImage applicationImageNamed:@"unknown.png"];
5938 [self _returnPNGWithImage:icon forRequest:request];
5940 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
5944 - (void) stopLoading {
5950 /* Sections View {{{ */
5951 @interface SectionsView : RVPage {
5952 _transient Database *database_;
5953 NSMutableArray *sections_;
5954 NSMutableArray *filtered_;
5955 UITransitionView *transition_;
5961 - (id) initWithBook:(RVBook *)book database:(Database *)database;
5962 - (void) reloadData;
5967 @implementation SectionsView
5970 [list_ setDataSource:nil];
5971 [list_ setDelegate:nil];
5973 [sections_ release];
5974 [filtered_ release];
5975 [transition_ release];
5977 [accessory_ release];
5981 - (int) numberOfRowsInTable:(UITable *)table {
5982 return editing_ ? [sections_ count] : [filtered_ count] + 1;
5985 - (float) table:(UITable *)table heightForRow:(int)row {
5989 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
5991 reusing = [[[SectionCell alloc] init] autorelease];
5992 [(SectionCell *)reusing setSection:(editing_ ?
5993 [sections_ objectAtIndex:row] :
5994 (row == 0 ? nil : [filtered_ objectAtIndex:(row - 1)])
5995 ) editing:editing_];
5999 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6003 - (BOOL) table:(UITable *)table canSelectRow:(int)row {
6007 - (void) tableRowSelected:(NSNotification *)notification {
6008 int row = [[notification object] selectedRow];
6019 title = CYLocalize("ALL_PACKAGES");
6021 section = [filtered_ objectAtIndex:(row - 1)];
6022 name = [section name];
6025 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6028 title = CYLocalize("NO_SECTION");
6032 PackageTable *table = [[[FilteredPackageTable alloc]
6036 filter:@selector(isVisiblyUninstalledInSection:)
6040 [table setDelegate:delegate_];
6042 [book_ pushPage:table];
6045 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6046 if ((self = [super initWithBook:book]) != nil) {
6047 database_ = database;
6049 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6050 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6052 transition_ = [[UITransitionView alloc] initWithFrame:[self bounds]];
6053 [self addSubview:transition_];
6055 list_ = [[UITable alloc] initWithFrame:[transition_ bounds]];
6056 [transition_ transition:0 toView:list_];
6058 UITableColumn *column = [[[UITableColumn alloc]
6059 initWithTitle:CYLocalize("NAME")
6061 width:[self frame].size.width
6064 [list_ setDataSource:self];
6065 [list_ setSeparatorStyle:1];
6066 [list_ addTableColumn:column];
6067 [list_ setDelegate:self];
6068 [list_ setReusesTableCells:YES];
6072 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6073 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6077 - (void) reloadData {
6078 NSArray *packages = [database_ packages];
6080 [sections_ removeAllObjects];
6081 [filtered_ removeAllObjects];
6084 typedef __gnu_cxx::hash_map<NSString *, Section *, NSStringMapHash, NSStringMapEqual> SectionMap;
6085 SectionMap sections;
6086 sections.resize(64);
6088 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6092 for (Package *package in packages) {
6093 NSString *name([package section]);
6094 NSString *key(name == nil ? @"" : name);
6099 _profile(SectionsView$reloadData$Section)
6100 section = §ions[key];
6101 if (*section == nil) {
6102 _profile(SectionsView$reloadData$Section$Allocate)
6103 *section = [[[Section alloc] initWithName:name] autorelease];
6108 [*section addToCount];
6110 _profile(SectionsView$reloadData$Filter)
6111 if (![package valid] || [package installed] != nil || ![package visible])
6115 [*section addToRow];
6119 _profile(SectionsView$reloadData$Section)
6120 section = [sections objectForKey:key];
6121 if (section == nil) {
6122 _profile(SectionsView$reloadData$Section$Allocate)
6123 section = [[[Section alloc] initWithName:name] autorelease];
6124 [sections setObject:section forKey:key];
6129 [section addToCount];
6131 _profile(SectionsView$reloadData$Filter)
6132 if (![package valid] || [package installed] != nil || ![package visible])
6142 for (SectionMap::const_iterator i(sections.begin()), e(sections.end()); i != e; ++i)
6143 [sections_ addObject:i->second];
6145 [sections_ addObjectsFromArray:[sections allValues]];
6148 [sections_ sortUsingSelector:@selector(compareByName:)];
6150 for (Section *section in sections_) {
6151 size_t count([section row]);
6152 if ([section row] == 0)
6155 section = [[[Section alloc] initWithName:[section name]] autorelease];
6156 [section setCount:count];
6157 [filtered_ addObject:section];
6164 - (void) resetView {
6166 [self _rightButtonClicked];
6169 - (void) resetViewAnimated:(BOOL)animated {
6170 [list_ resetViewAnimated:animated];
6173 - (void) _rightButtonClicked {
6174 if ((editing_ = !editing_))
6177 [delegate_ updateData];
6178 [book_ reloadTitleForPage:self];
6179 [book_ reloadButtonsForPage:self];
6182 - (NSString *) title {
6183 return editing_ ? CYLocalize("SECTION_VISIBILITY") : CYLocalize("INSTALL_BY_SECTION");
6186 - (NSString *) backButtonTitle {
6187 return CYLocalize("SECTIONS");
6190 - (id) rightButtonTitle {
6191 return [sections_ count] == 0 ? nil : editing_ ? CYLocalize("DONE") : CYLocalize("EDIT");
6194 - (UINavigationButtonStyle) rightButtonStyle {
6195 return editing_ ? UINavigationButtonStyleHighlighted : UINavigationButtonStyleNormal;
6198 - (UIView *) accessoryView {
6204 /* Changes View {{{ */
6205 @interface ChangesView : RVPage {
6206 _transient Database *database_;
6207 NSMutableArray *packages_;
6208 NSMutableArray *sections_;
6209 UISectionList *list_;
6213 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6214 - (void) reloadData;
6218 @implementation ChangesView
6221 [[list_ table] setDelegate:nil];
6222 [list_ setDataSource:nil];
6224 [packages_ release];
6225 [sections_ release];
6230 - (int) numberOfSectionsInSectionList:(UISectionList *)list {
6231 return [sections_ count];
6234 - (NSString *) sectionList:(UISectionList *)list titleForSection:(int)section {
6235 return [[sections_ objectAtIndex:section] name];
6238 - (int) sectionList:(UISectionList *)list rowForSection:(int)section {
6239 return [[sections_ objectAtIndex:section] row];
6242 - (int) numberOfRowsInTable:(UITable *)table {
6243 return [packages_ count];
6246 - (float) table:(UITable *)table heightForRow:(int)row {
6247 return [PackageCell heightForPackage:[packages_ objectAtIndex:row]];
6250 - (UITableCell *) table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col reusing:(UITableCell *)reusing {
6252 reusing = [[[PackageCell alloc] init] autorelease];
6253 [(PackageCell *)reusing setPackage:[packages_ objectAtIndex:row]];
6257 - (BOOL) table:(UITable *)table showDisclosureForRow:(int)row {
6261 - (void) tableRowSelected:(NSNotification *)notification {
6262 int row = [[notification object] selectedRow];
6265 Package *package = [packages_ objectAtIndex:row];
6266 PackageView *view([delegate_ packageView]);
6267 [view setDelegate:delegate_];
6268 [view setPackage:package];
6269 [book_ pushPage:view];
6272 - (void) _leftButtonClicked {
6273 [(CYBook *)book_ update];
6274 [self reloadButtons];
6277 - (void) _rightButtonClicked {
6278 [delegate_ distUpgrade];
6281 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6282 if ((self = [super initWithBook:book]) != nil) {
6283 database_ = database;
6285 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6286 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6288 list_ = [[UISectionList alloc] initWithFrame:[self bounds] showSectionIndex:NO];
6289 [self addSubview:list_];
6291 [list_ setShouldHideHeaderInShortLists:NO];
6292 [list_ setDataSource:self];
6293 //[list_ setSectionListStyle:1];
6295 UITableColumn *column = [[[UITableColumn alloc]
6296 initWithTitle:CYLocalize("NAME")
6298 width:[self frame].size.width
6301 UITable *table = [list_ table];
6302 [table setSeparatorStyle:1];
6303 [table addTableColumn:column];
6304 [table setDelegate:self];
6305 [table setReusesTableCells:YES];
6309 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6310 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6314 - (void) reloadData {
6315 NSArray *packages = [database_ packages];
6317 [packages_ removeAllObjects];
6318 [sections_ removeAllObjects];
6321 for (Package *package in packages)
6323 [package installed] == nil && [package valid] && [package visible] ||
6324 [package upgradableAndEssential:YES]
6326 [packages_ addObject:package];
6329 [packages_ radixSortUsingFunction:reinterpret_cast<uint32_t (*)(id, void *)>(&PackageChangesRadix) withArgument:NULL];
6332 Section *upgradable = [[[Section alloc] initWithName:CYLocalize("AVAILABLE_UPGRADES")] autorelease];
6333 Section *ignored = [[[Section alloc] initWithName:CYLocalize("IGNORED_UPGRADES")] autorelease];
6334 Section *section = nil;
6338 bool unseens = false;
6340 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
6343 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
6344 Package *package = [packages_ objectAtIndex:offset];
6347 _profile(ChangesView$reloadData$Upgrade)
6348 uae = [package upgradableAndEssential:YES];
6355 _profile(ChangesView$reloadData$Remember)
6356 seen = [package seen];
6360 _profile(ChangesView$reloadData$Compare)
6361 different = section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame);
6369 name = CYLocalize("UNKNOWN");
6371 _profile(ChangesView$reloadData$Format)
6372 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
6378 _profile(ChangesView$reloadData$Allocate)
6379 name = [NSString stringWithFormat:CYLocalize("NEW_AT"), name];
6380 section = [[[Section alloc] initWithName:name row:offset] autorelease];
6381 [sections_ addObject:section];
6385 [section addToCount];
6386 } else if ([package ignored])
6387 [ignored addToCount];
6390 [upgradable addToCount];
6395 CFRelease(formatter);
6398 Section *last = [sections_ lastObject];
6399 size_t count = [last count];
6400 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
6401 [sections_ removeLastObject];
6404 if ([ignored count] != 0)
6405 [sections_ insertObject:ignored atIndex:0];
6407 [sections_ insertObject:upgradable atIndex:0];
6410 [self reloadButtons];
6413 - (void) resetViewAnimated:(BOOL)animated {
6414 [list_ resetViewAnimated:animated];
6417 - (NSString *) leftButtonTitle {
6418 return [(CYBook *)book_ updating] ? nil : CYLocalize("REFRESH");
6421 - (id) rightButtonTitle {
6422 return upgrades_ == 0 ? nil : [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]];
6425 - (NSString *) title {
6426 return CYLocalize("CHANGES");
6431 /* Search View {{{ */
6432 @protocol SearchViewDelegate
6433 - (void) showKeyboard:(BOOL)show;
6436 @interface SearchView : RVPage {
6438 UISearchField *field_;
6439 UITransitionView *transition_;
6440 FilteredPackageTable *table_;
6441 UIPreferencesTable *advanced_;
6447 - (id) initWithBook:(RVBook *)book database:(Database *)database;
6448 - (void) reloadData;
6452 @implementation SearchView
6455 [field_ setDelegate:nil];
6457 [accessory_ release];
6459 [transition_ release];
6461 [advanced_ release];
6466 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6470 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6472 case 0: return [NSString stringWithFormat:CYLocalize("PARENTHETICAL"), CYLocalize("ADVANCED_SEARCH"), CYLocalize("COMING_SOON")];
6474 default: _assert(false);
6478 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6482 default: _assert(false);
6486 - (void) _showKeyboard:(BOOL)show {
6487 CGSize keysize = [UIKeyboard defaultSize];
6488 CGRect keydown = [book_ pageBounds];
6489 CGRect keyup = keydown;
6490 keyup.size.height -= keysize.height - ButtonBarHeight_;
6492 float delay = KeyboardTime_ * ButtonBarHeight_ / keysize.height;
6494 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:[table_ list]] autorelease];
6495 [animation setSignificantRectFields:8];
6498 [animation setStartFrame:keydown];
6499 [animation setEndFrame:keyup];
6501 [animation setStartFrame:keyup];
6502 [animation setEndFrame:keydown];
6505 UIAnimator *animator = [UIAnimator sharedAnimator];
6508 addAnimations:[NSArray arrayWithObjects:animation, nil]
6509 withDuration:(KeyboardTime_ - delay)
6514 [animator performSelector:@selector(startAnimation:) withObject:animation afterDelay:delay];
6516 [delegate_ showKeyboard:show];
6519 - (void) textFieldDidBecomeFirstResponder:(UITextField *)field {
6520 [self _showKeyboard:YES];
6523 - (void) textFieldDidResignFirstResponder:(UITextField *)field {
6524 [self _showKeyboard:NO];
6527 - (void) keyboardInputChanged:(UIFieldEditor *)editor {
6529 NSString *text([field_ text]);
6530 [field_ setClearButtonStyle:(text == nil || [text length] == 0 ? 0 : 2)];
6536 - (void) textFieldClearButtonPressed:(UITextField *)field {
6540 - (void) keyboardInputShouldDelete:(id)input {
6544 - (BOOL) keyboardInput:(id)input shouldInsertText:(NSString *)text isMarkedText:(int)marked {
6545 if ([text length] != 1 || [text characterAtIndex:0] != '\n') {
6549 [field_ resignFirstResponder];
6554 - (id) initWithBook:(RVBook *)book database:(Database *)database {
6555 if ((self = [super initWithBook:book]) != nil) {
6556 CGRect pageBounds = [book_ pageBounds];
6558 transition_ = [[UITransitionView alloc] initWithFrame:pageBounds];
6559 [self addSubview:transition_];
6561 advanced_ = [[UIPreferencesTable alloc] initWithFrame:pageBounds];
6563 [advanced_ setReusesTableCells:YES];
6564 [advanced_ setDataSource:self];
6565 [advanced_ reloadData];
6567 dimmed_ = [[UIView alloc] initWithFrame:pageBounds];
6568 CGColor dimmed(space_, 0, 0, 0, 0.5);
6569 [dimmed_ setBackgroundColor:[UIColor colorWithCGColor:dimmed]];
6571 table_ = [[FilteredPackageTable alloc]
6575 filter:@selector(isUnfilteredAndSearchedForBy:)
6579 [table_ setShouldHideHeaderInShortLists:NO];
6580 [transition_ transition:0 toView:table_];
6589 area.origin.x = /*cnfrect.origin.x + cnfrect.size.width + 4 +*/ 10;
6596 [self bounds].size.width - area.origin.x - 18;
6598 area.size.height = [UISearchField defaultHeight];
6600 field_ = [[UISearchField alloc] initWithFrame:area];
6602 UIFont *font = [UIFont systemFontOfSize:16];
6603 [field_ setFont:font];
6605 [field_ setPlaceholder:CYLocalize("SEARCH_EX")];
6606 [field_ setDelegate:self];
6608 [field_ setPaddingTop:5];
6610 UITextInputTraits *traits([field_ textInputTraits]);
6611 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6612 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6613 [traits setReturnKeyType:UIReturnKeySearch];
6615 CGRect accrect = {{0, 6}, {6 + cnfrect.size.width + 6 + area.size.width + 6, area.size.height}};
6617 accessory_ = [[UIView alloc] initWithFrame:accrect];
6618 [accessory_ addSubview:field_];
6620 /*UIPushButton *configure = [[[UIPushButton alloc] initWithFrame:cnfrect] autorelease];
6621 [configure setShowPressFeedback:YES];
6622 [configure setImage:[UIImage applicationImageNamed:@"advanced.png"]];
6623 [configure addTarget:self action:@selector(configurePushed) forEvents:1];
6624 [accessory_ addSubview:configure];*/
6626 [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6627 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
6633 LKAnimation *animation = [LKTransition animation];
6634 [animation setType:@"oglFlip"];
6635 [animation setTimingFunction:[LKTimingFunction functionWithName:@"easeInEaseOut"]];
6636 [animation setFillMode:@"extended"];
6637 [animation setTransitionFlags:3];
6638 [animation setDuration:10];
6639 [animation setSpeed:0.35];
6640 [animation setSubtype:(flipped_ ? @"fromLeft" : @"fromRight")];
6641 [[transition_ _layer] addAnimation:animation forKey:0];
6642 [transition_ transition:0 toView:(flipped_ ? (UIView *) table_ : (UIView *) advanced_)];
6643 flipped_ = !flipped_;
6647 - (void) configurePushed {
6648 [field_ resignFirstResponder];
6652 - (void) resetViewAnimated:(BOOL)animated {
6655 [table_ resetViewAnimated:animated];
6658 - (void) _reloadData {
6661 - (void) reloadData {
6664 [table_ setObject:[field_ text]];
6665 _profile(SearchView$reloadData)
6666 [table_ reloadData];
6669 [table_ resetCursor];
6672 - (UIView *) accessoryView {
6676 - (NSString *) title {
6680 - (NSString *) backButtonTitle {
6681 return CYLocalize("SEARCH");
6684 - (void) setDelegate:(id)delegate {
6685 [table_ setDelegate:delegate];
6686 [super setDelegate:delegate];
6692 @interface SettingsView : RVPage {
6693 _transient Database *database_;
6696 UIPreferencesTable *table_;
6697 _UISwitchSlider *subscribedSwitch_;
6698 _UISwitchSlider *ignoredSwitch_;
6699 UIPreferencesControlTableCell *subscribedCell_;
6700 UIPreferencesControlTableCell *ignoredCell_;
6703 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6707 @implementation SettingsView
6710 [table_ setDataSource:nil];
6713 if (package_ != nil)
6716 [subscribedSwitch_ release];
6717 [ignoredSwitch_ release];
6718 [subscribedCell_ release];
6719 [ignoredCell_ release];
6723 - (int) numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table {
6724 if (package_ == nil)
6730 - (NSString *) preferencesTable:(UIPreferencesTable *)table titleForGroup:(int)group {
6731 if (package_ == nil)
6738 default: _assert(false);
6744 - (BOOL) preferencesTable:(UIPreferencesTable *)table isLabelGroup:(int)group {
6745 if (package_ == nil)
6752 default: _assert(false);
6758 - (int) preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group {
6759 if (package_ == nil)
6766 default: _assert(false);
6772 - (void) onSomething:(UIPreferencesControlTableCell *)cell withKey:(NSString *)key {
6773 if (package_ == nil)
6776 _UISwitchSlider *slider([cell control]);
6777 BOOL value([slider value] != 0);
6778 NSMutableDictionary *metadata([package_ metadata]);
6781 if (NSNumber *number = [metadata objectForKey:key])
6782 before = [number boolValue];
6786 if (value != before) {
6787 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
6789 [delegate_ updateData];
6793 - (void) onSubscribed:(UIPreferencesControlTableCell *)cell {
6794 [self onSomething:cell withKey:@"IsSubscribed"];
6797 - (void) onIgnored:(UIPreferencesControlTableCell *)cell {
6798 [self onSomething:cell withKey:@"IsIgnored"];
6801 - (id) preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group {
6802 if (package_ == nil)
6806 case 0: switch (row) {
6808 return subscribedCell_;
6810 return ignoredCell_;
6811 default: _assert(false);
6814 case 1: switch (row) {
6816 UIPreferencesControlTableCell *cell([[[UIPreferencesControlTableCell alloc] init] autorelease]);
6817 [cell setShowSelection:NO];
6818 [cell setTitle:CYLocalize("SHOW_ALL_CHANGES_EX")];
6822 default: _assert(false);
6825 default: _assert(false);
6831 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
6832 if ((self = [super initWithBook:book])) {
6833 database_ = database;
6834 name_ = [package retain];
6836 table_ = [[UIPreferencesTable alloc] initWithFrame:[self bounds]];
6837 [self addSubview:table_];
6839 subscribedSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
6840 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:kUIControlEventMouseUpInside];
6842 ignoredSwitch_ = [[_UISwitchSlider alloc] initWithFrame:CGRectMake(200, 10, 50, 20)];
6843 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:kUIControlEventMouseUpInside];
6845 subscribedCell_ = [[UIPreferencesControlTableCell alloc] init];
6846 [subscribedCell_ setShowSelection:NO];
6847 [subscribedCell_ setTitle:CYLocalize("SHOW_ALL_CHANGES")];
6848 [subscribedCell_ setControl:subscribedSwitch_];
6850 ignoredCell_ = [[UIPreferencesControlTableCell alloc] init];
6851 [ignoredCell_ setShowSelection:NO];
6852 [ignoredCell_ setTitle:CYLocalize("IGNORE_UPGRADES")];
6853 [ignoredCell_ setControl:ignoredSwitch_];
6855 [table_ setDataSource:self];
6860 - (void) resetViewAnimated:(BOOL)animated {
6861 [table_ resetViewAnimated:animated];
6864 - (void) reloadData {
6865 if (package_ != nil)
6866 [package_ autorelease];
6867 package_ = [database_ packageWithName:name_];
6868 if (package_ != nil) {
6870 [subscribedSwitch_ setValue:([package_ subscribed] ? 1 : 0) animated:NO];
6871 [ignoredSwitch_ setValue:([package_ ignored] ? 1 : 0) animated:NO];
6874 [table_ reloadData];
6877 - (NSString *) title {
6878 return CYLocalize("SETTINGS");
6883 /* Signature View {{{ */
6884 @interface SignatureView : BrowserView {
6885 _transient Database *database_;
6889 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package;
6893 @implementation SignatureView
6900 - (void) webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
6902 [super webView:sender didClearWindowObject:window forFrame:frame];
6905 - (id) initWithBook:(RVBook *)book database:(Database *)database package:(NSString *)package {
6906 if ((self = [super initWithBook:book]) != nil) {
6907 database_ = database;
6908 package_ = [package retain];
6913 - (void) resetViewAnimated:(BOOL)animated {
6916 - (void) reloadData {
6917 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
6923 @interface Cydia : UIApplication <
6924 ConfirmationViewDelegate,
6925 ProgressViewDelegate,
6934 UIToolbar *buttonbar_;
6938 NSMutableArray *essential_;
6939 NSMutableArray *broken_;
6941 Database *database_;
6942 ProgressView *progress_;
6946 UIKeyboard *keyboard_;
6947 UIProgressHUD *hud_;
6949 SectionsView *sections_;
6950 ChangesView *changes_;
6951 ManageView *manage_;
6952 SearchView *search_;
6954 PackageView *package_;
6959 @implementation Cydia
6962 if ([broken_ count] != 0) {
6963 int count = [broken_ count];
6965 UIActionSheet *sheet = [[[UIActionSheet alloc]
6966 initWithTitle:(count == 1 ? CYLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:CYLocalize("HALFINSTALLED_PACKAGES"), count])
6967 buttons:[NSArray arrayWithObjects:
6968 CYLocalize("FORCIBLY_CLEAR"),
6969 CYLocalize("TEMPORARY_IGNORE"),
6971 defaultButtonIndex:0
6976 [sheet setBodyText:CYLocalize("HALFINSTALLED_PACKAGE_EX")];
6977 [sheet popupAlertAnimated:YES];
6978 } else if (!Ignored_ && [essential_ count] != 0) {
6979 int count = [essential_ count];
6981 UIActionSheet *sheet = [[[UIActionSheet alloc]
6982 initWithTitle:(count == 1 ? CYLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:CYLocalize("ESSENTIAL_UPGRADES"), count])
6983 buttons:[NSArray arrayWithObjects:
6984 CYLocalize("UPGRADE_ESSENTIAL"),
6985 CYLocalize("COMPLETE_UPGRADE"),
6986 CYLocalize("TEMPORARY_IGNORE"),
6988 defaultButtonIndex:0
6993 [sheet setBodyText:CYLocalize("ESSENTIAL_UPGRADE_EX")];
6994 [sheet popupAlertAnimated:YES];
6998 - (void) _reloadData {
7001 static bool loaded(false);
7002 UIProgressHUD *hud([self addProgressHUD]);
7003 [hud setText:(loaded ? CYLocalize("RELOADING_DATA") : CYLocalize("LOADING_DATA"))];
7006 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
7009 [self removeProgressHUD:hud];
7013 [essential_ removeAllObjects];
7014 [broken_ removeAllObjects];
7016 NSArray *packages = [database_ packages];
7017 for (Package *package in packages) {
7019 [broken_ addObject:package];
7020 if ([package upgradableAndEssential:NO]) {
7021 if ([package essential])
7022 [essential_ addObject:package];
7028 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
7029 [buttonbar_ setBadgeValue:badge forButton:3];
7030 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7031 [buttonbar_ setBadgeAnimated:([essential_ count] != 0) forButton:3];
7032 if ([self respondsToSelector:@selector(setApplicationBadge:)])
7033 [self setApplicationBadge:badge];
7035 [self setApplicationBadgeString:badge];
7037 [buttonbar_ setBadgeValue:nil forButton:3];
7038 if ([buttonbar_ respondsToSelector:@selector(setBadgeAnimated:forButton:)])
7039 [buttonbar_ setBadgeAnimated:NO forButton:3];
7040 if ([self respondsToSelector:@selector(removeApplicationBadge)])
7041 [self removeApplicationBadge];
7042 else // XXX: maybe use setApplicationBadgeString also?
7043 [self setApplicationIconBadgeNumber:0];
7047 [buttonbar_ setBadgeValue:nil forButton:4];
7051 // XXX: what is this line of code for?
7052 if ([packages count] == 0);
7053 else if (Loaded_ || ManualRefresh) loaded:
7058 if (NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]) {
7059 NSTimeInterval interval([update timeIntervalSinceNow]);
7060 if (interval <= 0 && interval > -600)
7068 - (void) _saveConfig {
7071 NSString *error(nil);
7072 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7074 NSError *error(nil);
7075 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7076 NSLog(@"failure to save metadata data: %@", error);
7079 NSLog(@"failure to serialize metadata: %@", error);
7087 - (void) updateData {
7090 /* XXX: this is just stupid */
7091 if (tag_ != 2 && sections_ != nil)
7092 [sections_ reloadData];
7093 if (tag_ != 3 && changes_ != nil)
7094 [changes_ reloadData];
7095 if (tag_ != 5 && search_ != nil)
7096 [search_ reloadData];
7106 FILE *file = fopen("/etc/apt/sources.list.d/cydia.list", "w");
7107 _assert(file != NULL);
7109 NSArray *keys = [Sources_ allKeys];
7111 for (NSString *key in keys) {
7112 NSDictionary *source = [Sources_ objectForKey:key];
7114 fprintf(file, "%s %s %s\n",
7115 [[source objectForKey:@"Type"] UTF8String],
7116 [[source objectForKey:@"URI"] UTF8String],
7117 [[source objectForKey:@"Distribution"] UTF8String]
7126 detachNewThreadSelector:@selector(update_)
7129 title:CYLocalize("UPDATING_SOURCES")
7133 - (void) reloadData {
7134 @synchronized (self) {
7135 if (confirm_ == nil)
7141 pkgProblemResolver *resolver = [database_ resolver];
7143 resolver->InstallProtect();
7144 if (!resolver->Resolve(true))
7148 - (void) popUpBook:(RVBook *)book {
7149 [underlay_ popSubview:book];
7152 - (CGRect) popUpBounds {
7153 return [underlay_ bounds];
7157 [database_ prepare];
7159 confirm_ = [[RVBook alloc] initWithFrame:[self popUpBounds]];
7160 [confirm_ setDelegate:self];
7162 ConfirmationView *page([[[ConfirmationView alloc] initWithBook:confirm_ database:database_] autorelease]);
7163 [page setDelegate:self];
7165 [confirm_ setPage:page];
7166 [self popUpBook:confirm_];
7170 @synchronized (self) {
7175 - (void) clearPackage:(Package *)package {
7176 @synchronized (self) {
7183 - (void) installPackage:(Package *)package {
7184 @synchronized (self) {
7191 - (void) removePackage:(Package *)package {
7192 @synchronized (self) {
7199 - (void) distUpgrade {
7200 @synchronized (self) {
7201 [database_ upgrade];
7207 [self slideUp:[[[UIActionSheet alloc]
7209 buttons:[NSArray arrayWithObjects:CYLocalize("CONTINUE_QUEUING"), CYLocalize("CANCEL_CLEAR"), nil]
7210 defaultButtonIndex:1
7217 @synchronized (self) {
7220 if (confirm_ != nil) {
7228 [overlay_ removeFromSuperview];
7232 detachNewThreadSelector:@selector(perform)
7235 title:CYLocalize("RUNNING")
7239 - (void) bootstrap_ {
7241 [database_ upgrade];
7242 [database_ prepare];
7243 [database_ perform];
7246 /* XXX: replace and localize */
7247 - (void) bootstrap {
7249 detachNewThreadSelector:@selector(bootstrap_)
7252 title:@"Bootstrap Install"
7256 - (void) progressViewIsComplete:(ProgressView *)progress {
7257 if (confirm_ != nil) {
7258 [underlay_ addSubview:overlay_];
7259 [confirm_ popFromSuperviewAnimated:NO];
7265 - (void) setPage:(RVPage *)page {
7266 [page resetViewAnimated:NO];
7267 [page setDelegate:self];
7268 [book_ setPage:page];
7271 - (RVPage *) _pageForURL:(NSURL *)url withClass:(Class)_class {
7272 BrowserView *browser = [[[_class alloc] initWithBook:book_] autorelease];
7273 [browser loadURL:url];
7277 - (void) _setHomePage {
7278 [self setPage:[self _pageForURL:[NSURL URLWithString:@"http://cydia.saurik.com/"] withClass:[HomeView class]]];
7281 - (SectionsView *) sectionsView {
7282 if (sections_ == nil)
7283 sections_ = [[SectionsView alloc] initWithBook:book_ database:database_];
7287 - (void) buttonBarItemTapped:(id)sender {
7288 unsigned tag = [sender tag];
7290 [book_ resetViewAnimated:YES];
7292 } else if (tag_ == 2 && tag != 2)
7293 [[self sectionsView] resetView];
7296 case 1: [self _setHomePage]; break;
7298 case 2: [self setPage:[self sectionsView]]; break;
7299 case 3: [self setPage:changes_]; break;
7300 case 4: [self setPage:manage_]; break;
7301 case 5: [self setPage:search_]; break;
7303 default: _assert(false);
7309 - (void) applicationWillSuspend {
7311 [super applicationWillSuspend];
7314 - (void) askForSettings {
7315 NSString *parenthetical(CYLocalize("PARENTHETICAL"));
7317 UIActionSheet *role = [[[UIActionSheet alloc]
7318 initWithTitle:CYLocalize("WHO_ARE_YOU")
7319 buttons:[NSArray arrayWithObjects:
7320 [NSString stringWithFormat:parenthetical, CYLocalize("USER"), CYLocalize("USER_EX")],
7321 [NSString stringWithFormat:parenthetical, CYLocalize("HACKER"), CYLocalize("HACKER_EX")],
7322 [NSString stringWithFormat:parenthetical, CYLocalize("DEVELOPER"), CYLocalize("DEVELOPER_EX")],
7324 defaultButtonIndex:-1
7329 [role setBodyText:CYLocalize("ROLE_EX")];
7330 [role popupAlertAnimated:YES];
7333 - (void) setPackageView:(PackageView *)view {
7334 if (package_ == nil)
7335 package_ = [view retain];
7338 - (PackageView *) packageView {
7341 if (package_ == nil)
7342 view = [[[PackageView alloc] initWithBook:book_ database:database_] autorelease];
7345 view = [package_ autorelease];
7354 [self setStatusBarShowsProgress:NO];
7355 [self removeProgressHUD:hud_];
7360 pid_t pid = ExecFork();
7362 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
7363 perror("launchctl stop");
7370 [self askForSettings];
7375 overlay_ = [[UIView alloc] initWithFrame:[underlay_ bounds]];
7377 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7378 book_ = [[CYBook alloc] initWithFrame:CGRectMake(
7379 0, 0, screenrect.size.width, screenrect.size.height - 48
7380 ) database:database_];
7382 [book_ setDelegate:self];
7384 [overlay_ addSubview:book_];
7386 NSArray *buttonitems = [NSArray arrayWithObjects:
7387 [NSDictionary dictionaryWithObjectsAndKeys:
7388 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7389 @"home-up.png", kUIButtonBarButtonInfo,
7390 @"home-dn.png", kUIButtonBarButtonSelectedInfo,
7391 [NSNumber numberWithInt:1], kUIButtonBarButtonTag,
7392 self, kUIButtonBarButtonTarget,
7393 CYLocalize("HOME"), kUIButtonBarButtonTitle,
7394 @"0", kUIButtonBarButtonType,
7397 [NSDictionary dictionaryWithObjectsAndKeys:
7398 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7399 @"install-up.png", kUIButtonBarButtonInfo,
7400 @"install-dn.png", kUIButtonBarButtonSelectedInfo,
7401 [NSNumber numberWithInt:2], kUIButtonBarButtonTag,
7402 self, kUIButtonBarButtonTarget,
7403 CYLocalize("SECTIONS"), kUIButtonBarButtonTitle,
7404 @"0", kUIButtonBarButtonType,
7407 [NSDictionary dictionaryWithObjectsAndKeys:
7408 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7409 @"changes-up.png", kUIButtonBarButtonInfo,
7410 @"changes-dn.png", kUIButtonBarButtonSelectedInfo,
7411 [NSNumber numberWithInt:3], kUIButtonBarButtonTag,
7412 self, kUIButtonBarButtonTarget,
7413 CYLocalize("CHANGES"), kUIButtonBarButtonTitle,
7414 @"0", kUIButtonBarButtonType,
7417 [NSDictionary dictionaryWithObjectsAndKeys:
7418 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7419 @"manage-up.png", kUIButtonBarButtonInfo,
7420 @"manage-dn.png", kUIButtonBarButtonSelectedInfo,
7421 [NSNumber numberWithInt:4], kUIButtonBarButtonTag,
7422 self, kUIButtonBarButtonTarget,
7423 CYLocalize("MANAGE"), kUIButtonBarButtonTitle,
7424 @"0", kUIButtonBarButtonType,
7427 [NSDictionary dictionaryWithObjectsAndKeys:
7428 @"buttonBarItemTapped:", kUIButtonBarButtonAction,
7429 @"search-up.png", kUIButtonBarButtonInfo,
7430 @"search-dn.png", kUIButtonBarButtonSelectedInfo,
7431 [NSNumber numberWithInt:5], kUIButtonBarButtonTag,
7432 self, kUIButtonBarButtonTarget,
7433 CYLocalize("SEARCH"), kUIButtonBarButtonTitle,
7434 @"0", kUIButtonBarButtonType,
7438 buttonbar_ = [[UIToolbar alloc]
7440 withFrame:CGRectMake(
7441 0, screenrect.size.height - ButtonBarHeight_,
7442 screenrect.size.width, ButtonBarHeight_
7444 withItemList:buttonitems
7447 [buttonbar_ setDelegate:self];
7448 [buttonbar_ setBarStyle:1];
7449 [buttonbar_ setButtonBarTrackingMode:2];
7451 int buttons[5] = {1, 2, 3, 4, 5};
7452 [buttonbar_ registerButtonGroup:0 withButtons:buttons withCount:5];
7453 [buttonbar_ showButtonGroup:0 withDuration:0];
7455 for (int i = 0; i != 5; ++i)
7456 [[buttonbar_ viewWithTag:(i + 1)] setFrame:CGRectMake(
7457 i * 64 + 2, 1, 60, ButtonBarHeight_
7460 [buttonbar_ showSelectionForButton:1];
7461 [overlay_ addSubview:buttonbar_];
7463 [UIKeyboard initImplementationNow];
7464 CGSize keysize = [UIKeyboard defaultSize];
7465 CGRect keyrect = {{0, [overlay_ bounds].size.height}, keysize};
7466 keyboard_ = [[UIKeyboard alloc] initWithFrame:keyrect];
7467 //[[UIKeyboardImpl sharedInstance] setSoundsEnabled:(Sounds_Keyboard_ ? YES : NO)];
7468 [overlay_ addSubview:keyboard_];
7471 [underlay_ addSubview:overlay_];
7475 [self sectionsView];
7476 changes_ = [[ChangesView alloc] initWithBook:book_ database:database_];
7477 search_ = [[SearchView alloc] initWithBook:book_ database:database_];
7479 manage_ = (ManageView *) [[self
7480 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
7481 withClass:[ManageView class]
7484 [self setPackageView:[self packageView]];
7491 [self _setHomePage];
7494 - (void) alertSheet:(UIActionSheet *)sheet buttonClicked:(int)button {
7495 NSString *context([sheet context]);
7497 if ([context isEqualToString:@"missing"])
7499 else if ([context isEqualToString:@"cancel"]) {
7517 @synchronized (self) {
7522 [buttonbar_ setBadgeValue:CYLocalize("Q_D") forButton:4];
7526 if (confirm_ != nil) {
7531 } else if ([context isEqualToString:@"fixhalf"]) {
7534 @synchronized (self) {
7535 for (Package *broken in broken_) {
7538 NSString *id = [broken id];
7539 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
7540 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
7541 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
7542 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
7551 [broken_ removeAllObjects];
7560 } else if ([context isEqualToString:@"role"]) {
7562 case 1: Role_ = @"User"; break;
7563 case 2: Role_ = @"Hacker"; break;
7564 case 3: Role_ = @"Developer"; break;
7571 bool reset = Settings_ != nil;
7573 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7577 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7587 } else if ([context isEqualToString:@"upgrade"]) {
7590 @synchronized (self) {
7591 for (Package *essential in essential_)
7592 [essential install];
7615 - (void) reorganize { _pooled
7616 system("/usr/libexec/cydia/free.sh");
7617 [self performSelectorOnMainThread:@selector(finish) withObject:nil waitUntilDone:NO];
7620 - (void) applicationSuspend:(__GSEvent *)event {
7621 if (hud_ == nil && ![progress_ isRunning])
7622 [super applicationSuspend:event];
7625 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
7627 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
7630 - (void) _setSuspended:(BOOL)value {
7632 [super _setSuspended:value];
7635 - (UIProgressHUD *) addProgressHUD {
7636 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
7637 [window_ setUserInteractionEnabled:NO];
7639 [progress_ addSubview:hud];
7643 - (void) removeProgressHUD:(UIProgressHUD *)hud {
7645 [hud removeFromSuperview];
7646 [window_ setUserInteractionEnabled:YES];
7649 - (void) openMailToURL:(NSURL *)url {
7650 // XXX: this makes me sad
7652 [[[MailToView alloc] initWithView:underlay_ delegate:self url:url] autorelease];
7654 [UIApp openURL:url];// asPanel:YES];
7658 - (void) clearFirstResponder {
7659 if (id responder = [window_ firstResponder])
7660 [responder resignFirstResponder];
7663 - (RVPage *) pageForPackage:(NSString *)name {
7664 if (Package *package = [database_ packageWithName:name]) {
7665 PackageView *view([self packageView]);
7666 [view setPackage:package];
7669 UIActionSheet *sheet = [[[UIActionSheet alloc]
7670 initWithTitle:CYLocalize("CANNOT_LOCATE_PACKAGE")
7671 buttons:[NSArray arrayWithObjects:CYLocalize("CLOSE"), nil]
7672 defaultButtonIndex:0
7677 [sheet setBodyText:[NSString stringWithFormat:CYLocalize("PACKAGE_CANNOT_BE_FOUND"), name]];
7679 [sheet popupAlertAnimated:YES];
7684 - (RVPage *) pageForURL:(NSURL *)url hasTag:(int *)tag {
7688 NSString *scheme([[url scheme] lowercaseString]);
7689 if (![scheme isEqualToString:@"cydia"])
7691 NSString *path([url absoluteString]);
7692 if ([path length] < 8)
7694 path = [path substringFromIndex:8];
7695 if (![path hasPrefix:@"/"])
7696 path = [@"/" stringByAppendingString:path];
7698 if ([path isEqualToString:@"/add-source"])
7699 return [[[AddSourceView alloc] initWithBook:book_ database:database_] autorelease];
7700 else if ([path isEqualToString:@"/storage"])
7701 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[BrowserView class]];
7702 else if ([path isEqualToString:@"/sources"])
7703 return [[[SourceTable alloc] initWithBook:book_ database:database_] autorelease];
7704 else if ([path isEqualToString:@"/packages"])
7705 return [[[InstalledView alloc] initWithBook:book_ database:database_] autorelease];
7706 else if ([path hasPrefix:@"/url/"])
7707 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[BrowserView class]];
7708 else if ([path hasPrefix:@"/launch/"])
7709 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
7710 else if ([path hasPrefix:@"/package-settings/"])
7711 return [[[SettingsView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:18]] autorelease];
7712 else if ([path hasPrefix:@"/package-signature/"])
7713 return [[[SignatureView alloc] initWithBook:book_ database:database_ package:[path substringFromIndex:19]] autorelease];
7714 else if ([path hasPrefix:@"/package/"])
7715 return [self pageForPackage:[path substringFromIndex:9]];
7716 else if ([path hasPrefix:@"/files/"]) {
7717 NSString *name = [path substringFromIndex:7];
7719 if (Package *package = [database_ packageWithName:name]) {
7720 FileTable *files = [[[FileTable alloc] initWithBook:book_ database:database_] autorelease];
7721 [files setPackage:package];
7729 - (void) applicationOpenURL:(NSURL *)url {
7730 [super applicationOpenURL:url];
7732 if (RVPage *page = [self pageForURL:url hasTag:&tag]) {
7733 [self setPage:page];
7734 [buttonbar_ showSelectionForButton:tag];
7739 - (void) applicationDidFinishLaunching:(id)unused {
7741 Font12_ = [[UIFont systemFontOfSize:12] retain];
7742 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
7743 Font14_ = [[UIFont systemFontOfSize:14] retain];
7744 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
7745 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
7747 _assert(pkgInitConfig(*_config));
7748 _assert(pkgInitSystem(*_config, _system));
7752 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
7753 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
7755 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
7757 CGRect screenrect = [UIHardware fullScreenApplicationContentRect];
7758 window_ = [[UIWindow alloc] initWithContentRect:screenrect];
7760 [window_ orderFront:self];
7761 [window_ makeKey:self];
7762 [window_ setHidden:NO];
7764 database_ = [Database sharedInstance];
7765 progress_ = [[ProgressView alloc] initWithFrame:[window_ bounds] database:database_ delegate:self];
7766 [database_ setDelegate:progress_];
7767 [window_ setContentView:progress_];
7769 underlay_ = [[UIView alloc] initWithFrame:[progress_ bounds]];
7770 [progress_ setContentView:underlay_];
7772 [progress_ resetView];
7775 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
7776 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
7777 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
7778 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
7779 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
7780 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL /*||
7781 readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL*/
7783 [self setIdleTimerDisabled:YES];
7785 hud_ = [[self addProgressHUD] retain];
7786 [hud_ setText:@"Reorganizing\n\nWill Automatically\nClose When Done"];
7788 [self setStatusBarShowsProgress:YES];
7791 detachNewThreadSelector:@selector(reorganize)
7799 - (void) showKeyboard:(BOOL)show {
7800 CGSize keysize = [UIKeyboard defaultSize];
7801 CGRect keydown = {{0, [overlay_ bounds].size.height}, keysize};
7802 CGRect keyup = keydown;
7803 keyup.origin.y -= keysize.height;
7805 UIFrameAnimation *animation = [[[UIFrameAnimation alloc] initWithTarget:keyboard_] autorelease];
7806 [animation setSignificantRectFields:2];
7809 [animation setStartFrame:keydown];
7810 [animation setEndFrame:keyup];
7811 [keyboard_ activate];
7813 [animation setStartFrame:keyup];
7814 [animation setEndFrame:keydown];
7815 [keyboard_ deactivate];
7818 [[UIAnimator sharedAnimator]
7819 addAnimations:[NSArray arrayWithObjects:animation, nil]
7820 withDuration:KeyboardTime_
7825 - (void) slideUp:(UIActionSheet *)alert {
7827 [alert presentSheetFromButtonBar:buttonbar_];
7829 [alert presentSheetInView:overlay_];
7834 void AddPreferences(NSString *plist) { _pooled
7835 NSMutableDictionary *settings = [[[NSMutableDictionary alloc] initWithContentsOfFile:plist] autorelease];
7836 _assert(settings != NULL);
7837 NSMutableArray *items = [settings objectForKey:@"items"];
7841 for (NSMutableDictionary *item in items) {
7842 NSString *label = [item objectForKey:@"label"];
7843 if (label != nil && [label isEqualToString:@"Cydia"]) {
7850 for (size_t i(0); i != [items count]; ++i) {
7851 NSDictionary *item([items objectAtIndex:i]);
7852 NSString *label = [item objectForKey:@"label"];
7853 if (label != nil && [label isEqualToString:@"General"]) {
7854 [items insertObject:[NSDictionary dictionaryWithObjectsAndKeys:
7855 @"CydiaSettings", @"bundle",
7856 @"PSLinkCell", @"cell",
7857 [NSNumber numberWithBool:YES], @"hasIcon",
7858 [NSNumber numberWithBool:YES], @"isController",
7860 nil] atIndex:(i + 1)];
7866 _assert([settings writeToFile:plist atomically:YES] == YES);
7871 id Alloc_(id self, SEL selector) {
7872 id object = alloc_(self, selector);
7873 lprintf("[%s]A-%p\n", self->isa->name, object);
7878 id Dealloc_(id self, SEL selector) {
7879 id object = dealloc_(self, selector);
7880 lprintf("[%s]D-%p\n", self->isa->name, object);
7884 Class $WebDefaultUIKitDelegate;
7886 void (*_UIWebDocumentView$_setUIKitDelegate$)(UIWebDocumentView *, SEL, id);
7888 void $UIWebDocumentView$_setUIKitDelegate$(UIWebDocumentView *self, SEL sel, id delegate) {
7889 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
7890 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
7891 return _UIWebDocumentView$_setUIKitDelegate$(self, sel, delegate);
7894 int main(int argc, char *argv[]) { _pooled
7897 /* Library Hacks {{{ */
7898 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
7900 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
7901 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
7902 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
7903 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
7904 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
7907 /* Set Locale {{{ */
7908 Locale_ = CFLocaleCopyCurrent();
7910 CFStringRef locale(CFLocaleGetIdentifier(Locale_));
7911 setenv("LANG", [(NSString *) locale UTF8String], true);
7914 // XXX: apr_app_initialize?
7917 /* Parse Arguments {{{ */
7918 bool substrate(false);
7924 for (int argi(1); argi != argc; ++argi)
7925 if (strcmp(argv[argi], "--") == 0) {
7927 argv[argi] = argv[0];
7933 for (int argi(1); argi != arge; ++argi)
7934 if (strcmp(args[argi], "--bootstrap") == 0)
7936 else if (strcmp(args[argi], "--substrate") == 0)
7939 fprintf(stderr, "unknown argument: %s\n", args[argi]);
7944 NSString *plist = [Home_ stringByAppendingString:@"/Library/Preferences/com.apple.preferences.sounds.plist"];
7945 if (NSDictionary *sounds = [NSDictionary dictionaryWithContentsOfFile:plist])
7946 if (NSNumber *keyboard = [sounds objectForKey:@"keyboard"])
7947 Sounds_Keyboard_ = [keyboard boolValue];
7950 App_ = [[NSBundle mainBundle] bundlePath];
7951 Home_ = NSHomeDirectory();
7956 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
7957 alloc_ = alloc->method_imp;
7958 alloc->method_imp = (IMP) &Alloc_;*/
7960 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
7961 dealloc_ = dealloc->method_imp;
7962 dealloc->method_imp = (IMP) &Dealloc_;*/
7967 size = sizeof(maxproc);
7968 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
7969 perror("sysctlbyname(\"kern.maxproc\", ?)");
7970 else if (maxproc < 64) {
7972 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
7973 perror("sysctlbyname(\"kern.maxproc\", #)");
7976 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
7977 char *machine = new char[size];
7978 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
7979 perror("sysctlbyname(\"hw.machine\", ?)");
7983 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
7985 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
7986 Build_ = [system objectForKey:@"ProductBuildVersion"];
7987 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
7988 Product_ = [info objectForKey:@"SafariProductVersion"];
7989 Safari_ = [info objectForKey:@"CFBundleVersion"];
7992 /*AddPreferences(@"/Applications/Preferences.app/Settings-iPhone.plist");
7993 AddPreferences(@"/Applications/Preferences.app/Settings-iPod.plist");*/
7995 /* Load Database {{{ */
7997 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
7999 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
8002 if (Metadata_ == NULL)
8003 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
8005 Settings_ = [Metadata_ objectForKey:@"Settings"];
8007 Packages_ = [Metadata_ objectForKey:@"Packages"];
8008 Sections_ = [Metadata_ objectForKey:@"Sections"];
8009 Sources_ = [Metadata_ objectForKey:@"Sources"];
8012 if (Settings_ != nil)
8013 Role_ = [Settings_ objectForKey:@"Role"];
8015 if (Packages_ == nil) {
8016 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
8017 [Metadata_ setObject:Packages_ forKey:@"Packages"];
8020 if (Sections_ == nil) {
8021 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
8022 [Metadata_ setObject:Sections_ forKey:@"Sections"];
8025 if (Sources_ == nil) {
8026 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
8027 [Metadata_ setObject:Sources_ forKey:@"Sources"];
8032 Documents_ = [[[NSMutableArray alloc] initWithCapacity:4] autorelease];
8035 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
8036 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
8037 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
8038 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
8040 if (access("/User", F_OK) != 0) {
8042 system("/usr/libexec/cydia/firmware.sh");
8046 _assert([[NSFileManager defaultManager]
8047 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
8048 withIntermediateDirectories:YES
8053 if (access("/tmp/cydia.chk", F_OK) == 0) {
8054 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
8055 _assert(errno == ENOENT);
8056 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
8057 _assert(errno == ENOENT);
8060 /* Color Choices {{{ */
8061 space_ = CGColorSpaceCreateDeviceRGB();
8063 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
8064 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
8065 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
8066 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
8067 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
8068 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
8069 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
8070 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
8071 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
8072 /*Purple_.Set(space_, 1.0, 0.3, 0.0, 1.0);
8073 Purplish_.Set(space_, 1.0, 0.6, 0.4, 1.0); ORANGE */
8074 /*Purple_.Set(space_, 1.0, 0.5, 0.0, 1.0);
8075 Purplish_.Set(space_, 1.0, 0.7, 0.2, 1.0); ORANGISH */
8076 /*Purple_.Set(space_, 0.5, 0.0, 0.7, 1.0);
8077 Purplish_.Set(space_, 0.7, 0.4, 0.8, 1.0); PURPLE */
8080 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
8081 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
8084 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
8086 /* UIKit Configuration {{{ */
8087 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
8088 if ($GSFontSetUseLegacyFontMetrics != NULL)
8089 $GSFontSetUseLegacyFontMetrics(YES);
8091 UIKeyboardDisableAutomaticAppearance();
8095 int value = UIApplicationMain(argc, argv, @"Cydia", @"Cydia");
8097 CGColorSpaceRelease(space_);